diff --git a/.changeset/start-compiler-yuku.md b/.changeset/start-compiler-yuku.md index 89e30a5585..7544d596ba 100644 --- a/.changeset/start-compiler-yuku.md +++ b/.changeset/start-compiler-yuku.md @@ -23,7 +23,7 @@ Start's Vite and Rsbuild plugins run on the new compiler core instead of Babel: - **Production builds answer HTTP calls only for server functions that client code imports.** A function only server code calls (another server function, a server route), or one returned to the client as data, is refused when called over HTTP. The dev server still answers such a call and warns once per function. - `serverFns.generateFunctionId` receives the server function's stable key (its export or variable name, e.g. `greetUser`) as `functionName`, instead of the generated handler name (`greetUser_createServerFn_handler`). Custom generators keyed on the old names must be updated. - Default production ids are shorter (22 characters). -- Server functions are recognised by binding through re-exports, namespaces, aliases, user factories and stored builders, whatever the code formatting (#7280). With SSR as the provider the handler stays in its module (one instance) and server-side callers call it directly (#7213, #8731). `createServerOnlyFn(...)` passed to `.handler()` works (#8446). Nested server functions are hoisted on the server when safe. +- Server functions are recognised by binding through re-exports, namespaces, aliases, user factories and stored builders, whatever the code formatting (#7280). With SSR as the provider a server function's module evaluates once and server-side callers call it directly (#7213, #8731); the modules only its handlers import still load on the first call, like before, without running the module's code again (a handler that writes state its module reads, or one in a module that awaits at its top level, loads with its module). `createServerOnlyFn(...)` passed to `.handler()` works (#8446). Nested server functions are hoisted on the server when safe. - Client middleware sees only the server function's id during SSR, as in the browser. - Vite `bundledDev`: lazy dependencies load, edits no longer crash the hot update, and SSR reflects edits (#8407, #8062, #7535). diff --git a/packages/router-utils/src/compiler/README.md b/packages/router-utils/src/compiler/README.md index 281a637ad7..04846232ef 100644 --- a/packages/router-utils/src/compiler/README.md +++ b/packages/router-utils/src/compiler/README.md @@ -18,7 +18,7 @@ re-parses, re-prints or reads another job's output. The plan yields: - the env module (the code returned for the requested id), - every derived module of the same source in that env: split chunks (`?tsr-split=…`), lazy shared modules, extracted exports (`?tsr-split=export~Name`), Hydrate chunks (`?tss-hydrate=…`), server-function provider modules - (`?tss-serverfn-split`), + (`?tss-serverfn-split`), server-function handler modules (`?tss-serverfn-handler`), - facts: surviving import edges (import protection), server-function registry entries, diagnostics, file dependencies, per-planner data. diff --git a/packages/router-utils/src/compiler/identity.ts b/packages/router-utils/src/compiler/identity.ts index b73e55cc5a..917da6bf7a 100644 --- a/packages/router-utils/src/compiler/identity.ts +++ b/packages/router-utils/src/compiler/identity.ts @@ -9,7 +9,13 @@ */ import { hash } from 'node:crypto' -export type DerivedKind = 'split' | 'shared' | 'export' | 'hydrate' | 'provider' +export type DerivedKind = + | 'split' + | 'shared' + | 'export' + | 'hydrate' + | 'provider' + | 'handler' export interface DerivedQuery { kind: DerivedKind @@ -42,6 +48,7 @@ export const OWNED_QUERY_KEYS = { split: 'tsr-split', hydrate: 'tss-hydrate', provider: 'tss-serverfn-split', + handler: 'tss-serverfn-handler', } as const const OWNED_KEY_SET = new Set(Object.values(OWNED_QUERY_KEYS)) @@ -77,6 +84,9 @@ function parseDerived(key: string, value: string): DerivedQuery | null { if (key === OWNED_QUERY_KEYS.provider) { return { kind: 'provider', value } } + if (key === OWNED_QUERY_KEYS.handler) { + return { kind: 'handler', value } + } if (key === OWNED_QUERY_KEYS.split) { if (value.startsWith('shared~')) { return { kind: 'shared', value: value.slice('shared~'.length) } @@ -103,6 +113,8 @@ function ownedQueryPair(q: DerivedQuery): string { return q.value ? `${OWNED_QUERY_KEYS.provider}=${q.value}` : OWNED_QUERY_KEYS.provider + case 'handler': + return OWNED_QUERY_KEYS.handler } } @@ -140,11 +152,23 @@ export function identify(hostId: string): SourceIdentity { } } -/** Adds the owned key to the canonical id's existing query; never reorders or drops foreign keys. */ +/** + * Adds the owned key to the canonical id's existing query; never reorders or + * drops foreign keys. A trailing language key (`Page.vue?vue&type=script&lang.ts`, + * how `@vitejs/plugin-vue` serves an SFC block) stays last: other plugins + * pick the transform by the id's ending. + */ export function deriveId(canonicalId: string, q: DerivedQuery): string { const { base, query, hash } = splitQuery(canonicalId) const pair = ownedQueryPair(q) - return `${base}?${query.length > 0 ? `${query}&` : ''}${pair}${hash}` + if (query.length === 0) { + return `${base}?${pair}${hash}` + } + const last = query.lastIndexOf('&') + 1 + if (/^lang\.\w+$/.test(query.slice(last))) { + return `${base}?${query.slice(0, last)}${pair}&${query.slice(last)}${hash}` + } + return `${base}?${query}&${pair}${hash}` } /** The glue specifier a sibling output uses to import from `target` (same directory, hostile basenames allowed). */ diff --git a/packages/router-utils/tests/identity.test.ts b/packages/router-utils/tests/identity.test.ts index 8dec00b7b8..6ed5d6ed79 100644 --- a/packages/router-utils/tests/identity.test.ts +++ b/packages/router-utils/tests/identity.test.ts @@ -60,6 +60,26 @@ describe('identity', () => { }) }) + it('keeps a trailing language key of a foreign query last', () => { + const sfc = '/app/Page.vue?vue&type=script&lang.ts' + const handler = deriveId(sfc, { kind: 'handler', value: '' }) + expect(handler).toBe( + '/app/Page.vue?vue&type=script&tss-serverfn-handler&lang.ts', + ) + expect(identify(handler)).toMatchObject({ + canonicalId: sfc, + derived: { kind: 'handler', value: '' }, + lang: 'ts', + }) + expect( + deriveId('/app/Page.vue?lang.tsx#f', { kind: 'split', value: 'a' }), + ).toBe('/app/Page.vue?tsr-split=a&lang.tsx#f') + // `lang` with a value is an ordinary key + expect(deriveId('/app/x.ts?lang=ts', { kind: 'handler', value: '' })).toBe( + '/app/x.ts?lang=ts&tss-serverfn-handler', + ) + }) + it('builds sibling specifiers with the query verbatim', () => { expect( siblingSpecifier('/app/dir/page.tsx?flavour=b&tsr-split=component'), diff --git a/packages/start-plugin-core/src/planners/start-env.ts b/packages/start-plugin-core/src/planners/start-env.ts index 2740fffe37..4ba0d3ba08 100644 --- a/packages/start-plugin-core/src/planners/start-env.ts +++ b/packages/start-plugin-core/src/planners/start-env.ts @@ -1,7 +1,10 @@ /** * The `start-env` planner (J4): Start's environment - * separation on the core's plan. Server fns become client/SSR stubs or keep - * their handler in place next to a generated `createServerRpc` export; + * separation on the core's plan. Server fns become client/SSR stubs, or + * keep their chain next to a generated `createServerRpc` export in the + * provider; an in-place provider (SSR) moves the handlers into one derived + * handler module it imports on the first call (what only handlers read + * loads then, once; everything else stays and is imported back); * middleware links, isomorphic implementations and env-only fns are * selected per env; `` children leave server envs; nested * server fns are hoisted on the server when that is safe, else refused at @@ -14,6 +17,7 @@ import { cleanOrphanedDeclarations, identifierBase, isPureExpression, + siblingSpecifier, stringLiteral, unwrapExpression, walk, @@ -466,6 +470,50 @@ function planStartEnv( return sym } + // ---- lazy handler module (in-place provider): one per defining module, loaded once on the first call + let handlerOut: OutputId | null = null + let handlerLoad: SymbolId | null = null + const lazyHandlerOutput = (): { out: OutputId; load: SymbolId } => { + if (handlerOut === null || handlerLoad === null) { + handlerOut = ctx.declareOutput({ + kind: 'custom', + key: 'handler', + derived: { kind: 'handler', value: '' }, + }) + const memo = names.alloc('tsrHandlers') + const load = names.alloc('tsrLoadHandlers') + const spec = siblingSpecifier(handlerOut.slice('derived:'.length)) + rewrites.addGenerated({ + body: [ + text( + 'let ', + { sym: memo.sym }, + '\nconst ', + { sym: load.sym }, + ' = () => (', + { sym: memo.sym }, + ' ??= import(', + ), + { + k: 'spec', + specifier: spec, + edgeKey: ctx.edgeKey(spec, 'dynamic', 'runtime'), + provenance: { origin: 'runtime' }, + form: 'dynamic', + }, + text('))\n'), + ], + declares: [memo.sym, load.sym], + effectful: false, + anchor: { k: 'after-header' }, + home: 'auto', + by, + }) + handlerLoad = load.sym + } + return { out: handlerOut, load: handlerLoad } + } + // ---- 1. link stripping on the client (serverFn validators, middleware server/validator) for (const chain of analysis.chains) { if (chain.unsupported) { @@ -557,6 +605,48 @@ function planStartEnv( } } + // Handlers that move to the lazy handler module (in-place provider). An env + // rewrite of exactly such a handler range (the handler is itself a + // createServerOnlyFn / createIsomorphicFn call) renders inside the + // handler module's unit instead of overriding the claim's placeholder. + const rangeKey = (r: Range) => `${r.start}:${r.end}` + const lazySites = new Set() + const lazyRanges = new Set() + const lazyEdits = new Map; reason: string }>() + if ( + role === 'provider' && + !providerOut && + sites.length > 0 && + // a module that awaits at its top level could await one of its own server fns while it + // evaluates: the handler module imports it back and would wait for it forever + !hasTopLevelAwait(ctx) + ) { + for (const site of sites) { + const h = site.handler + // a core fallback (the handler writes module state other code reads) keeps it in place + if ( + !ctx.fallbacks.some( + (f) => + f.kind === 'custom' && + f.range.start === h.start && + f.range.end === h.end, + ) + ) { + lazySites.add(site) + lazyRanges.add(rangeKey(rangeOf(h))) + } + } + } + /** Adds an env rewrite, unless it replaces exactly a lazy handler (then it applies in the handler module only). */ + const envEdit = (range: Range, body: Array, reason: string) => { + const k = rangeKey(range) + if (lazyRanges.has(k)) { + lazyEdits.set(k, { body, reason }) + return + } + rewrites.add({ range, body, scope: 'all-outputs', by, reason }) + } + // ---- 3. isomorphic fns const wantLink = isServer ? 'server' : 'client' for (const chain of analysis.chains) { @@ -583,37 +673,31 @@ function planStartEnv( chain.wrapped, chain.parent, ) - rewrites.add({ - range: rangeOf(X), - body: parens + envEdit( + rangeOf(X), + parens ? [text('('), slice(rangeOf(link.arg)), text(')')] : [slice(rangeOf(link.arg))], - scope: 'all-outputs', - by, - reason: `isomorphic ${wantLink} implementation`, - }) + `isomorphic ${wantLink} implementation`, + ) continue } if (chain.headIsFactoryCall) { const parens = needsParens('arrow', chain.wrapped, chain.parent) - rewrites.add({ - range: rangeOf(X), - body: [text(parens ? '(() => {})' : '() => {}')], - scope: 'all-outputs', - by, - reason: 'isomorphic fn without an implementation for this environment', - }) + envEdit( + rangeOf(X), + [text(parens ? '(() => {})' : '() => {}')], + 'isomorphic fn without an implementation for this environment', + ) continue } if (chain.links.length > 0) { // the implementation lives on the stored receiver (this module or another): strip this segment's links - rewrites.add({ - range: rangeOf(X), - body: [slice(rangeOf(chain.head))], - scope: 'all-outputs', - by, - reason: 'isomorphic links of the other environment', - }) + envEdit( + rangeOf(X), + [slice(rangeOf(chain.head))], + 'isomorphic links of the other environment', + ) } } @@ -634,26 +718,22 @@ function planStartEnv( continue } const parens = needsParens(unwrapExpression(c.arg), wrapped, parent) - rewrites.add({ - range: rangeOf(c.call), - body: parens + envEdit( + rangeOf(c.call), + parens ? [text('('), slice(rangeOf(c.arg)), text(')')] : [slice(rangeOf(c.arg))], - scope: 'all-outputs', - by, - reason: `${c.kind}-only implementation`, - }) + `${c.kind}-only implementation`, + ) } else { const message = `create${c.kind === 'server' ? 'Server' : 'Client'}OnlyFn() functions can only be called on the ${c.kind}!` const parens = needsParens('arrow', wrapped, parent) const stub = `() => { throw new Error(${stringLiteral(message, '"')}) }` - rewrites.add({ - range: rangeOf(c.call), - body: [text(parens ? `(${stub})` : stub)], - scope: 'all-outputs', - by, - reason: `${c.kind}-only stub`, - }) + envEdit( + rangeOf(c.call), + [text(parens ? `(${stub})` : stub)], + `${c.kind}-only stub`, + ) } } @@ -758,7 +838,8 @@ function planStartEnv( continue } } - // provider: the handler stays in place next to a generated createServerRpc export + // provider: the chain stays in place next to a generated createServerRpc export; an + // in-place provider's handler moves to the handler module, loaded on the first call const serverRpc = glueImport( specs.serverRpc, 'createServerRpc', @@ -779,13 +860,55 @@ function planStartEnv( anchor = hoisted!.anchor commitHoist = hoisted!.commit } - rewrites.add({ - range: { start: h.start, end: h.start }, - body: [text({ sym: rpcLocal.sym }, ', ')], - scope: providerScope, - by, - reason: 'server rpc wrapper argument', - }) + if (lazySites.has(site)) { + const { out, load } = lazyHandlerOutput() + const local = names.alloc(`tsrHandler$${identifierBase(site.stableKey)}`) + const owner = rewrites.addGenerated({ + body: [ + text('const ', { sym: local.sym }, ' = '), + slice(rangeOf(h)), + text('\nexport { ', { sym: local.sym }, ' }\n'), + ], + declares: [local.sym], + effectful: false, + anchor: { k: 'end' }, + home: out, + by, + }) + ctx.addRoot(out, { t: 'gen', id: owner }) + const rewritten = lazyEdits.get(rangeKey(rangeOf(h))) + if (rewritten) { + // the handler is itself an env-only / isomorphic call: rewritten in the handler module only + rewrites.add({ + range: rangeOf(h), + body: rewritten.body, + scope: [out], + by, + reason: rewritten.reason, + }) + } + rewrites.claim({ + region: ctx.region(rangeOf(h), 'custom'), + owner, + placeholder: [ + text( + { sym: rpcLocal.sym }, + ', (...args) => ', + { sym: load, ctx: 'callee' }, + `().then((m) => m.${local.name}(...args))`, + ), + ], + by, + }) + } else { + rewrites.add({ + range: { start: h.start, end: h.start }, + body: [text({ sym: rpcLocal.sym }, ', ')], + scope: providerScope, + by, + reason: 'server rpc wrapper argument', + }) + } const gen = rewrites.addGenerated({ body: [ text( @@ -859,6 +982,47 @@ function planStartEnv( ctx.setFacts(START_ENV, facts) } +/** + * Whether the module awaits at its top level (`await`, `for await`) outside + * any function. Only top-level statements whose text has `await` are walked. + */ +function hasTopLevelAwait(ctx: PlanContext): boolean { + const code = ctx.analysis.source.code + const hit = { found: false } + const skipFn = (_n: Node, w: { skip: () => void }) => w.skip() + let at = -1 + for (const statement of ctx.analysis.file.program.body) { + if (at < statement.start) { + at = code.indexOf('await', statement.start) + } + if (at === -1) { + return false + } + if (at >= statement.end) { + continue + } + walk(statement, { + FunctionDeclaration: skipFn, + FunctionExpression: skipFn, + ArrowFunctionExpression: skipFn, + AwaitExpression: (_n, w) => { + hit.found = true + w.stop() + }, + ForOfStatement: (n, w) => { + if (n.await) { + hit.found = true + w.stop() + } + }, + }) + if (hit.found) { + return true + } + } + return false +} + function serverFnFact( site: ServerFnSite, id: string, diff --git a/packages/start-plugin-core/src/rsbuild/COMPILER_ARCHITECTURE.md b/packages/start-plugin-core/src/rsbuild/COMPILER_ARCHITECTURE.md index 3748a3f00e..7ebf002dd0 100644 --- a/packages/start-plugin-core/src/rsbuild/COMPILER_ARCHITECTURE.md +++ b/packages/start-plugin-core/src/rsbuild/COMPILER_ARCHITECTURE.md @@ -24,7 +24,7 @@ compiler core (`@tanstack/router-utils/compiler`, [README](../../../router-utils ## One compile per module The loader runs for every JavaScript/TypeScript id of an environment, derived ids included (`?tsr-split=`, -`?tss-hydrate=`, `?tss-serverfn-split`): each id compiles from the text Rspack hands it, derived ids hit the plan of +`?tss-hydrate=`, `?tss-serverfn-split`, `?tss-serverfn-handler`): each id compiles from the text Rspack hands it, derived ids hit the plan of their file at the same revision. The planners run in the core's fixed order: `start-env` (server functions, environment separation), `hydrate`, `rsc-css` (modules of the RSC layer), `route-split` and `route-hmr` (client), `import-edges` (import protection). The loader composes its source map with the input map, names the absolute file @@ -50,7 +50,11 @@ plugin rebuilds the environment's snapshot from every module of the compilation persistent cache), the session rebuilds the registry from all snapshots, and the resolver virtual module is rewritten; at stage −10 its importers are rebuilt. The resolver is a manifest importing each provider module; production builds whose SSR environment is the provider list only client-referenced functions (the client compiles first: -`MultiCompiler.setDependencies`). Custom ids (`generateFunctionId`) are placeholders in the outputs, allocated per +`MultiCompiler.setDependencies`). When the SSR environment is the provider, a module defining server functions keeps +their chains and `createServerRpc` exports, and its handlers move into its `?tss-serverfn-handler` derived module, +which it imports once on the first call (direct or through the resolver): what only handlers read loads then, and +what the module itself needs stays in it and is imported back (nothing evaluates twice). A handler that writes state +its module reads, and the handlers of a module that awaits at its top level, stay in place. Custom ids (`generateFunctionId`) are placeholders in the outputs, allocated per rank (client first) and patched at `processAssets` before minification. ## Import protection diff --git a/packages/start-plugin-core/tests/integration/rsbuild/dev-server.test.ts b/packages/start-plugin-core/tests/integration/rsbuild/dev-server.test.ts index ee5526dc1e..aa1d9c1696 100644 --- a/packages/start-plugin-core/tests/integration/rsbuild/dev-server.test.ts +++ b/packages/start-plugin-core/tests/integration/rsbuild/dev-server.test.ts @@ -131,6 +131,42 @@ import { fn2 } from './a2' ) }) +/** + * A Start app on Rsbuild's dev server with its HMR client: the harness + * entries, the router and a root route rendering the document, with a + * `hydrated` mark; the test adds `src/routes/index.tsx`. + */ +const hmrAppFiles = { + 'harness/client-entry.ts': `import { createElement } from 'react' +import { hydrateRoot } from 'react-dom/client' +import { StartClient } from '@tanstack/react-start/client' +hydrateRoot(document, createElement(StartClient)) +`, + 'harness/server-entry.ts': `export { default } from '@tanstack/react-start/server-entry'\n`, + 'src/router.ts': `import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' +export const getRouter = () => createRouter({ routeTree }) +`, + 'src/routes/__root.tsx': `import { HeadContent, Outlet, Scripts, createRootRoute, useHydrated } from '@tanstack/react-router' +export const Route = createRootRoute({ component: Root }) +function Root() { + const hydrated = useHydrated() + return ( + + + + + +
+ {hydrated ? 'hydrated' : 'hydrating'} + + + + ) +} +`, +} + describe('Rsbuild dev with HMR: editing a server fn module', () => { /** * `src/routes/index.tsx` declares a server fn whose handler returns @@ -184,34 +220,7 @@ function Page() { }, }, files: { - 'harness/client-entry.ts': `import { createElement } from 'react' -import { hydrateRoot } from 'react-dom/client' -import { StartClient } from '@tanstack/react-start/client' -hydrateRoot(document, createElement(StartClient)) -`, - 'harness/server-entry.ts': `export { default } from '@tanstack/react-start/server-entry'\n`, - 'src/router.ts': `import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' -export const getRouter = () => createRouter({ routeTree }) -`, - 'src/routes/__root.tsx': `import { HeadContent, Outlet, Scripts, createRootRoute, useHydrated } from '@tanstack/react-router' -export const Route = createRootRoute({ component: Root }) -function Root() { - const hydrated = useHydrated() - return ( - - - - - -
- {hydrated ? 'hydrated' : 'hydrating'} - - - - ) -} -`, + ...hmrAppFiles, 'src/routes/index.tsx': route('V1'), }, }) @@ -250,6 +259,79 @@ function Root() { }, timeout, ) + + // The modules only handlers import load on the first call (like a + // production build, start-build-lazy-handlers.test.ts), and an edit of + // one reaches the next call without a full reload. + test( + "a handler's server-only module loads on the first call, and an edit of it reaches the next call without a full reload", + async () => { + const db = ( + version: string, + ) => `const g = globalThis as Record +g.__tssRsbuildDbLoads = ((g.__tssRsbuildDbLoads as number | undefined) ?? 0) + 1 +export const db = { x: () => 'MARK_DB_${version}' } +` + const server = await startRsbuildStartDevServer({ + hmr: true, + browser: true, + config: { tools: { htmlPlugin: false } }, + files: { + ...hmrAppFiles, + 'src/db.server.ts': db('V1'), + // (a module of its own: the handlers of one module load together) + 'src/loads.ts': `import { createServerFn } from '@tanstack/react-start' +export const loads = createServerFn().handler(async () => + String((globalThis as Record).__tssRsbuildDbLoads ?? 0), +) +`, + 'src/routes/index.tsx': `import { createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import { useState } from 'react' +import { db } from '../db.server' +import { loads } from '../loads' +const greet = createServerFn().handler(async () => db.x()) +export const Route = createFileRoute('/')({ + loader: () => loads(), + component: Page, +}) +function Page() { + const [result, setResult] = useState(Route.useLoaderData()) + return ( +
+

result {result}

+ + +
+ ) +} +`, + }, + }) + expect(server.errors).toEqual([]) + const page = await openPage(server.url!, { + registerCleanup: onTestFinished, + }) + const result = (text: string) => + page.waitForText(`result ${text}`, { selector: '[data-testid=result]' }) + // The page's SSR ran the loader: the module defining the fns is + // loaded, the handler's server-only module is not + await result('0') + await page.waitForText('hydrated', { selector: '[data-testid=hydrated]' }) + await page.page.locator('[data-testid=call]').click() + await result('MARK_DB_V1') + await page.page.locator('[data-testid=loads]').click() + await result('1') + + await server.edit({ 'src/db.server.ts': db('V2') }) + expect(server.errors).toEqual([]) + await page.page.locator('[data-testid=call]').click() + await result('MARK_DB_V2') + expect(page.loads()).toBe(1) + expect(page.errors).toEqual([]) + }, + timeout, + ) }) describe('Rsbuild dev: removing a server fn module', () => { diff --git a/packages/start-plugin-core/tests/integration/start-build-lazy-handlers.test.ts b/packages/start-plugin-core/tests/integration/start-build-lazy-handlers.test.ts new file mode 100644 index 0000000000..3cb4b901e5 --- /dev/null +++ b/packages/start-plugin-core/tests/integration/start-build-lazy-handlers.test.ts @@ -0,0 +1,274 @@ +/** + * What a production server build evaluates, and when, for the modules that + * define server fns (Vite and Rsbuild builds, Start's whole plugin, the + * server bundle run by Start's own server entry inside a real request): + * the modules only handlers import load on the first call, like main, and + * nothing a server fn module evaluates runs twice, whether server code calls + * the fn directly or a page calls it over HTTP. + * Source: the real-app differential corpus (lbogerd/tictaak-start: a route + * file whose handlers import the database module, which throws at load + * without DATABASE_URL); issue #6451 (concurrent first calls of a server fn + * whose handler's imports load slowly). + */ +import { afterAll, beforeAll, describe, expect, test } from 'vitest' +import { + buildStart, + callByIdExports, + callByIdPrelude, + startBundlers, +} from '../build-harness' +import { createStartHost } from '../regression-helpers' +import type { StartBuild } from '../build-harness' +import type { StartHost } from '../regression-helpers' + +const timeout = 60_000 + +const head = `import { createServerFn } from '@tanstack/react-start'\n` + +/** A module counting its evaluations in `globalThis[name]`, exporting `value`. */ +const counted = (name: string, value = `'${name}'`) => + `globalThis.${name} = (globalThis.${name} ?? 0) + 1 +export const value = ${value} +` + +const files = { + // handler-only dependencies + 'heavy.server.ts': counted('MARK_HEAVY'), + 'deep.server.ts': counted('MARK_DEEP'), + 'slow.server.ts': `${counted('MARK_SLOW')}await new Promise((resolve) => setTimeout(resolve, 200)) +`, + 'broken.server.ts': `throw new Error('MARK_BROKEN_AT_IMPORT') +export const value = 'unreachable' +`, + 'tla-dep.server.ts': counted('MARK_TLA_DEP'), + // a module whose own code and handlers share state + 'fns.ts': `${head}import { value as heavy } from './heavy.server' +import { value as slow } from './slow.server' +import { value as deep } from './deep.server' +globalThis.MARK_FNS = (globalThis.MARK_FNS ?? 0) + 1 +let label = 'initial' +export function setLabel(next: string) { + label = next +} +let count = 0 +export function readCount() { + return count +} +export const getHeavy = createServerFn().handler(async () => heavy) +export const getSlow = createServerFn().handler(async () => slow) +export const readLabel = createServerFn().handler(async () => label) +export const bump = createServerFn().handler(async () => ++count) +export function makeNested() { + const nested = createServerFn().handler(async () => deep) + return nested +} +`, + 'broken.ts': `${head}import { value } from './broken.server' +export const callBroken = createServerFn().handler(async () => value) +`, + // a module that awaits one of its own server fns while it evaluates, whose + // handler reads the module's own state + 'tla.ts': `${head}import { value } from './tla-dep.server' +export const prefix = ['tla', ''].join(':') +export const tlaFn = createServerFn().handler(async () => prefix + value) +export const ready = await tlaFn() +`, + 'client-entry.ts': `export * from './fns' +export { callBroken } from './broken' +export const loadTla = () => import('./tla') +`, + 'ssr-entry.ts': `export * from './client-entry' +${callByIdExports}`, +} + +/** SSR script prelude: the evaluation counters of `files`. */ +const counters = `const count = (name) => globalThis[name] ?? 0 +const counts = (...names) => + Object.fromEntries(names.map((name) => [name, count('MARK_' + name.toUpperCase())])) +` + +describe.each(startBundlers)('%s build', (bundler) => { + let build: StartBuild + const cleanups: Array<() => Promise> = [] + + beforeAll(async () => { + build = await buildStart({ + bundler, + files, + entry: { client: 'client-entry.ts', ssr: 'ssr-entry.ts' }, + registerCleanup: (cleanup) => cleanups.push(cleanup), + }) + }, timeout) + + afterAll(async () => { + await Promise.all(cleanups.map((cleanup) => cleanup())) + }) + + test( + 'SSR: the server-only modules of handlers load on the first call, not with the module defining the fn', + async () => { + const { result } = await build.ssr + .run(`${counters}const before = counts('fns', 'heavy') +const heavy = await entry.getHeavy() +return { before, heavy, after: counts('fns', 'heavy') }`) + expect(result).toEqual({ + before: { fns: 1, heavy: 0 }, + heavy: 'MARK_HEAVY', + after: { fns: 1, heavy: 1 }, + }) + }, + timeout, + ) + + test( + 'SSR: direct calls and calls over HTTP run one instance of the module and of what its handlers import', + async () => { + const { result } = await build.ssr + .run(`${callByIdPrelude}${counters}const results = await Promise.all([ + ...Array.from({ length: 25 }, () => entry.getSlow()), + ...Array.from({ length: 25 }, () => callById(serverFnId(entry.getSlow))), +]) +return { + results: [...new Set(results)], + counts: counts('fns', 'slow'), + overHttp: await callById(serverFnId(entry.getHeavy)), + after: counts('fns', 'slow', 'heavy'), +}`) + expect(result).toEqual({ + results: ['MARK_SLOW'], + counts: { fns: 1, slow: 1 }, + overHttp: 'MARK_HEAVY', + after: { fns: 1, slow: 1, heavy: 1 }, + }) + }, + timeout, + ) + + test( + "SSR: a handler reads the module's current state, and a handler's writes are what the module reads", + async () => { + const { result } = await build.ssr + .run(`${callByIdPrelude}entry.setLabel('changed') +const label = await entry.readLabel() +const overHttp = await callById(serverFnId(entry.readLabel)) +await entry.bump() +await callById(serverFnId(entry.bump)) +return { label, overHttp, count: entry.readCount() }`) + expect(result).toEqual({ + label: 'changed', + overHttp: 'changed', + count: 2, + }) + }, + timeout, + ) + + test( + 'SSR: the server-only module of a nested server fn loads on its first call', + async () => { + const { result } = await build.ssr + .run(`${counters}const fn = entry.makeNested() +const before = counts('deep') +return { before, called: await fn(), after: counts('deep') }`) + expect(result).toEqual({ + before: { deep: 0 }, + called: 'MARK_DEEP', + after: { deep: 1 }, + }) + }, + timeout, + ) + + test( + 'SSR: a handler-only module that throws at load fails only the calls of that fn', + async () => { + const { result } = await build.ssr.run(`const settle = async (run) => { + try { + return { value: await run() } + } catch (error) { + return { error: String(error?.message ?? error) } + } +} +return { + broken: await settle(() => entry.callBroken()), + other: await settle(() => entry.getHeavy()), +}`) + expect(result).toEqual({ + broken: { error: expect.stringContaining('MARK_BROKEN_AT_IMPORT') }, + other: { value: 'MARK_HEAVY' }, + }) + }, + timeout, + ) + + test( + 'SSR: a module that awaits one of its own server fns at its top level evaluates', + async () => { + const { result } = await build.ssr.run(`const tla = await entry.loadTla() +return { ready: tla.ready, again: await tla.tlaFn(), dep: globalThis.MARK_TLA_DEP }`) + expect(result).toEqual({ + ready: 'tla:MARK_TLA_DEP', + again: 'tla:MARK_TLA_DEP', + dep: 1, + }) + }, + timeout, + ) +}) + +// `@vitejs/plugin-vue` serves an SFC's ` + + +`, + 'db.server.ts': `export const db = { x: (input: string) => 'MARK_DB_SERVER:' + input }\n`, + 'module.ts': `export { fn } from './Page.vue'\n`, + }) + const build = await host.build() + const { chunks } = build.environments.ssr! + const byName = new Map(chunks.map((chunk) => [chunk.fileName, chunk])) + const page = startCase.file('Page.vue') + // (the SFC module itself, which imports its blocks) + const own = chunks.filter((chunk) => chunk.moduleIds.includes(page)) + expect(own.length, 'SSR chunks of the SFC').toBeGreaterThan(0) + // the SFC's chunks and every chunk they import statically + const loaded = new Set(own) + for (const chunk of loaded) { + for (const name of chunk.imports) { + const next = byName.get(name) + if (next) { + loaded.add(next) + } + } + } + expect({ + withTheSfc: [...loaded].some((chunk) => + chunk.code.includes('MARK_DB_SERVER'), + ), + inTheBuild: chunks.some((chunk) => + chunk.code.includes('MARK_DB_SERVER'), + ), + }).toEqual({ withTheSfc: false, inTheBuild: true }) + }, + timeout, + ) +}) diff --git a/packages/start-plugin-core/tests/integration/start-compiler-dev-server.test.ts b/packages/start-plugin-core/tests/integration/start-compiler-dev-server.test.ts index 09bc574c7b..b87494fe7f 100644 --- a/packages/start-plugin-core/tests/integration/start-compiler-dev-server.test.ts +++ b/packages/start-plugin-core/tests/integration/start-compiler-dev-server.test.ts @@ -231,6 +231,91 @@ export const greet = createServerFn().handler(() => db.x()) }, timeout, ) + + // A module both the server fn module and its handler read: an edit + // reaches the module's own code and the handler alike (one instance). + test( + 'SSR: an edit of a module the server fn module and its handler share reaches both, without a full reload', + async () => { + const state = (version: string) => + `export const label = 'MARK_STATE_${version}'\n` + const server = await startDevServer({ + start: {}, + files: { + ...startRequestFiles, + 'src/fns.ts': `import { createServerFn } from '@tanstack/react-start' +import { label } from './state' +export const shown = label.toLowerCase() +export const greet = createServerFn().handler(() => [shown, label]) +`, + 'src/state.ts': state('V1'), + }, + }) + const call = async () => { + const { greet } = await server.import('/src/fns.ts') + return callServerFn(server, greet) + } + expect(await call()).toEqual(['mark_state_v1', 'MARK_STATE_V1']) + + const messages = describeHmr( + await server.edit({ 'src/state.ts': state('V2') }), + ) + + expect(await call()).toEqual(['mark_state_v2', 'MARK_STATE_V2']) + expect( + messages.filter((message) => message.includes('full-reload')), + ).toEqual([]) + }, + timeout, + ) +}) + +describe('Vite dev: when the modules of a server fn handler load', () => { + // Like a production build (start-build-lazy-handlers.test.ts): the + // modules only handlers import load on the first call, once, however + // many first calls run at the same time (server code calling the fn + // directly, pages calling it over HTTP) while they load. + // Source: issue #6451 (concurrent first calls of a server fn whose + // handler's imports load slowly). + test( + 'SSR: the server-only module of a handler loads on the first call, once, for concurrent direct and HTTP calls', + async () => { + const marker = '__tssDevLazyHandlerLoads' + const global = globalThis as Record + onTestFinished(() => { + delete global[marker] + }) + const server = await startDevServer({ + start: {}, + files: { + ...startRequestFiles, + 'src/fns.ts': `import { createServerFn } from '@tanstack/react-start' +import { db } from './db.server' +export const greet = createServerFn().handler(async () => db.x()) +`, + 'src/db.server.ts': `const g = globalThis as Record +g.${marker} = ((g.${marker} as number | undefined) ?? 0) + 1 +await new Promise((resolve) => setTimeout(resolve, 100)) +export const db = { x: () => 'MARK_DB' } +`, + }, + }) + const { greet } = await server.import('/src/fns.ts') + const before = global[marker] ?? 0 + const results = await Promise.all([ + ...Array.from({ length: 10 }, () => + inDevRequest(server, () => greet()), + ), + ...Array.from({ length: 10 }, () => callServerFn(server, greet)), + ]) + expect({ + before, + results: [...new Set(results)], + after: global[marker], + }).toEqual({ before: 0, results: ['MARK_DB'], after: 1 }) + }, + timeout, + ) }) describe('Vite dev: editing what a route module imports', () => { diff --git a/packages/start-plugin-core/tests/planner-outputs.test.ts b/packages/start-plugin-core/tests/planner-outputs.test.ts index 10b09e35f6..9a2409086a 100644 --- a/packages/start-plugin-core/tests/planner-outputs.test.ts +++ b/packages/start-plugin-core/tests/planner-outputs.test.ts @@ -133,7 +133,7 @@ export const label = () => 'client' }) }) - test('provider: the handler stays in place next to a createServerRpc export', async () => { + test('provider: the chain stays next to a createServerRpc export, its handler loads on the first call', async () => { const out = (await compile(files, 'ssr'))! expect(out.code).toContain( "import { createServerRpc as tsrServerRpc } from '@tanstack/react-start/server-rpc'", @@ -142,9 +142,21 @@ export const label = () => 'client' /const fn_createServerFn_handler = tsrServerRpc\(\{ id: '[^']+', name: 'fn', filename: 'module\.tsx' \}, \(opts\) => fn\.__executeServer\(opts\)\)\nexport \{ fn_createServerFn_handler \}/, ) expect(out.code).toContain( - '.validator(schema).handler(fn_createServerFn_handler, async () => db.x())', + "const tsrLoadHandlers = () => (tsrHandlers ??= import('./module.tsx?tss-serverfn-handler'))", ) - expect(out.code).toContain("from './db.server'") + expect(out.code).toContain( + '.validator(schema).handler(fn_createServerFn_handler, (...args) => tsrLoadHandlers().then((m) => m.tsrHandler$fn(...args)))', + ) + expect(out.code).not.toContain('db.server') + const handlers = (await compile( + files, + 'ssr', + '/app/module.tsx?tss-serverfn-handler', + ))! + expect(handlers.code).toBe(`import { db } from './db.server' +const tsrHandler$fn = async () => db.x() +export { tsrHandler$fn } +`) }) test('ssr caller with a separate provider: an ssr rpc stub keeps the validator', async () => { @@ -285,10 +297,10 @@ export const wrapped = wrap(wrap(createServerFn().handler(async () => 'w'))) expect(client.code).not.toContain('schema') const ssr = (await compile(files, 'ssr'))! expect(ssr.code).toContain( - '.handler(fn_createServerFn_handler, async ({ data }) => data)', + '.handler(fn_createServerFn_handler, (...args) => tsrLoadHandlers().then((m) => m.tsrHandler$fn(...args)))', ) expect(ssr.code).toContain( - 'wrap(wrap(createServerFn().handler(wrapped_createServerFn_handler, async', + 'wrap(wrap(createServerFn().handler(wrapped_createServerFn_handler, (...args) =>', ) }) @@ -338,8 +350,15 @@ export function make() { expect(client.code).not.toContain('db.server') const ssr = (await compile(files2, 'ssr'))! expect(ssr.code).toContain( - 'const tsrServerFn$inner = createServerFn().handler(inner_make_createServerFn_handler, async () => db.inner())', + 'const tsrServerFn$inner = createServerFn().handler(inner_make_createServerFn_handler, (...args) => tsrLoadHandlers().then((m) => m.tsrHandler$inner_make(...args)))', ) + expect(ssr.code).not.toContain('db.server') + const handlers = (await compile( + files2, + 'ssr', + '/app/module.tsx?tss-serverfn-handler', + ))! + expect(handlers.code).toContain('= async () => db.inner()') expect(ssr.code).toContain('const inner = tsrServerFn$inner') expect(ssr.code).toContain("name: 'inner'") }) diff --git a/packages/start-plugin-core/tests/planners/start-env.test.ts b/packages/start-plugin-core/tests/planners/start-env.test.ts index b4566522d5..6eddbff88b 100644 --- a/packages/start-plugin-core/tests/planners/start-env.test.ts +++ b/packages/start-plugin-core/tests/planners/start-env.test.ts @@ -435,8 +435,122 @@ import { db } from './db.server' expect(r.code).toContain('tsrSsrRpc') expect(r.code).not.toContain('db.q(1)') } else { - expect(r.code).toContain('db.q(1)') + // the in-place provider's handlers live in its handler module + expect(r.code).not.toContain('db.q(1)') + expect(await r.derived(`${FILE}?tss-serverfn-handler`)).toContain( + 'db.q(1)', + ) } } }) }) + +// In-place provider (SSR = provider): handlers move to one lazy handler +// module the defining module imports on the first call; what only they read +// moves with them, what the defining module also reads stays and is +// imported back (nothing evaluates twice). +describe('lazy handler module of the in-place provider', () => { + const FNS = `import { createServerFn, createServerOnlyFn } from '@tanstack/react-start'\n` + const files = { + '/app/src/db.server.ts': `export const db = { get: (x: unknown) => x }\n`, + } + const HANDLER_ID = `${FILE}?tss-serverfn-handler` + + it('moves a handler and the imports only it reads', async () => { + const r = await compile( + `${FNS}import { db } from './db.server' +let count = 0 +export const fn = createServerFn().handler(async () => db.get(count)) +export function read() { return count } +`, + { env: ssrEnv, files }, + ) + expectValid(r.code) + expect(r.code).not.toContain('./db.server') + expect(r.code).toContain('?tss-serverfn-handler') + const h = await r.derived(HANDLER_ID) + expectValid(h) + expect(h).toContain(`from './db.server'`) + // module state the defining module also reads is imported from it, not copied + expect(h).not.toMatch(/let count/) + expect(h).toMatch(/import \{[^}]*\bcount\b[^}]*\} from '\.\/module\.tsx'/) + }) + + it('keeps a handler that writes module state the module also reads in place', async () => { + const r = await compile( + `${FNS}let count = 0 +export const fn = createServerFn().handler(async () => count++) +export function read() { return count } +`, + { env: ssrEnv }, + ) + expectValid(r.code) + expect(r.code).toContain('count++') + expect(r.code).not.toContain('?tss-serverfn-handler') + }) + + it('keeps the handlers of a module that awaits at its top level in place', async () => { + const r = await compile( + `${FNS}import { db } from './db.server' +export const fn = createServerFn().handler(async () => db.get(1)) +export const first = await Promise.resolve(1) +`, + { env: ssrEnv, files }, + ) + expectValid(r.code) + expect(r.code).toContain('./db.server') + expect(r.code).not.toContain('?tss-serverfn-handler') + }) + + it('moves a handler that is itself a createServerOnlyFn call, rewritten', async () => { + const r = await compile( + `${FNS}import { db } from './db.server' +export const fn = createServerFn().handler(createServerOnlyFn(async () => db.get(2))) +`, + { env: ssrEnv, files }, + ) + expectValid(r.code) + expect(r.code).not.toContain('createServerOnlyFn(') + const h = await r.derived(HANDLER_ID) + expectValid(h) + expect(h).not.toContain('createServerOnlyFn') + expect(h).toContain('db.get(2)') + }) + + it('moves the handler of a hoisted nested server fn', async () => { + const r = await compile( + `${FNS}import { db } from './db.server' +export function makeFns() { + const inner = createServerFn().handler(async () => db.get(3)) + return { inner } +} +`, + { env: ssrEnv, files }, + ) + expectValid(r.code) + expect(r.code).not.toContain('./db.server') + expect(r.code).toContain('?tss-serverfn-handler') + const h = await r.derived(HANDLER_ID) + expectValid(h) + expect(h).toContain(`from './db.server'`) + expect(h).toContain('db.get(3)') + }) + + it('derives the handler module of an SFC block before its language key', async () => { + const id = `${FILE}?vue&type=script&lang.ts` + const r = await compile( + `${FNS}import { db } from './db.server' +export const fn = createServerFn().handler(async () => db.get(4)) +`, + { env: ssrEnv, files, id }, + ) + expectValid(r.code) + expect(r.code).toContain( + `import('./module.tsx?vue&type=script&tss-serverfn-handler&lang.ts')`, + ) + const h = await r.derived( + `${FILE}?vue&type=script&tss-serverfn-handler&lang.ts`, + ) + expect(h).toContain('db.get(4)') + }) +})