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