fix: compile createMiddleware using start-compiler-plugin #5245
Mergedschiller-manuel(GitHub profile, opens in a new tab)merged 2 commits into
main fromrefs/pull/5245/headmerged by schiller-manuel(GitHub profile, opens in a new tab) github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: start-plugin-core
- packages/start-plugin-core/src/create-server-fn-plugin/plugin.ts lines 86 to 88@@ -52,5 +83,6 @@5283 exclude: new RegExp(`${SERVER_FN_LOOKUP}$`),5384 },5485 code: {55- // only scan files that mention `.handler(` | `.server(` | `.client(`56- include: [/\.handler\(/, /\.server\(/, /\.client\(/],86+ // TODO apply this plugin with a different filter per environment so that .createMiddleware() calls are not scanned in server env87+ // only scan files that mention `.handler(` | `.createMiddleware()`88+ include: [/\.handler\(/, /.createMiddleware\(\)/],packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/createMiddleware.test.ts lines 12 to 36Outdated@@ -0,0 +16,21 @@16+ const file = await readFile(17+ path.resolve(import.meta.dirname, `./test-files/${filename}`),18+ )19+ const code = file.toString()20+21+ test.each(['client', 'server'] as const)(22+ `should compile for ${filename} %s`,23+ async (env) => {24+ const compiledResult = compileStartOutput({25+ env,26+ code,27+ filename,28+ dce: false,29+ })30+31+ await expect(compiledResult.code).toMatchFileSnapshot(32+ `./snapshots/${env}/${filename}`,33+ )34+ },35+ )36+ })packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/createMiddlewareDestructured.tsx lines 12 to 20Outdated@@ -0,0 +1,20 @@1+import { createMiddleware } from '@tanstack/react-start';2+import { z } from 'zod';3+export const withUseServer = createMiddleware({4+ id: 'test'5+});6+export const withoutUseServer = createMiddleware({7+ id: 'test'8+});9+export const withVariable = createMiddleware({10+ id: 'test'11+});12+async function abstractedFunction() {13+ console.info('Fetching posts...');14+ await new Promise(r => setTimeout(r, 500));15+ return axios.get<Array<PostType>>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10));16+}17+function zodValidator<TSchema extends z.ZodSchema, TResult>(schema: TSchema, fn: (input: z.output<TSchema>) => TResult) {18+ return async (input: unknown) => {19+ return fn(schema.parse(input));20+ };packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/createMiddlewareDestructuredRename.tsx lines 12 to 16Outdated@@ -0,0 +1,16 @@1+import { createMiddleware as middlewareFn } from '@tanstack/react-start';2+import { z } from 'zod';3+export const withUseServer = middlewareFn({4+ id: 'test'5+});6+export const withoutUseServer = middlewareFn({7+ id: 'test'8+});9+export const withVariable = middlewareFn({10+ id: 'test'11+});12+async function abstractedFunction() {13+ console.info('Fetching posts...');14+ await new Promise(r => setTimeout(r, 500));15+ return axios.get<Array<PostType>>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10));16+}packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/createMiddlewareStarImport.tsx lines 12 to 16Outdated@@ -0,0 +1,16 @@1+import * as TanStackStart from '@tanstack/react-start';2+import { z } from 'zod';3+export const withUseServer = TanStackStart.createMiddleware({4+ id: 'test'5+});6+export const withoutUseServer = TanStackStart.createMiddleware({7+ id: 'test'8+});9+export const withVariable = TanStackStart.createMiddleware({10+ id: 'test'11+});12+async function abstractedFunction() {13+ console.info('Fetching posts...');14+ await new Promise(r => setTimeout(r, 500));15+ return axios.get<Array<PostType>>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10));16+}packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/factory.ts lines 1 to 2Outdated@@ -0,0 +1,2 @@1+import { createMiddleware } from "@tanstack/react-start";2+import { getCookie } from "@tanstack/react-start/server";packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/factory.ts lines 15 to 22Outdated@@ -0,0 +2,21 @@2+import { getCookie } from "@tanstack/react-start/server";3+interface AuthMiddlewareOptions {4+ allowUnauthenticated?: boolean;5+}6+interface AuthContext {7+ session: {8+ id: string;9+ } | null;10+}11+export const createAuthMiddleware = (opts: AuthMiddlewareOptions = {12+ allowUnauthenticated: false13+}) => createMiddleware({14+ type: "function"15+}).server<AuthContext>(({16+ next17+}) => {18+ const token = getCookie("session");19+ if (!token) {20+ if (!opts.allowUnauthenticated) {21+ throw new Error("Unauthorized");22+ }packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/test-files/factory.ts lines 15 to 23Outdated@@ -0,0 +3,21 @@3+4+interface AuthMiddlewareOptions {5+ allowUnauthenticated?: boolean6+}7+8+interface AuthContext {9+ session: { id: string } | null10+}11+12+export const createAuthMiddleware = (13+ opts: AuthMiddlewareOptions = { allowUnauthenticated: false },14+) =>15+ createMiddleware({ type: 'function' }).server<AuthContext>(({ next }) => {16+ const token = getCookie('session')17+ if (!token) {18+ if (!opts.allowUnauthenticated) {19+ throw new Error('Unauthorized')20+ }21+22+ return next({23+ context: {
Sign in to join this conversation.
Walkthrough#
Adds a configurable LookupKind model to ServerFnCompiler, switches candidate detection to per-kind identifiers, and makes the plugin build lookup kinds/configurations per environment. Start compiler adds createMiddleware handling. Tests and snapshots updated: new createMiddleware start-compiler tests added; legacy createMiddleware and some createStart snapshots removed or adjusted.
Changes#
packages/start-plugin-core/src/create-server-fn-plugin/compiler.tsLookupKind; addedLookupSetup; replaced static valid kinds withoptions.lookupKindsstored asthis.validLookupKinds: Set<LookupKind>; updatedisCandidateCallExpressionsignature and all internal checks to use the instance set; wired per-kind candidate identifiers.packages/start-plugin-core/src/create-server-fn-plugin/plugin.tsLookupKindsPerEnvandgetLookupConfigurationsForEnv; plugin now constructslookupKindsandlookupConfigurationsper env/framework and passes them toServerFnCompiler; adjusted include filters for scanning.packages/start-plugin-core/src/start-compiler-plugin/compilers.ts,packages/start-plugin-core/src/start-compiler-plugin/constants.tshandleCreateMiddlewareand added'createMiddleware'totransformFuncs; added identifier entry forcreateMiddlewarein the compile/start identifiers map.packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/createMiddleware.test.ts,packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/*,packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/factory.ts,packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/test-files/factory.tscreateMiddlewareusage and a middleware factory example.packages/start-plugin-core/tests/createMiddleware-create-server-fn-plugin/createMiddleware.test.tslookupKinds: new Set(['Middleware']); removedcreateServerFnlookup configuration entry.packages/start-plugin-core/tests/createMiddleware/snapshots/client/*packages/start-plugin-core/tests/createServerFn/createServerFn.test.ts,packages/start-plugin-core/tests/createServerFn/snapshots/client/createStart.tsx,packages/start-plugin-core/tests/createServerFn/snapshots/server/createStart.tsx,packages/start-plugin-core/tests/createServerFn/test-files/createStart.tsx,packages/start-plugin-core/tests/createServerFn/snapshots/client/factory.tsxlookupKinds: new Set(['ServerFn']); removed createStart-based snapshots and test-file content; retained/updated factory snapshot showing middleware chaining.Sequence Diagram(s)#
Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~60 minutes
Poem#
Pre-merge checks and finishing touches#
✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests
📜 Recent review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 0886efbd012428c0d0ea5f426092bcd6f59de6c3 and 3c1ece78952dfdce5181e423db7560ea17835900.
📒 Files selected for processing (2)
packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/factory.ts(1 hunks)packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/factory.ts(1 hunks)🚧 Files skipped from review as they are similar to previous changes (2)
Comment `@coderabbitai help` to get the list of available commands and usage tips.