Open History to see the last commit
1/// <reference types="vite/client" />
2import crypto from 'node:crypto'
3import { TanStackDirectiveFunctionsPluginEnv } from '@tanstack/directive-functions-plugin'
4import type { DevEnvironment, Plugin } from 'vite'
5import type {
6 DirectiveFn,
7 GenerateFunctionIdFn,
8 ReplacerFn,
9} from '@tanstack/directive-functions-plugin'
10β
11export type GenerateFunctionIdFnOptional = (
12 opts: Omit<Parameters<GenerateFunctionIdFn>[0], 'extractedFilename'>,
13) => string | undefined
14β
15export type TanStackServerFnPluginOpts = {
16 /**
17 * The virtual import ID that will be used to import the server function manifest.
18 * This virtual import ID will be used in the server build to import the manifest
19 * and its modules.
20 */
21 manifestVirtualImportId: string
22 generateFunctionId?: GenerateFunctionIdFnOptional
23 client: ServerFnPluginEnvOpts
24 server: ServerFnPluginEnvOpts
25}
26β
27export type ServerFnPluginEnvOpts = {
28 getRuntimeCode: () => string
29 replacer: ReplacerFn
30 envName?: string
31}
32β
33const debug =
34 process.env.TSR_VITE_DEBUG &&
35 ['true', 'server-functions-plugin'].includes(process.env.TSR_VITE_DEBUG)
36β
37export function TanStackServerFnPlugin(
38 _opts: TanStackServerFnPluginOpts,
39): Array<Plugin> {
40 const opts = {
41 ..._opts,
42 client: {
43 ..._opts.client,
44 envName: _opts.client.envName || 'client',
45 },
46 server: {
47 ..._opts.server,
48 envName: _opts.server.envName || 'server',
49 },
50 }
51β
52 const directiveFnsById: Record<string, DirectiveFn> = {}
53 let serverDevEnv: DevEnvironment | undefined
54β
55 const onDirectiveFnsById = (d: Record<string, DirectiveFn>) => {
56 if (serverDevEnv) {
57 return
58 }
59 if (debug) {
60 console.info(`onDirectiveFnsById received: `, d)
61 }
62 Object.assign(directiveFnsById, d)
63 if (debug) {
64 console.info(`directiveFnsById after update: `, directiveFnsById)
65 }
66 }
67β
68 const entryIdToFunctionId = new Map<string, string>()
69 const functionIds = new Set<string>()
70β
71 function withTrailingSlash(path: string): string {
72 if (path[path.length - 1] !== '/') {
73 return `${path}/`
74 }
75 return path
76 }
77β
78 const generateFunctionId: GenerateFunctionIdFn = ({
79 extractedFilename,
80 functionName,
81 filename,
82 }) => {
83 if (serverDevEnv) {
84 const root = serverDevEnv.config.root
85 const rootWithTrailingSlash = withTrailingSlash(root)
86 let file = extractedFilename
87 if (extractedFilename.startsWith(rootWithTrailingSlash)) {
88 file = extractedFilename.slice(rootWithTrailingSlash.length)
89 }
90 file = `/@id/${file}`
91β
92 const serverFn: {
93 file: string
94 export: string
95 } = {
96 file,
97 export: functionName,
98 }
99 const base64 = Buffer.from(JSON.stringify(serverFn), 'utf8').toString(
100 'base64url',
101 )
102 return base64
103 }
104β
105 // production build allows to override the function ID generation
106 const entryId = `${filename}--${functionName}`
107 let functionId = entryIdToFunctionId.get(entryId)
108 if (functionId === undefined) {
109 if (opts.generateFunctionId) {
110 functionId = opts.generateFunctionId({
111 functionName,
112 filename,
113 })
114 }
115 if (!functionId) {
116 functionId = crypto.createHash('sha256').update(entryId).digest('hex')
117 }
118 // Deduplicate in case the generated id conflicts with an existing id
119 if (functionIds.has(functionId)) {
120 let deduplicatedId
121 let iteration = 0
122 do {
123 deduplicatedId = `${functionId}_${++iteration}`
124 } while (functionIds.has(deduplicatedId))
125 functionId = deduplicatedId
126 }
127 entryIdToFunctionId.set(entryId, functionId)
128 functionIds.add(functionId)
129 }
130 return functionId
131 }
132 const directive = 'use server'
133 const directiveLabel = 'Server Function'
134β
135 const resolvedManifestVirtualImportId = resolveViteId(
136 opts.manifestVirtualImportId,
137 )
138β
139 return [
140 // The client plugin is used to compile the client directives
141 // and save them so we can create a manifest
142 TanStackDirectiveFunctionsPluginEnv({
143 directive,
144 directiveLabel,
145 onDirectiveFnsById,
146 generateFunctionId,
147 environments: {
148 client: {
149 envLabel: 'Client',
150 getRuntimeCode: opts.client.getRuntimeCode,
151 replacer: opts.client.replacer,
152 envName: opts.client.envName,
153 },
154 server: {
155 envLabel: 'Server',
156 getRuntimeCode: opts.server.getRuntimeCode,
157 replacer: opts.server.replacer,
158 envName: opts.server.envName,
159 },
160 },
161 }),
162 {
163 // On the server, we need to be able to read the server-function manifest from the client build.
164 // This is likely used in the handler for server functions, so we can find the server function
165 // by its ID, import it, and call it.
166 name: 'tanstack-start-server-fn-vite-plugin-manifest-server',
167 enforce: 'pre',
168 configureServer(viteDevServer) {
169 serverDevEnv = viteDevServer.environments[opts.server.envName]
170 if (!serverDevEnv) {
171 throw new Error(
172 `TanStackServerFnPluginEnv: environment "${opts.server.envName}" not found`,
173 )
174 }
175 },
176 resolveId: {
177 filter: { id: new RegExp(opts.manifestVirtualImportId) },
178 handler() {
179 return resolvedManifestVirtualImportId
180 },
181 },
182 load: {
183 filter: { id: new RegExp(resolvedManifestVirtualImportId) },
184 handler() {
185 if (this.environment.name !== opts.server.envName) {
186 return `export default {}`
187 }
188β
189 if (this.environment.mode !== 'build') {
190 const mod = `
191 export async function getServerFnById(id) {
192 const decoded = Buffer.from(id, 'base64url').toString('utf8')
193 const devServerFn = JSON.parse(decoded)
194 const mod = await import(/* @vite-ignore */ devServerFn.file)
195 return mod[devServerFn.export]
196 }
197 `
198 return mod
199 }
200β
201 const mod = `
202 const manifest = {${Object.entries(directiveFnsById)
203 .map(
204 ([id, fn]: any) =>
205 `'${id}': {
206 functionName: '${fn.functionName}',
207 importer: () => import(${JSON.stringify(fn.extractedFilename)})
208 }`,
209 )
210 .join(',')}}
211 export async function getServerFnById(id) {
212 const serverFnInfo = manifest[id]
213 if (!serverFnInfo) {
214 throw new Error('Server function info not found for ' + id)
215 }
216 const fnModule = await serverFnInfo.importer()
217β
218 if (!fnModule) {
219 console.info('serverFnInfo', serverFnInfo)
220 throw new Error('Server function module not resolved for ' + id)
221 }
222β
223 const action = fnModule[serverFnInfo.functionName]
224β
225 if (!action) {
226 console.info('serverFnInfo', serverFnInfo)
227 console.info('fnModule', fnModule)
228β
229 throw new Error(
230 \`Server function module export not resolved for serverFn ID: \${id}\`,
231 )
232 }
233 return action
234 }
235 `
236β
237 return mod
238 },
239 },
240 },
241 ]
242}
243β
244function resolveViteId(id: string) {
245 return `\0${id}`
246}