Skip to content

Commit b43fe8e

Browse files
perf: create-server-fn-plugin
1 parent 0ba5735 commit b43fe8e

4 files changed

Lines changed: 224 additions & 165 deletions

File tree

‎packages/start-plugin-core/src/create-server-fn-plugin/compiler.ts‎

Lines changed: 141 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
} from 'babel-dead-code-elimination'
99
import { handleCreateServerFn } from './handleCreateServerFn'
1010
import { handleCreateMiddleware } from './handleCreateMiddleware'
11+
import type { MethodChainPaths } from './types'
1112

1213
type Binding =
1314
| {
@@ -41,6 +42,16 @@ const LookupSetup: Record<
4142
},
4243
}
4344

45+
// Pre-computed map: identifier name -> LookupKind for fast candidate detection
46+
const IdentifierToKind = new Map<string, LookupKind>()
47+
for (const [kind, setup] of Object.entries(LookupSetup) as Array<
48+
[LookupKind, { candidateCallIdentifier: Set<string> }]
49+
>) {
50+
for (const id of setup.candidateCallIdentifier) {
51+
IdentifierToKind.set(id, kind)
52+
}
53+
}
54+
4455
export type LookupConfig = {
4556
libName: string
4657
rootExport: string
@@ -247,55 +258,118 @@ export class ServerFnCompiler {
247258
}
248259

249260
// let's find out which of the candidates are actually server functions
250-
const toRewrite: Array<{
251-
callExpression: t.CallExpression
252-
kind: LookupKind
253-
}> = []
254-
for (const handler of candidates) {
255-
const kind = await this.resolveExprKind(handler, id)
261+
// Resolve all candidates in parallel for better performance
262+
const resolvedCandidates = await Promise.all(
263+
candidates.map(async (candidate) => ({
264+
candidate,
265+
kind: await this.resolveExprKind(candidate, id),
266+
})),
267+
)
268+
269+
// Map from candidate/root node -> kind
270+
// Note: For top-level variable declarations, candidate === root (the outermost CallExpression)
271+
const toRewriteMap = new Map<t.CallExpression, LookupKind>()
272+
for (const { candidate, kind } of resolvedCandidates) {
256273
if (this.validLookupKinds.has(kind as LookupKind)) {
257-
toRewrite.push({ callExpression: handler, kind: kind as LookupKind })
274+
toRewriteMap.set(candidate, kind as LookupKind)
258275
}
259276
}
260-
if (toRewrite.length === 0) {
277+
if (toRewriteMap.size === 0) {
261278
return null
262279
}
263280

281+
// Single-pass traversal to find NodePaths and collect method chains
264282
const pathsToRewrite: Array<{
265-
nodePath: babel.NodePath<t.CallExpression>
283+
path: babel.NodePath<t.CallExpression>
266284
kind: LookupKind
285+
methodChain: MethodChainPaths
267286
}> = []
287+
288+
// First, collect all CallExpression paths in the AST for O(1) lookup
289+
const callExprPaths = new Map<
290+
t.CallExpression,
291+
babel.NodePath<t.CallExpression>
292+
>()
293+
268294
babel.traverse(ast, {
269295
CallExpression(path) {
270-
const found = toRewrite.findIndex((h) => path.node === h.callExpression)
271-
if (found !== -1) {
272-
pathsToRewrite.push({ nodePath: path, kind: toRewrite[found]!.kind })
273-
// delete from toRewrite
274-
toRewrite.splice(found, 1)
275-
}
296+
callExprPaths.set(path.node, path)
276297
},
277298
})
278299

279-
if (toRewrite.length > 0) {
300+
// Now process candidates - we can look up any CallExpression path in O(1)
301+
for (const [node, kind] of toRewriteMap) {
302+
const path = callExprPaths.get(node)
303+
if (!path) {
304+
continue
305+
}
306+
307+
// Collect method chain paths by walking DOWN from root through the chain
308+
const methodChain: MethodChainPaths = {
309+
middleware: null,
310+
inputValidator: null,
311+
handler: null,
312+
server: null,
313+
client: null,
314+
}
315+
316+
// Walk down the call chain using nodes, look up paths from map
317+
let currentNode: t.CallExpression = node
318+
while (true) {
319+
const callee = currentNode.callee
320+
if (!t.isMemberExpression(callee)) {
321+
break
322+
}
323+
324+
// Record method chain path if it's a known method
325+
if (t.isIdentifier(callee.property)) {
326+
const name = callee.property.name as keyof MethodChainPaths
327+
if (name in methodChain) {
328+
const currentPath = callExprPaths.get(currentNode)!
329+
// Get first argument path
330+
const args = currentPath.get('arguments')
331+
const firstArgPath =
332+
Array.isArray(args) && args.length > 0 ? (args[0] ?? null) : null
333+
methodChain[name] = {
334+
callPath: currentPath,
335+
firstArgPath,
336+
}
337+
}
338+
}
339+
340+
// Move to the inner call (the object of the member expression)
341+
if (!t.isCallExpression(callee.object)) {
342+
break
343+
}
344+
currentNode = callee.object
345+
}
346+
347+
pathsToRewrite.push({ path, kind, methodChain })
348+
}
349+
350+
// Verify we found all candidates (pathsToRewrite should have same size as toRewriteMap had)
351+
if (pathsToRewrite.length !== toRewriteMap.size) {
280352
throw new Error(
281353
`Internal error: could not find all paths to rewrite. please file an issue`,
282354
)
283355
}
284356

285357
const refIdents = findReferencedIdentifiers(ast)
286358

287-
pathsToRewrite.map((p) => {
359+
for (const p of pathsToRewrite) {
288360
if (p.kind === 'ServerFn') {
289-
handleCreateServerFn(p.nodePath, {
361+
handleCreateServerFn(p, {
290362
env: this.options.env,
291363
code,
292364
directive: this.options.directive,
293365
isProviderFile,
294366
})
295367
} else {
296-
handleCreateMiddleware(p.nodePath, { env: this.options.env })
368+
handleCreateMiddleware(p, {
369+
env: this.options.env,
370+
})
297371
}
298-
})
372+
}
299373

300374
deadCodeElimination(ast, refIdents)
301375

@@ -312,12 +386,12 @@ export class ServerFnCompiler {
312386

313387
for (const binding of bindings.values()) {
314388
if (binding.type === 'var') {
315-
const handler = isCandidateCallExpression(
389+
const candidate = isCandidateCallExpression(
316390
binding.init,
317391
this.validLookupKinds,
318392
)
319-
if (handler) {
320-
candidates.push(handler)
393+
if (candidate) {
394+
candidates.push(candidate)
321395
}
322396
}
323397
}
@@ -376,19 +450,28 @@ export class ServerFnCompiler {
376450
}
377451
}
378452

379-
// If not found, recursively check re-export-all sources
380-
for (const reExportSource of moduleInfo.reExportAllSources) {
381-
const reExportTarget = await this.options.resolveId(
382-
reExportSource,
383-
moduleInfo.id,
453+
// If not found, recursively check re-export-all sources in parallel
454+
// Valid code won't have duplicate exports across chains, so first match wins
455+
if (moduleInfo.reExportAllSources.length > 0) {
456+
const results = await Promise.all(
457+
moduleInfo.reExportAllSources.map(async (reExportSource) => {
458+
const reExportTarget = await this.options.resolveId(
459+
reExportSource,
460+
moduleInfo.id,
461+
)
462+
if (reExportTarget) {
463+
const reExportModule = await this.getModuleInfo(reExportTarget)
464+
return this.findExportInModule(
465+
reExportModule,
466+
exportName,
467+
visitedModules,
468+
)
469+
}
470+
return undefined
471+
}),
384472
)
385-
if (reExportTarget) {
386-
const reExportModule = await this.getModuleInfo(reExportTarget)
387-
const result = await this.findExportInModule(
388-
reExportModule,
389-
exportName,
390-
visitedModules,
391-
)
473+
// Return the first valid result
474+
for (const result of results) {
392475
if (result) {
393476
return result
394477
}
@@ -417,8 +500,8 @@ export class ServerFnCompiler {
417500
// Find the export, recursively searching through export * from chains
418501
const found = await this.findExportInModule(
419502
importedModule,
420-
binding.importedName,
421-
)
503+
binding.importedName,
504+
)
422505

423506
if (!found) {
424507
return 'None'
@@ -457,6 +540,15 @@ export class ServerFnCompiler {
457540
return 'None'
458541
}
459542

543+
// Unwrap common TypeScript/parenthesized wrappers first for efficiency
544+
while (
545+
t.isTSAsExpression(expr) ||
546+
t.isTSNonNullExpression(expr) ||
547+
t.isParenthesizedExpression(expr)
548+
) {
549+
expr = expr.expression
550+
}
551+
460552
let result: Kind = 'None'
461553

462554
if (t.isCallExpression(expr)) {
@@ -468,15 +560,12 @@ export class ServerFnCompiler {
468560
fileId,
469561
visited,
470562
)
471-
if (calleeKind !== 'None') {
472-
if (calleeKind === `Root` || calleeKind === `Builder`) {
473-
return `Builder`
474-
}
475-
for (const kind of this.validLookupKinds) {
476-
if (calleeKind === kind) {
477-
return kind
478-
}
479-
}
563+
if (calleeKind === 'Root' || calleeKind === 'Builder') {
564+
return 'Builder'
565+
}
566+
// Use direct Set.has() instead of iterating
567+
if (this.validLookupKinds.has(calleeKind as LookupKind)) {
568+
return calleeKind
480569
}
481570
} else if (t.isMemberExpression(expr) && t.isIdentifier(expr.property)) {
482571
result = await this.resolveCalleeKind(expr.object, fileId, visited)
@@ -486,16 +575,6 @@ export class ServerFnCompiler {
486575
result = await this.resolveIdentifierKind(expr.name, fileId, visited)
487576
}
488577

489-
if (result === 'None' && t.isTSAsExpression(expr)) {
490-
result = await this.resolveExprKind(expr.expression, fileId, visited)
491-
}
492-
if (result === 'None' && t.isTSNonNullExpression(expr)) {
493-
result = await this.resolveExprKind(expr.expression, fileId, visited)
494-
}
495-
if (result === 'None' && t.isParenthesizedExpression(expr)) {
496-
result = await this.resolveExprKind(expr.expression, fileId, visited)
497-
}
498-
499578
return result
500579
}
501580

@@ -590,17 +669,18 @@ export class ServerFnCompiler {
590669
function isCandidateCallExpression(
591670
node: t.Node | null | undefined,
592671
lookupKinds: Set<LookupKind>,
593-
): undefined | t.CallExpression {
672+
): t.CallExpression | undefined {
594673
if (!t.isCallExpression(node)) return undefined
595674

596675
const callee = node.callee
597676
if (!t.isMemberExpression(callee) || !t.isIdentifier(callee.property)) {
598677
return undefined
599678
}
600-
for (const kind of lookupKinds) {
601-
if (LookupSetup[kind].candidateCallIdentifier.has(callee.property.name)) {
602-
return node
603-
}
679+
680+
// Use pre-computed map for O(1) lookup instead of iterating over lookupKinds
681+
const kind = IdentifierToKind.get(callee.property.name)
682+
if (kind && lookupKinds.has(kind)) {
683+
return node
604684
}
605685

606686
return undefined
Lines changed: 18 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,26 @@
11
import * as t from '@babel/types'
2-
import { getRootCallExpression } from '../start-compiler-plugin/utils'
3-
import type * as babel from '@babel/core'
4-
2+
import type { RewriteCandidate } from './types'
3+
4+
/**
5+
* Handles createMiddleware transformations.
6+
*
7+
* @param candidate - The rewrite candidate containing path and method chain
8+
* @param opts - Options including the environment
9+
*/
510
export function handleCreateMiddleware(
6-
path: babel.NodePath<t.CallExpression>,
11+
candidate: RewriteCandidate,
712
opts: {
813
env: 'client' | 'server'
914
},
1015
) {
1116
if (opts.env === 'server') {
1217
throw new Error('handleCreateMiddleware should not be called on the server')
1318
}
14-
const rootCallExpression = getRootCallExpression(path)
15-
16-
const callExpressionPaths = {
17-
middleware: null as babel.NodePath<t.CallExpression> | null,
18-
inputValidator: null as babel.NodePath<t.CallExpression> | null,
19-
client: null as babel.NodePath<t.CallExpression> | null,
20-
server: null as babel.NodePath<t.CallExpression> | null,
21-
}
22-
23-
const validMethods = Object.keys(callExpressionPaths)
2419

25-
rootCallExpression.traverse({
26-
MemberExpression(memberExpressionPath) {
27-
if (t.isIdentifier(memberExpressionPath.node.property)) {
28-
const name = memberExpressionPath.node.property
29-
.name as keyof typeof callExpressionPaths
20+
const { inputValidator, server } = candidate.methodChain
3021

31-
if (
32-
validMethods.includes(name) &&
33-
memberExpressionPath.parentPath.isCallExpression()
34-
) {
35-
callExpressionPaths[name] = memberExpressionPath.parentPath
36-
}
37-
}
38-
},
39-
})
40-
41-
if (callExpressionPaths.inputValidator) {
42-
const innerInputExpression =
43-
callExpressionPaths.inputValidator.node.arguments[0]
22+
if (inputValidator) {
23+
const innerInputExpression = inputValidator.callPath.node.arguments[0]
4424

4525
if (!innerInputExpression) {
4626
throw new Error(
@@ -49,23 +29,17 @@ export function handleCreateMiddleware(
4929
}
5030

5131
// remove the validator call expression
52-
if (t.isMemberExpression(callExpressionPaths.inputValidator.node.callee)) {
53-
callExpressionPaths.inputValidator.replaceWith(
54-
callExpressionPaths.inputValidator.node.callee.object,
32+
if (t.isMemberExpression(inputValidator.callPath.node.callee)) {
33+
inputValidator.callPath.replaceWith(
34+
inputValidator.callPath.node.callee.object,
5535
)
5636
}
5737
}
5838

59-
const serverFnPath = callExpressionPaths.server?.get(
60-
'arguments.0',
61-
) as babel.NodePath<any>
62-
63-
if (callExpressionPaths.server && serverFnPath.node) {
39+
if (server && server.firstArgPath?.node) {
6440
// remove the server call expression
65-
if (t.isMemberExpression(callExpressionPaths.server.node.callee)) {
66-
callExpressionPaths.server.replaceWith(
67-
callExpressionPaths.server.node.callee.object,
68-
)
41+
if (t.isMemberExpression(server.callPath.node.callee)) {
42+
server.callPath.replaceWith(server.callPath.node.callee.object)
6943
}
7044
}
7145
}

0 commit comments

Comments
 (0)