diff --git a/.prettierignore b/.prettierignore index 210d68c1b1..a234ee7bd1 100644 --- a/.prettierignore +++ b/.prettierignore @@ -13,4 +13,5 @@ pnpm-lock.yaml node_modules **/test-results -**/tests/generator/file-modification/routes/(test)/* \ No newline at end of file +**/tests/generator/file-modification/routes/(test)/* +/.nx/workspace-data \ No newline at end of file diff --git a/examples/react/start-basic/app/routes/deferred.tsx b/examples/react/start-basic/app/routes/deferred.tsx index 7cc7f8b9b5..606ab69b80 100644 --- a/examples/react/start-basic/app/routes/deferred.tsx +++ b/examples/react/start-basic/app/routes/deferred.tsx @@ -3,13 +3,13 @@ import { createServerFn } from '@tanstack/start' import { Suspense, useState } from 'react' const personServerFn = createServerFn({ method: 'GET' }) - .validator((d) => d as string) + .validator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .validator((d) => d as string) + .validator((d: string) => d) .handler(async ({ data: name }) => { await new Promise((r) => setTimeout(r, 1000)) return { name, randomNumber: Math.floor(Math.random() * 100) } diff --git a/examples/react/start-basic/app/routes/posts.tsx b/examples/react/start-basic/app/routes/posts.tsx index ae49032459..2b397ec6ba 100644 --- a/examples/react/start-basic/app/routes/posts.tsx +++ b/examples/react/start-basic/app/routes/posts.tsx @@ -1,8 +1,22 @@ import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '../utils/posts' +import { createServerFnClient } from '@tanstack/start' + +const serverFnClient = createServerFnClient({ + baseUrl: + process.env.NODE_ENV === 'production' + ? 'https://my-site.com/_server' + : 'http://localhost:3000/_server', +}) export const Route = createFileRoute('/posts')({ - loader: async () => fetchPosts(), + // loader: async () => fetchPosts(), + loader: () => + serverFnClient + .fetch({ + functionId: 'fetchPosts', + method: 'GET', + }) + .then((d) => d.result), component: PostsComponent, }) diff --git a/examples/react/start-basic/app/utils/posts.tsx b/examples/react/start-basic/app/utils/posts.tsx index 196498f8c9..6cc1be1438 100644 --- a/examples/react/start-basic/app/utils/posts.tsx +++ b/examples/react/start-basic/app/utils/posts.tsx @@ -9,9 +9,9 @@ export type PostType = { body: string } -export const fetchPost = createServerFn({ method: 'GET' }) +export const fetchPost = createServerFn({ id: 'fetchPost', method: 'GET' }) .middleware([logMiddleware]) - .validator((d) => d as string) + .validator((d: string) => d) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) const post = await axios @@ -28,8 +28,8 @@ export const fetchPost = createServerFn({ method: 'GET' }) return post }) -export const fetchPosts = createServerFn({ method: 'GET' }) - .middleware([logMiddleware]) +export const fetchPosts = createServerFn({ id: 'fetchPosts', method: 'GET' }) + // .middleware([logMiddleware]) .handler(async () => { console.info('Fetching posts...') return axios diff --git a/examples/react/start-supabase-basic/app/utils/posts.ts b/examples/react/start-supabase-basic/app/utils/posts.ts index 3c8b8d2434..6eb213af1f 100644 --- a/examples/react/start-supabase-basic/app/utils/posts.ts +++ b/examples/react/start-supabase-basic/app/utils/posts.ts @@ -9,7 +9,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'GET' }) - .validator((d) => d as string) + .validator((d: string) => d) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios diff --git a/package.json b/package.json index 1c40996f6d..4007d6ba70 100644 --- a/package.json +++ b/package.json @@ -81,9 +81,7 @@ "@tanstack/arktype-adapter": "workspace:*", "@tanstack/start": "workspace:*", "@tanstack/start-vite-plugin": "workspace:*", - "@tanstack/eslint-plugin-router": "workspace:*", - "temp-react": "0.0.0-experimental-035a41c4e-20230704", - "temp-react-dom": "0.0.0-experimental-035a41c4e-20230704" + "@tanstack/eslint-plugin-router": "workspace:*" } } } diff --git a/packages/router-plugin/src/core/code-splitter/compilers.ts b/packages/router-plugin/src/core/code-splitter/compilers.ts index 84f082e1cc..ba2485b7d8 100644 --- a/packages/router-plugin/src/core/code-splitter/compilers.ts +++ b/packages/router-plugin/src/core/code-splitter/compilers.ts @@ -270,6 +270,7 @@ export function compileCodeSplitReferenceRoute(opts: ParseAstOptions) { return generate(ast, { sourceMaps: true, sourceFileName: opts.filename, + minified: process.env.NODE_ENV === 'production', }) } @@ -543,6 +544,7 @@ export function compileCodeSplitVirtualRoute(opts: ParseAstOptions) { return generate(ast, { sourceMaps: true, sourceFileName: opts.filename, + minified: process.env.NODE_ENV === 'production', }) } diff --git a/packages/server-functions-vite-plugin/README.md b/packages/server-functions-vite-plugin/README.md new file mode 100644 index 0000000000..798fa094a3 --- /dev/null +++ b/packages/server-functions-vite-plugin/README.md @@ -0,0 +1,5 @@ + + +# TanStack Start Vite Plugin + +See https://tanstack.com/router/latest/docs/framework/react/guide/file-based-routing diff --git a/packages/server-functions-vite-plugin/eslint.config.js b/packages/server-functions-vite-plugin/eslint.config.js new file mode 100644 index 0000000000..8ce6ad05fc --- /dev/null +++ b/packages/server-functions-vite-plugin/eslint.config.js @@ -0,0 +1,5 @@ +// @ts-check + +import rootConfig from '../../eslint.config.js' + +export default [...rootConfig] diff --git a/packages/server-functions-vite-plugin/package.json b/packages/server-functions-vite-plugin/package.json new file mode 100644 index 0000000000..831a76d956 --- /dev/null +++ b/packages/server-functions-vite-plugin/package.json @@ -0,0 +1,89 @@ +{ + "name": "@tanstack/directive-functions-plugin", + "version": "1.87.3", + "description": "Modern and scalable routing for React applications", + "author": "Tanner Linsley", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/TanStack/router.git", + "directory": "packages/directive-functions-plugin" + }, + "homepage": "https://tanstack.com/start", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "keywords": [ + "react", + "location", + "router", + "routing", + "async", + "async router", + "typescript" + ], + "scripts": { + "clean": "rimraf ./dist && rimraf ./coverage", + "test": "pnpm test:eslint && pnpm test:types && pnpm test:build && pnpm test:unit", + "test:unit": "vitest", + "test:unit:dev": "vitest --watch", + "test:eslint": "eslint ./src", + "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", + "test:types:ts52": "node ../../node_modules/typescript52/lib/tsc.js", + "test:types:ts53": "node ../../node_modules/typescript53/lib/tsc.js", + "test:types:ts54": "node ../../node_modules/typescript54/lib/tsc.js", + "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", + "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", + "test:types:ts57": "tsc", + "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", + "build": "vite build" + }, + "type": "module", + "types": "dist/esm/index.d.ts", + "main": "dist/cjs/index.cjs", + "module": "dist/esm/index.js", + "exports": { + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/cjs/index.d.cts", + "default": "./dist/cjs/index.cjs" + } + }, + "./package.json": "./package.json" + }, + "sideEffects": false, + "files": [ + "dist", + "src" + ], + "engines": { + "node": ">=12" + }, + "dependencies": { + "@babel/code-frame": "7.26.2", + "@babel/core": "^7.26.0", + "@babel/generator": "^7.26.3", + "@babel/parser": "^7.26.3", + "@babel/plugin-syntax-jsx": "^7.25.9", + "@babel/plugin-syntax-typescript": "^7.25.9", + "@babel/template": "^7.25.9", + "@babel/traverse": "^7.26.4", + "@babel/types": "^7.26.3", + "@types/babel__code-frame": "^7.0.6", + "@types/babel__core": "^7.20.5", + "@types/babel__generator": "^7.6.8", + "@types/babel__template": "^7.4.4", + "@types/babel__traverse": "^7.20.6", + "@types/diff": "^6.0.0", + "babel-dead-code-elimination": "^1.0.6", + "chalk": "^5.3.0", + "dedent": "^1.5.3", + "diff": "^7.0.0", + "tiny-invariant": "^1.3.3" + } +} diff --git a/packages/server-functions-vite-plugin/src/ast.ts b/packages/server-functions-vite-plugin/src/ast.ts new file mode 100644 index 0000000000..c353b97abc --- /dev/null +++ b/packages/server-functions-vite-plugin/src/ast.ts @@ -0,0 +1,20 @@ +import { parse } from '@babel/parser' +import type { ParseResult } from '@babel/parser' + +export type ParseAstOptions = { + code: string + filename: string + root: string +} + +export function parseAst(opts: ParseAstOptions): ParseResult { + return parse(opts.code, { + plugins: ['jsx', 'typescript'], + sourceType: 'module', + ...{ + root: opts.root, + filename: opts.filename, + sourceMaps: true, + }, + }) +} diff --git a/packages/server-functions-vite-plugin/src/compilers.ts b/packages/server-functions-vite-plugin/src/compilers.ts new file mode 100644 index 0000000000..ea2d2b46fe --- /dev/null +++ b/packages/server-functions-vite-plugin/src/compilers.ts @@ -0,0 +1,590 @@ +import path from 'node:path' +import * as babel from '@babel/core' +import _generate from '@babel/generator' + +import { isIdentifier, isVariableDeclarator } from '@babel/types' +import { codeFrameColumns } from '@babel/code-frame' +import { deadCodeElimination } from 'babel-dead-code-elimination' +import { parseAst } from './ast' +import type { ParseAstOptions } from './ast' + +let generate = _generate + +if ('default' in generate) { + generate = generate.default as typeof generate +} + +export interface DirectiveFn { + hasStableId: boolean + nodePath: SupportedFunctionPath + functionName: string + functionId: string + referenceName: string + splitFilename: string + filename: string + chunkName: string +} + +export type SupportedFunctionPath = + | babel.NodePath + | babel.NodePath + | babel.NodePath + +export type ReplacerFn = (opts: { + fn: string + splitImportFn: string + filename: string + functionId: string + isSplitFn: boolean +}) => string + +// const debug = process.env.TSR_VITE_DEBUG === 'true' + +export type CompileDirectivesOpts = ParseAstOptions & { + directive: string + directiveLabel: string + getRuntimeCode?: (opts: { + directiveFnsById: Record + }) => string + replacer: ReplacerFn + devSplitImporter: string +} + +export function compileDirectives(opts: CompileDirectivesOpts) { + const [_, searchParamsStr] = opts.filename.split('?') + const searchParams = new URLSearchParams(searchParamsStr) + const directiveSplitParam = `tsr-directive-${opts.directive.replace(/[^a-zA-Z0-9]/g, '-')}-split` + const functionName = searchParams.get(directiveSplitParam) + + const ast = parseAst(opts) + const directiveFnsById = findDirectives(ast, { + ...opts, + splitFunctionName: functionName, + directiveSplitParam, + }) + + const directiveFnsByFunctionName = Object.fromEntries( + Object.entries(directiveFnsById).map(([id, fn]) => [fn.functionName, fn]), + ) + + // Add runtime code if there are directives + // Add runtime code if there are directives + if (Object.keys(directiveFnsById).length > 0) { + // Add a vite import to the top of the file + ast.program.body.unshift( + babel.types.importDeclaration( + [babel.types.importDefaultSpecifier(babel.types.identifier('vite'))], + babel.types.stringLiteral('vite'), + ), + ) + + if (opts.getRuntimeCode) { + const runtimeImport = babel.template.statement( + opts.getRuntimeCode({ directiveFnsById }), + )() + ast.program.body.unshift(runtimeImport) + } + } + + // If there is a functionName, we need to remove all exports + // then make sure that our function is exported under the + // directive name + if (functionName) { + const directiveFn = directiveFnsByFunctionName[functionName] + + if (!directiveFn) { + throw new Error(`${opts.directiveLabel} ${functionName} not found`) + } + + safeRemoveExports(ast) + + ast.program.body.push( + babel.types.exportDefaultDeclaration( + babel.types.identifier(directiveFn.referenceName), + ), + ) + } + + deadCodeElimination(ast) + + const compiledResult = generate(ast, { + sourceMaps: true, + sourceFileName: opts.filename, + minified: process.env.NODE_ENV === 'production', + }) + + return { + compiledResult, + directiveFnsById, + } +} + +function findNearestVariableName( + path: babel.NodePath, + directiveLabel: string, +): string { + let currentPath: babel.NodePath | null = path + const nameParts: Array = [] + + while (currentPath) { + const name = (() => { + // Check for named function expression + if ( + babel.types.isFunctionExpression(currentPath.node) && + currentPath.node.id + ) { + return currentPath.node.id.name + } + + // Handle method chains + if (babel.types.isCallExpression(currentPath.node)) { + const current = currentPath.node.callee + const chainParts: Array = [] + + // Get the nearest method name (if it's a method call) + if (babel.types.isMemberExpression(current)) { + if (babel.types.isIdentifier(current.property)) { + chainParts.unshift(current.property.name) + } + + // Get the base callee + let base = current.object + while (!babel.types.isIdentifier(base)) { + if (babel.types.isCallExpression(base)) { + base = base.callee as babel.types.Expression + } else if (babel.types.isMemberExpression(base)) { + base = base.object + } else { + break + } + } + if (babel.types.isIdentifier(base)) { + chainParts.unshift(base.name) + } + } else if (babel.types.isIdentifier(current)) { + chainParts.unshift(current.name) + } + + if (chainParts.length > 0) { + return chainParts.join('_') + } + } + + // Rest of the existing checks... + if (babel.types.isFunctionDeclaration(currentPath.node)) { + return currentPath.node.id?.name + } + + if (babel.types.isIdentifier(currentPath.node)) { + return currentPath.node.name + } + + if ( + isVariableDeclarator(currentPath.node) && + isIdentifier(currentPath.node.id) + ) { + return currentPath.node.id.name + } + + if ( + babel.types.isClassMethod(currentPath.node) || + babel.types.isObjectMethod(currentPath.node) + ) { + throw new Error( + `${directiveLabel} in ClassMethod or ObjectMethod not supported`, + ) + } + + return '' + })() + + if (name) { + nameParts.unshift(name) + } + + currentPath = currentPath.parentPath + } + + return nameParts.length > 0 ? nameParts.join('_') : 'anonymous' +} + +function makeFileLocationUrlSafe(location: string): string { + return location + .replace(/[^a-zA-Z0-9-_]/g, '_') // Replace unsafe chars with underscore + .replace(/_{2,}/g, '_') // Collapse multiple underscores + .replace(/^_|_$/g, '') // Trim leading/trailing underscores +} + +function makeIdentifierSafe(identifier: string): string { + return identifier + .replace(/[^a-zA-Z0-9_$]/g, '_') // Replace unsafe chars with underscore + .replace(/^[0-9]/, '_$&') // Prefix leading number with underscore + .replace(/^\$/, '_$') // Prefix leading $ with underscore + .replace(/_{2,}/g, '_') // Collapse multiple underscores + .replace(/^_|_$/g, '') // Trim leading/trailing underscores +} + +export function findDirectives( + ast: babel.types.File, + opts: ParseAstOptions & { + directive: string + directiveLabel: string + replacer?: ReplacerFn + splitFunctionName?: string | null + directiveSplitParam: string + devSplitImporter: string + }, +) { + const directiveFnsById: Record = {} + const functionNameCounts: Record = {} + + let programPath: babel.NodePath + + babel.traverse(ast, { + Program(path) { + programPath = path + }, + }) + + // Does the file have the directive in the program body? + const hasFileDirective = ast.program.directives.some( + (directive) => directive.value.value === opts.directive, + ) + + // If the entire file has a directive, we need to compile all of the functions that are + // exported by the file. + if (hasFileDirective) { + // Find all of the exported functions + // They must be either function declarations or const function/anonymous function declarations + babel.traverse(ast, { + ExportDefaultDeclaration(path) { + if (babel.types.isFunctionDeclaration(path.node.declaration)) { + compileDirective(path.get('declaration') as SupportedFunctionPath) + } + }, + ExportNamedDeclaration(path) { + if (babel.types.isFunctionDeclaration(path.node.declaration)) { + compileDirective(path.get('declaration') as SupportedFunctionPath) + } + }, + }) + } else { + // Find all directives + babel.traverse(ast, { + DirectiveLiteral(nodePath) { + if (nodePath.node.value === opts.directive) { + const directiveFn = nodePath.findParent((p) => p.isFunction()) as + | SupportedFunctionPath + | undefined + + if (!directiveFn) return + + // Handle class and object methods which are not supported + const isGenerator = + directiveFn.isFunction() && directiveFn.node.generator + + const isClassMethod = directiveFn.isClassMethod() + const isObjectMethod = directiveFn.isObjectMethod() + + if (isClassMethod || isObjectMethod || isGenerator) { + throw codeFrameError( + opts.code, + directiveFn.node.loc, + `"${opts.directive}" in ${isClassMethod ? 'class' : isObjectMethod ? 'object method' : 'generator function'} not supported`, + ) + } + + // If the function is inside another block that isn't the program, + // Error out. This is not supported. + const nearestBlock = directiveFn.findParent( + (p) => (p.isBlockStatement() || p.isScopable()) && !p.isProgram(), + ) + + if (nearestBlock) { + throw codeFrameError( + opts.code, + nearestBlock.node.loc, + `${opts.directiveLabel}s cannot be nested in other blocks or functions`, + ) + } + + if ( + !directiveFn.isFunctionDeclaration() && + !directiveFn.isFunctionExpression() && + !( + directiveFn.isArrowFunctionExpression() && + babel.types.isBlockStatement(directiveFn.node.body) + ) + ) { + throw codeFrameError( + opts.code, + directiveFn.node.loc, + `${opts.directiveLabel}s must be function declarations or function expressions`, + ) + } + + compileDirective(directiveFn) + } + }, + }) + } + + return directiveFnsById + + function compileDirective(directiveFn: SupportedFunctionPath) { + // Remove the directive directive from the function body + let directiveId: string | undefined + + if ( + babel.types.isFunction(directiveFn.node) && + babel.types.isBlockStatement(directiveFn.node.body) + ) { + directiveFn.node.body.directives = + directiveFn.node.body.directives.filter( + (directive) => directive.value.value !== opts.directive, + ) + + // Look for an optional id: \d+ directive + const idDirective = directiveFn.node.body.directives.find((directive) => + directive.value.value.startsWith('id:'), + ) + + if (idDirective) { + directiveId = idDirective.value.value.split(':')[1]?.trim() + } + } + + // Find the nearest variable name + let functionName = findNearestVariableName(directiveFn, opts.directiveLabel) + + // Count the number of functions with the same baseLabel + functionNameCounts[functionName] = + (functionNameCounts[functionName] || 0) + 1 + + // If there are multiple functions with the same fnName, + // append a unique identifier to the functionId + functionName = + functionNameCounts[functionName]! > 1 + ? `${functionName}_${functionNameCounts[functionName]! - 1}` + : functionName + + // Move the function to program level while preserving its position + // in the program body + const programBody = programPath.node.body + + const topParent = + directiveFn.findParent((p) => !!p.parentPath?.isProgram()) || directiveFn + + const topParentIndex = programBody.indexOf(topParent.node as any) + + // Determine the reference name for the function + let referenceName = makeIdentifierSafe(functionName) + + // Crawl the scope to refresh all the bindings + programPath.scope.crawl() + + // If we find this referece in the scope, we need to make it unique + while (programPath.scope.hasBinding(referenceName)) { + const [realReferenceName, count] = referenceName.split(/_(\d+)$/) + referenceName = realReferenceName + `_${Number(count || '0') + 1}` + } + + // if (referenceCounts.get(referenceName) === 0) { + + // referenceName += `_${(referenceCounts.get(referenceName) || 0) + 1}` + + // If the reference name came from the function declaration, + // // We need to update the function name to match the reference name + // if (babel.types.isFunctionDeclaration(directiveFn.node)) { + // console.log('updating function name', directiveFn.node.id!.name) + // directiveFn.node.id!.name = referenceName + // } + + // If the function has a parent that isn't the program, + // we need to replace it with an identifier and + // hoist the function to the top level as a const declaration + if (!directiveFn.parentPath.isProgram()) { + // Then place the function at the top level + programBody.splice( + topParentIndex, + 0, + babel.types.variableDeclaration('const', [ + babel.types.variableDeclarator( + babel.types.identifier(referenceName), + babel.types.toExpression(directiveFn.node as any), + ), + ]), + ) + + // If it's an exported named function, we need to swap it with an + // export const originalFunctionName = referenceName + if ( + babel.types.isExportNamedDeclaration(directiveFn.parentPath.node) && + (babel.types.isFunctionDeclaration(directiveFn.node) || + babel.types.isFunctionExpression(directiveFn.node)) && + babel.types.isIdentifier(directiveFn.node.id) + ) { + const originalFunctionName = directiveFn.node.id.name + programBody.splice( + topParentIndex + 1, + 0, + babel.types.exportNamedDeclaration( + babel.types.variableDeclaration('const', [ + babel.types.variableDeclarator( + babel.types.identifier(originalFunctionName), + babel.types.identifier(referenceName), + ), + ]), + ), + ) + + directiveFn.remove() + } else { + directiveFn.replaceWith(babel.types.identifier(referenceName)) + } + + directiveFn = programPath.get( + `body.${topParentIndex}.declarations.0.init`, + ) as SupportedFunctionPath + } + + const functionId = + directiveId || + makeFileLocationUrlSafe( + `${opts.filename.replace( + path.extname(opts.filename), + '', + )}--${functionName}`.replace(opts.root, ''), + ) + + const [filename, searchParamsStr] = opts.filename.split('?') + const searchParams = new URLSearchParams(searchParamsStr) + searchParams.set(opts.directiveSplitParam, functionName) + const splitFilename = `${filename}?${searchParams.toString()}` + + // If a replacer is provided, replace the function with the replacer + if (opts.replacer) { + const replacer = opts.replacer({ + fn: '$$fn$$', + splitImportFn: '$$splitImportFn$$', + // splitFilename, + filename: filename!, + functionId: functionId, + isSplitFn: functionName === opts.splitFunctionName, + }) + + const replacement = babel.template.expression(replacer, { + placeholderPattern: false, + placeholderWhitelist: new Set(['$$fn$$', '$$splitImportFn$$']), + })({ + ...(replacer.includes('$$fn$$') + ? { $$fn$$: babel.types.toExpression(directiveFn.node) } + : {}), + ...(replacer.includes('$$splitImportFn$$') + ? { + $$splitImportFn$$: + process.env.NODE_ENV === 'production' + ? `(...args) => import(${JSON.stringify(splitFilename)}).then(module => module.default(...args))` + : `(...args) => ${opts.devSplitImporter}(${JSON.stringify(splitFilename)}).then(module => module.default(...args))`, + } + : {}), + }) + + directiveFn.replaceWith(replacement) + } + + // Finally register the directive to + // our map of directives + directiveFnsById[functionId] = { + hasStableId: !!directiveId, + nodePath: directiveFn, + referenceName, + functionName: functionName || '', + functionId: functionId, + splitFilename, + filename: opts.filename, + chunkName: fileNameToChunkName(opts.root, splitFilename), + } + } +} + +function codeFrameError( + code: string, + loc: + | { + start: { line: number; column: number } + end: { line: number; column: number } + } + | undefined + | null, + message: string, +) { + if (!loc) { + return new Error(`${message} at unknown location`) + } + + const frame = codeFrameColumns( + code, + { + start: loc.start, + end: loc.end, + }, + { + highlightCode: true, + message, + }, + ) + + return new Error(frame) +} + +const safeRemoveExports = (ast: babel.types.File) => { + const programBody = ast.program.body + + const removeExport = ( + path: + | babel.NodePath + | babel.NodePath, + ) => { + // If the value is a function declaration, class declaration, or variable declaration, + // That means it has a name and can remain in the file, just unexported. + if ( + babel.types.isFunctionDeclaration(path.node.declaration) || + babel.types.isClassDeclaration(path.node.declaration) || + babel.types.isVariableDeclaration(path.node.declaration) + ) { + // If the value is a function declaration, class declaration, or variable declaration, + // That means it has a name and can remain in the file, just unexported. + if ( + babel.types.isFunctionDeclaration(path.node.declaration) || + babel.types.isClassDeclaration(path.node.declaration) || + babel.types.isVariableDeclaration(path.node.declaration) + ) { + // Move the declaration to the top level at the same index + const insertIndex = programBody.findIndex( + (node) => node === path.node.declaration, + ) + programBody.splice(insertIndex, 0, path.node.declaration as any) + } + } + + // Otherwise, remove the export declaration + path.remove() + } + + // Before we add our export, remove any other exports. + // Don't remove the thing they export, just the export declaration + babel.traverse(ast, { + ExportDefaultDeclaration(path) { + removeExport(path) + }, + ExportNamedDeclaration(path) { + removeExport(path) + }, + }) +} + +function fileNameToChunkName(root: string, fileName: string) { + // Replace anything that can't go into an import statement + return fileName.replace(root, '').replace(/[^a-zA-Z0-9_]/g, '_') +} diff --git a/packages/server-functions-vite-plugin/src/index.ts b/packages/server-functions-vite-plugin/src/index.ts new file mode 100644 index 0000000000..7f42dd8db7 --- /dev/null +++ b/packages/server-functions-vite-plugin/src/index.ts @@ -0,0 +1,245 @@ +import { fileURLToPath, pathToFileURL } from 'node:url' + +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import path from 'node:path' +import { compileDirectives } from './compilers' +import { logDiff } from './logger' +import type { CompileDirectivesOpts, DirectiveFn } from './compilers' +import type { Plugin } from 'vite' + +const debug = Boolean(process.env.TSR_VITE_DEBUG) + +export type ServerFunctionsViteOptions = Pick< + CompileDirectivesOpts, + 'directive' | 'directiveLabel' | 'getRuntimeCode' | 'replacer' +> + +export type CreateClientRpcFn = (functionId: string) => any +export type CreateSsrRpcFn = (functionId: string) => any +export type CreateServerRpcFn = ( + functionId: string, + splitImportFn: string, +) => any + +const createDirectiveRx = (directive: string) => + new RegExp(`"${directive}"|'${directive}'`, 'g') + +export function createTanStackServerFnPlugin(_opts?: {}): { + client: Array + ssr: Array + server: Array +} { + const ROOT = process.cwd() + const manifestFilename = + 'node_modules/.tanstack-start/server-functions-manifest.json' + const directiveFnsById: Record = {} + + const directiveFnsByIdToManifest = ( + directiveFnsById: Record, + ) => + Object.fromEntries( + Object.entries(directiveFnsById).map(([id, fn]) => [ + id, + { + functionName: fn.functionName, + referenceName: fn.referenceName, + splitFilename: fn.splitFilename, + filename: fn.filename, + chunkName: fn.chunkName, + }, + ]), + ) + + const readManifestPlugin = (): Plugin => ({ + name: 'tanstack-start-server-fn-vite-plugin-manifest', + enforce: 'pre', + resolveId: (id) => { + if (id === 'tsr:server-fn-manifest') { + return id + } + + return null + }, + load(id) { + if (id === 'tsr:server-fn-manifest') { + return `export default ${JSON.stringify( + directiveFnsByIdToManifest(directiveFnsById), + )}` + } + + return null + }, + }) + + return { + client: [ + // The client plugin is used to compile the client directives + // and save them so we can create a manifest + TanStackDirectiveFunctionsPlugin({ + directive: 'use server', + directiveLabel: 'Server Function', + getRuntimeCode: () => + `import { createClientRpc } from '@tanstack/start/client-runtime'`, + replacer: (opts) => + // On the client, all we need is the function ID + `createClientRpc(${JSON.stringify(opts.functionId)})`, + onDirectiveFnsById: (d) => { + // When directives are compiled, save them so we + // can create a manifest + Object.assign(directiveFnsById, d) + }, + }), + // Now that we have the directiveFnsById, we need to create a new + // virtual module that can be used to import that manifest + { + name: 'tanstack-start-server-fn-vite-plugin-build-client', + generateBundle() { + // We also need to create a production manifest so we can + // access it the server build, which does not run in the + // same vite build environment + console.log('Generating production manifest') + mkdirSync(path.dirname(manifestFilename), { recursive: true }) + writeFileSync( + path.join(ROOT, manifestFilename), + JSON.stringify(directiveFnsByIdToManifest(directiveFnsById)), + ) + }, + }, + ], + ssr: [ + readManifestPlugin(), + // The SSR plugin is used to compile the server directives + TanStackDirectiveFunctionsPlugin({ + directive: 'use server', + directiveLabel: 'Server Function', + getRuntimeCode: () => + `import { createSsrRpc } from '@tanstack/start/ssr-runtime'`, + replacer: (opts) => + // During SSR, we just need the function ID since our server environment + // is split into a worker. Similar to the client, we'll use the ID + // to call into the worker using a local http event. + `createSsrRpc(${JSON.stringify(opts.functionId)})`, + onDirectiveFnsById: (d) => { + // When directives are compiled, save them so we + // can create a manifest + Object.assign(directiveFnsById, d) + }, + }), + ], + server: [ + readManifestPlugin(), + // On the server, we need to compile the server functions + // so they can be called by other server functions. + // This is also where we split the server function into a separate file + // so we can load them on demand in the worker. + TanStackDirectiveFunctionsPlugin({ + directive: 'use server', + directiveLabel: 'Server Function', + getRuntimeCode: () => + `import { createServerRpc } from '@tanstack/start/server-runtime'`, + replacer: (opts) => + // By using the provided splitImportFn, we can both trigger vite + // to create a new chunk/entry for the server function and also + // replace other function references to it with the import statement + `createServerRpc(${JSON.stringify(opts.functionId)}, ${opts.isSplitFn ? opts.fn : opts.splitImportFn})`, + onDirectiveFnsById: (d) => { + // When directives are compiled, save them so we + // can create a manifest + Object.assign(directiveFnsById, d) + }, + }), + (() => { + let serverFunctionsManifest: Record + return { + name: 'tanstack-start-server-fn-vite-plugin-build-', + enforce: 'post', + apply: 'build', + config(config) { + // We use a file to store the manifest so we can access it between + // vite environments + serverFunctionsManifest = JSON.parse( + readFileSync(path.join(ROOT, manifestFilename), 'utf-8'), + ) + + return { + build: { + rollupOptions: { + output: { + chunkFileNames: '[name].mjs', + entryFileNames: '[name].mjs', + }, + treeshake: true, + }, + }, + } + }, + + configResolved(config) { + const serverFnEntries = Object.fromEntries( + Object.entries(serverFunctionsManifest).map(([id, fn]) => { + return [fn.chunkName, fn.splitFilename] + }), + ) + + config.build.rollupOptions.input = { + entry: Array.isArray(config.build.rollupOptions.input) + ? config.build.rollupOptions.input[0] + : typeof config.build.rollupOptions.input === 'object' && + 'entry' in config.build.rollupOptions.input + ? config.build.rollupOptions.input.entry + : ((() => { + throw new Error('Invalid input') + }) as any), + ...serverFnEntries, + } + console.log(config.build.rollupOptions.input) + }, + } + })(), + ], + } +} + +export function TanStackDirectiveFunctionsPlugin( + opts: ServerFunctionsViteOptions & { + onDirectiveFnsById?: (directiveFnsById: Record) => void + }, +): Plugin { + let ROOT: string = process.cwd() + + const directiveRx = createDirectiveRx(opts.directive) + + return { + name: 'tanstack-start-directive-vite-plugin', + enforce: 'pre', + configResolved: (config) => { + ROOT = config.root + }, + transform(code, id) { + const url = pathToFileURL(id) + url.searchParams.delete('v') + id = fileURLToPath(url).replace(/\\/g, '/') + + if (!directiveRx.test(code)) { + return null + } + + const { compiledResult, directiveFnsById } = compileDirectives({ + ...opts, + code, + root: ROOT, + filename: id, + // globalThis.app currently refers to Vinxi's app instance. In the future, it can just be the + // vite dev server instance we get from Nitro. + devSplitImporter: `(globalThis.app.getRouter('server').internals.devServer.ssrLoadModule)`, + }) + + opts.onDirectiveFnsById?.(directiveFnsById) + + if (debug) console.info('Directive Input/Output') + if (debug) logDiff(code, compiledResult.code) + + return compiledResult + }, + } +} diff --git a/packages/server-functions-vite-plugin/src/logger.ts b/packages/server-functions-vite-plugin/src/logger.ts new file mode 100644 index 0000000000..fd777080c3 --- /dev/null +++ b/packages/server-functions-vite-plugin/src/logger.ts @@ -0,0 +1,59 @@ +import chalk from 'chalk' +import { diffWords } from 'diff' + +export function logDiff(oldStr: string, newStr: string) { + const differences = diffWords(oldStr, newStr) + + let output = '' + let unchangedLines = '' + + function processUnchangedLines(lines: string): string { + const lineArray = lines.split('\n') + if (lineArray.length > 4) { + return [ + chalk.dim(lineArray[0]), + chalk.dim(lineArray[1]), + '', + chalk.dim.bold(`... (${lineArray.length - 4} lines) ...`), + '', + chalk.dim(lineArray[lineArray.length - 2]), + chalk.dim(lineArray[lineArray.length - 1]), + ].join('\n') + } + return chalk.dim(lines) + } + + differences.forEach((part, index) => { + const nextPart = differences[index + 1] + + if (part.added) { + if (unchangedLines) { + output += processUnchangedLines(unchangedLines) + unchangedLines = '' + } + output += chalk.green.bold(part.value) + if (nextPart?.removed) output += ' ' + } else if (part.removed) { + if (unchangedLines) { + output += processUnchangedLines(unchangedLines) + unchangedLines = '' + } + output += chalk.red.bold(part.value) + if (nextPart?.added) output += ' ' + } else { + unchangedLines += part.value + } + }) + + // Process any remaining unchanged lines at the end + if (unchangedLines) { + output += processUnchangedLines(unchangedLines) + } + + if (output) { + console.log('\nDiff:') + console.log(output) + } else { + console.log('No changes') + } +} diff --git a/packages/server-functions-vite-plugin/tests/compiler.test.ts b/packages/server-functions-vite-plugin/tests/compiler.test.ts new file mode 100644 index 0000000000..7092e1e348 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/compiler.test.ts @@ -0,0 +1,1083 @@ +import { describe, expect, test } from 'vitest' + +import { compileDirectives } from '../src/compilers' +import type { CompileDirectivesOpts } from '../src/compilers' + +const clientConfig: Omit = { + directive: 'use server', + directiveLabel: 'Server function', + root: './test-files', + filename: 'test.ts', + getRuntimeCode: () => 'import { createClientRpc } from "my-rpc-lib-client"', + replacer: (opts) => + `createClientRpc({ + filename: ${JSON.stringify(opts.filename)}, + functionId: ${JSON.stringify(opts.functionId)}, + })`, + devSplitImporter: `devImport`, +} + +const ssrConfig: Omit = { + directive: 'use server', + directiveLabel: 'Server function', + root: './test-files', + filename: 'test.ts', + getRuntimeCode: () => 'import { createSsrRpc } from "my-rpc-lib-server"', + replacer: (opts) => + `createSsrRpc({ + filename: ${JSON.stringify(opts.filename)}, + functionId: ${JSON.stringify(opts.functionId)}, + })`, + devSplitImporter: `devImport`, +} + +const serverConfig: Omit = { + directive: 'use server', + directiveLabel: 'Server function', + root: './test-files', + filename: 'test.ts', + getRuntimeCode: () => 'import { createServerRpc } from "my-rpc-lib-server"', + replacer: (opts) => + // On the server build, we need different code for the split function + // vs any other server functions the split function may reference + + // For the split function itself, we use the original function. + // For any other server functions the split function may reference, + // we use the splitImportFn which is a dynamic import of the split file. + `createServerRpc({ + fn: ${opts.isSplitFn ? opts.fn : opts.splitImportFn}, + filename: ${JSON.stringify(opts.filename)}, + functionId: ${JSON.stringify(opts.functionId)}, + })`, + devSplitImporter: `devImport`, +} + +describe('server function compilation', () => { + const code = ` + export const namedFunction = wrapper(function namedFunction() { + 'use server' + return 'hello' + }) + + export const arrowFunction = wrapper(() => { + 'use server' + return 'hello' + }) + + export const anonymousFunction = wrapper(function () { + 'use server' + return 'hello' + }) + + export const multipleDirectives = function multipleDirectives() { + 'use server' + 'use strict' + return 'hello' + } + + export const iife = (function () { + 'use server' + return 'hello' + })() + + export default function defaultExportFn() { + 'use server' + return 'hello' + } + + export function namedExportFn() { + 'use server' + return 'hello' + } + + export const exportedArrowFunction = wrapper(() => { + 'use server' + return 'hello' + }) + + export const namedExportConst = () => { + 'use server' + return usedFn() + } + + function usedFn() { + return 'hello' + } + + function unusedFn() { + return 'hello' + } + + const namedDefaultExport = 'namedDefaultExport' + export default namedDefaultExport + + const usedButNotExported = 'usedButNotExported' + + const namedExport = 'namedExport' + + export { + namedExport + } + + ` + + test('basic function declaration nested in other variable', () => { + const client = compileDirectives({ + ...clientConfig, + code, + }) + const ssr = compileDirectives({ ...ssrConfig, code }) + const splitFiles = Object.entries(ssr.directiveFnsById) + .map(([_fnId, directiveFn]) => { + return `// ${directiveFn.functionId}\n\n${ + compileDirectives({ + ...serverConfig, + code, + filename: directiveFn.splitFilename, + }).compiledResult.code + }` + }) + .join('\n\n\n') + + expect(client.compiledResult.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib-client"; + const namedFunction_wrapper_namedFunction = createClientRpc({ + filename: "test.ts", + functionId: "test--namedFunction_wrapper_namedFunction" + }); + export const namedFunction = wrapper(namedFunction_wrapper_namedFunction); + const arrowFunction_wrapper = createClientRpc({ + filename: "test.ts", + functionId: "test--arrowFunction_wrapper" + }); + export const arrowFunction = wrapper(arrowFunction_wrapper); + const anonymousFunction_wrapper = createClientRpc({ + filename: "test.ts", + functionId: "test--anonymousFunction_wrapper" + }); + export const anonymousFunction = wrapper(anonymousFunction_wrapper); + const multipleDirectives_multipleDirectives = createClientRpc({ + filename: "test.ts", + functionId: "test--multipleDirectives_multipleDirectives" + }); + export const multipleDirectives = multipleDirectives_multipleDirectives; + const iife_1 = createClientRpc({ + filename: "test.ts", + functionId: "test--iife" + }); + export const iife = iife_1(); + const defaultExportFn_1 = createClientRpc({ + filename: "test.ts", + functionId: "test--defaultExportFn" + }); + export default defaultExportFn_1; + const namedExportFn_1 = createClientRpc({ + filename: "test.ts", + functionId: "test--namedExportFn" + }); + export const namedExportFn = namedExportFn_1; + const exportedArrowFunction_wrapper = createClientRpc({ + filename: "test.ts", + functionId: "test--exportedArrowFunction_wrapper" + }); + export const exportedArrowFunction = wrapper(exportedArrowFunction_wrapper); + const namedExportConst_1 = createClientRpc({ + filename: "test.ts", + functionId: "test--namedExportConst" + }); + export const namedExportConst = namedExportConst_1; + const namedDefaultExport = 'namedDefaultExport'; + export default namedDefaultExport; + const namedExport = 'namedExport'; + export { namedExport };" + `) + + expect(ssr.compiledResult.code).toMatchInlineSnapshot(` + "import { createSsrRpc } from "my-rpc-lib-server"; + const namedFunction_wrapper_namedFunction = createSsrRpc({ + filename: "test.ts", + functionId: "test--namedFunction_wrapper_namedFunction" + }); + export const namedFunction = wrapper(namedFunction_wrapper_namedFunction); + const arrowFunction_wrapper = createSsrRpc({ + filename: "test.ts", + functionId: "test--arrowFunction_wrapper" + }); + export const arrowFunction = wrapper(arrowFunction_wrapper); + const anonymousFunction_wrapper = createSsrRpc({ + filename: "test.ts", + functionId: "test--anonymousFunction_wrapper" + }); + export const anonymousFunction = wrapper(anonymousFunction_wrapper); + const multipleDirectives_multipleDirectives = createSsrRpc({ + filename: "test.ts", + functionId: "test--multipleDirectives_multipleDirectives" + }); + export const multipleDirectives = multipleDirectives_multipleDirectives; + const iife_1 = createSsrRpc({ + filename: "test.ts", + functionId: "test--iife" + }); + export const iife = iife_1(); + const defaultExportFn_1 = createSsrRpc({ + filename: "test.ts", + functionId: "test--defaultExportFn" + }); + export default defaultExportFn_1; + const namedExportFn_1 = createSsrRpc({ + filename: "test.ts", + functionId: "test--namedExportFn" + }); + export const namedExportFn = namedExportFn_1; + const exportedArrowFunction_wrapper = createSsrRpc({ + filename: "test.ts", + functionId: "test--exportedArrowFunction_wrapper" + }); + export const exportedArrowFunction = wrapper(exportedArrowFunction_wrapper); + const namedExportConst_1 = createSsrRpc({ + filename: "test.ts", + functionId: "test--namedExportConst" + }); + export const namedExportConst = namedExportConst_1; + const namedDefaultExport = 'namedDefaultExport'; + export default namedDefaultExport; + const namedExport = 'namedExport'; + export { namedExport };" + `) + + expect(splitFiles).toMatchInlineSnapshot( + ` + "// test--namedFunction_wrapper_namedFunction + + import { createServerRpc } from "my-rpc-lib-server"; + const namedFunction_wrapper_namedFunction = createServerRpc({ + fn: function namedFunction() { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--namedFunction_wrapper_namedFunction" + }); + export default namedFunction_wrapper_namedFunction; + + + // test--arrowFunction_wrapper + + import { createServerRpc } from "my-rpc-lib-server"; + const arrowFunction_wrapper = createServerRpc({ + fn: () => { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--arrowFunction_wrapper" + }); + export default arrowFunction_wrapper; + + + // test--anonymousFunction_wrapper + + import { createServerRpc } from "my-rpc-lib-server"; + const anonymousFunction_wrapper = createServerRpc({ + fn: function () { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--anonymousFunction_wrapper" + }); + export default anonymousFunction_wrapper; + + + // test--multipleDirectives_multipleDirectives + + import { createServerRpc } from "my-rpc-lib-server"; + const multipleDirectives_multipleDirectives = createServerRpc({ + fn: function multipleDirectives() { + 'use strict'; + + return 'hello'; + }, + filename: "test.ts", + functionId: "test--multipleDirectives_multipleDirectives" + }); + export default multipleDirectives_multipleDirectives; + + + // test--iife + + import { createServerRpc } from "my-rpc-lib-server"; + const iife_1 = createServerRpc({ + fn: function () { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--iife" + }); + export default iife_1; + + + // test--defaultExportFn + + import { createServerRpc } from "my-rpc-lib-server"; + const defaultExportFn_1 = createServerRpc({ + fn: function defaultExportFn() { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--defaultExportFn" + }); + export default defaultExportFn_1; + + + // test--namedExportFn + + import { createServerRpc } from "my-rpc-lib-server"; + const namedExportFn_1 = createServerRpc({ + fn: function namedExportFn() { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--namedExportFn" + }); + export default namedExportFn_1; + + + // test--exportedArrowFunction_wrapper + + import { createServerRpc } from "my-rpc-lib-server"; + const exportedArrowFunction_wrapper = createServerRpc({ + fn: () => { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--exportedArrowFunction_wrapper" + }); + export default exportedArrowFunction_wrapper; + + + // test--namedExportConst + + import { createServerRpc } from "my-rpc-lib-server"; + const namedExportConst_1 = createServerRpc({ + fn: () => { + return usedFn(); + }, + filename: "test.ts", + functionId: "test--namedExportConst" + }); + function usedFn() { + return 'hello'; + } + export default namedExportConst_1;" + `, + ) + }) + + test('Does not support function declarations nested in other blocks', () => { + const code = ` + outer(() => { + function useServer() { + 'use server' + return 'hello' + } + }) + ` + + expect(() => + compileDirectives({ ...clientConfig, code }), + ).toThrowErrorMatchingInlineSnapshot( + ` + [Error: 1 | + > 2 | outer(() => { + | ^^ + > 3 | function useServer() { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 6 | } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 7 | }) + | ^^^^^^^ Server functions cannot be nested in other blocks or functions + 8 | ] + `, + ) + expect(() => + compileDirectives({ ...serverConfig, code }), + ).toThrowErrorMatchingInlineSnapshot( + ` + [Error: 1 | + > 2 | outer(() => { + | ^^ + > 3 | function useServer() { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 6 | } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 7 | }) + | ^^^^^^^ Server functions cannot be nested in other blocks or functions + 8 | ] + `, + ) + expect(() => + compileDirectives({ + ...serverConfig, + code, + filename: serverConfig.filename + `?tsr-serverfn-split=temp`, + }), + ).toThrowErrorMatchingInlineSnapshot( + ` + [Error: 1 | + > 2 | outer(() => { + | ^^ + > 3 | function useServer() { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 6 | } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 7 | }) + | ^^^^^^^ Server functions cannot be nested in other blocks or functions + 8 | ] + `, + ) + }) + + test('does not support class methods', () => { + const code = ` + class TestClass { + method() { + 'use server' + return 'hello' + } + + static staticMethod() { + 'use server' + return 'hello' + } + } + ` + + expect(() => compileDirectives({ ...clientConfig, code })) + .toThrowErrorMatchingInlineSnapshot(` + [Error: 1 | + 2 | class TestClass { + > 3 | method() { + | ^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 6 | } + | ^^^^^^^^^ "use server" in class not supported + 7 | + 8 | static staticMethod() { + 9 | 'use server'] + `) + expect(() => compileDirectives({ ...serverConfig, code })) + .toThrowErrorMatchingInlineSnapshot(` + [Error: 1 | + 2 | class TestClass { + > 3 | method() { + | ^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 6 | } + | ^^^^^^^^^ "use server" in class not supported + 7 | + 8 | static staticMethod() { + 9 | 'use server'] + `) + expect(() => + compileDirectives({ + ...serverConfig, + code, + filename: serverConfig.filename + `?tsr-serverfn-split=temp`, + }), + ).toThrowErrorMatchingInlineSnapshot(` + [Error: 1 | + 2 | class TestClass { + > 3 | method() { + | ^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 6 | } + | ^^^^^^^^^ "use server" in class not supported + 7 | + 8 | static staticMethod() { + 9 | 'use server'] + `) + }) + + test('does not support object methods', () => { + const code = ` + const obj = { + method() { + 'use server' + return 'hello' + }, + } + ` + + expect(() => compileDirectives({ ...clientConfig, code })) + .toThrowErrorMatchingInlineSnapshot(` + [Error: 1 | + 2 | const obj = { + > 3 | method() { + | ^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 6 | }, + | ^^^^^^^^^ "use server" in object method not supported + 7 | } + 8 | ] + `) + expect(() => compileDirectives({ ...serverConfig, code })) + .toThrowErrorMatchingInlineSnapshot(` + [Error: 1 | + 2 | const obj = { + > 3 | method() { + | ^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 6 | }, + | ^^^^^^^^^ "use server" in object method not supported + 7 | } + 8 | ] + `) + expect(() => + compileDirectives({ + ...serverConfig, + code, + filename: serverConfig.filename + `?tsr-serverfn-split=temp`, + }), + ).toThrowErrorMatchingInlineSnapshot(` + [Error: 1 | + 2 | const obj = { + > 3 | method() { + | ^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 6 | }, + | ^^^^^^^^^ "use server" in object method not supported + 7 | } + 8 | ] + `) + }) + + test('does not support generator functions', () => { + const code = ` + function* generatorServer() { + 'use server' + yield 'hello' + } + + async function* asyncGeneratorServer() { + 'use server' + yield 'hello' + } + ` + + expect(() => compileDirectives({ ...clientConfig, code })) + .toThrowErrorMatchingInlineSnapshot(` + [Error: 1 | + > 2 | function* generatorServer() { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 3 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^ + > 4 | yield 'hello' + | ^^^^^^^^^^^^^^^^^^^^ + > 5 | } + | ^^^^^^^ "use server" in generator function not supported + 6 | + 7 | async function* asyncGeneratorServer() { + 8 | 'use server'] + `) + expect(() => compileDirectives({ ...serverConfig, code })) + .toThrowErrorMatchingInlineSnapshot(` + [Error: 1 | + > 2 | function* generatorServer() { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 3 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^ + > 4 | yield 'hello' + | ^^^^^^^^^^^^^^^^^^^^ + > 5 | } + | ^^^^^^^ "use server" in generator function not supported + 6 | + 7 | async function* asyncGeneratorServer() { + 8 | 'use server'] + `) + expect(() => + compileDirectives({ + ...serverConfig, + code, + filename: serverConfig.filename + `?tsr-serverfn-split=temp`, + }), + ).toThrowErrorMatchingInlineSnapshot(` + [Error: 1 | + > 2 | function* generatorServer() { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 3 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^ + > 4 | yield 'hello' + | ^^^^^^^^^^^^^^^^^^^^ + > 5 | } + | ^^^^^^^ "use server" in generator function not supported + 6 | + 7 | async function* asyncGeneratorServer() { + 8 | 'use server'] + `) + }) + + test('multiple directiveFnsById', () => { + const code = ` + function multiDirective() { + 'use strict' + 'use server' + return 'hello' + } + ` + + const client = compileDirectives({ ...clientConfig, code }) + const ssr = compileDirectives({ ...ssrConfig, code }) + const splitFiles = Object.entries(ssr.directiveFnsById) + .map(([_fnId, directiveFn]) => { + return `// ${directiveFn.functionId}\n\n${ + compileDirectives({ + ...serverConfig, + code, + filename: directiveFn.splitFilename, + }).compiledResult.code + }` + }) + .join('\n\n\n') + + expect(client.compiledResult.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib-client"; + createClientRpc({ + filename: "test.ts", + functionId: "test--multiDirective" + });" + `) + expect(ssr.compiledResult.code).toMatchInlineSnapshot(` + "import { createSsrRpc } from "my-rpc-lib-server"; + createSsrRpc({ + filename: "test.ts", + functionId: "test--multiDirective" + });" + `) + expect(splitFiles).toMatchInlineSnapshot(` + "// test--multiDirective + + import { createServerRpc } from "my-rpc-lib-server"; + createServerRpc({ + fn: function multiDirective() { + 'use strict'; + + return 'hello'; + }, + filename: "test.ts", + functionId: "test--multiDirective" + }); + export default multiDirective_1;" + `) + }) + + test('IIFE', () => { + const code = ` + export const iife = (function () { + 'use server' + return 'hello' + })() + ` + + const client = compileDirectives({ ...clientConfig, code }) + const ssr = compileDirectives({ ...ssrConfig, code }) + const splitFiles = Object.entries(ssr.directiveFnsById) + .map(([_fnId, directiveFn]) => { + return `// ${directiveFn.functionId}\n\n${ + compileDirectives({ + ...serverConfig, + code, + filename: directiveFn.splitFilename, + }).compiledResult.code + }` + }) + .join('\n\n\n') + + expect(client.compiledResult.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib-client"; + const iife_1 = createClientRpc({ + filename: "test.ts", + functionId: "test--iife" + }); + export const iife = iife_1();" + `) + + expect(ssr.compiledResult.code).toMatchInlineSnapshot(` + "import { createSsrRpc } from "my-rpc-lib-server"; + const iife_1 = createSsrRpc({ + filename: "test.ts", + functionId: "test--iife" + }); + export const iife = iife_1();" + `) + + expect(splitFiles).toMatchInlineSnapshot(` + "// test--iife + + import { createServerRpc } from "my-rpc-lib-server"; + const iife_1 = createServerRpc({ + fn: function () { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--iife" + }); + export default iife_1;" + `) + }) + + test('functions that might have the same functionId', () => { + const code = ` + outer(function useServer() { + 'use server' + return 'hello' + }) + + outer(function useServer() { + 'use server' + return 'hello' + }) + ` + + const client = compileDirectives({ ...clientConfig, code }) + const ssr = compileDirectives({ ...ssrConfig, code }) + + const splitFiles = Object.entries(ssr.directiveFnsById) + .map(([_fnId, directiveFn]) => { + return `// ${directiveFn.functionId}\n\n${ + compileDirectives({ + ...serverConfig, + code, + filename: directiveFn.splitFilename, + }).compiledResult.code + }` + }) + .join('\n\n\n') + + expect(client.compiledResult.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib-client"; + const outer_useServer = createClientRpc({ + filename: "test.ts", + functionId: "test--outer_useServer" + }); + outer(outer_useServer); + const outer_useServer_1 = createClientRpc({ + filename: "test.ts", + functionId: "test--outer_useServer_1" + }); + outer(outer_useServer_1);" + `) + + expect(ssr.compiledResult.code).toMatchInlineSnapshot(` + "import { createSsrRpc } from "my-rpc-lib-server"; + const outer_useServer = createSsrRpc({ + filename: "test.ts", + functionId: "test--outer_useServer" + }); + outer(outer_useServer); + const outer_useServer_1 = createSsrRpc({ + filename: "test.ts", + functionId: "test--outer_useServer_1" + }); + outer(outer_useServer_1);" + `) + + expect(splitFiles).toMatchInlineSnapshot(` + "// test--outer_useServer + + import { createServerRpc } from "my-rpc-lib-server"; + const outer_useServer = createServerRpc({ + fn: function useServer() { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--outer_useServer" + }); + outer(outer_useServer); + const outer_useServer_1 = createServerRpc({ + fn: (...args) => devImport("test.ts?tsr-directive-use-server-split=test--outer_useServer_1").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--outer_useServer_1" + }); + outer(outer_useServer_1); + export default outer_useServer; + + + // test--outer_useServer_1 + + import { createServerRpc } from "my-rpc-lib-server"; + const outer_useServer = createServerRpc({ + fn: (...args) => devImport("test.ts?tsr-directive-use-server-split=test--outer_useServer").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--outer_useServer" + }); + outer(outer_useServer); + const outer_useServer_1 = createServerRpc({ + fn: function useServer() { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--outer_useServer_1" + }); + outer(outer_useServer_1); + export default outer_useServer_1;" + `) + }) + + test('use server directive in program body', () => { + const code = ` + 'use server' + + export function useServer() { + return usedInUseServer() + } + + function notExported() { + return 'hello' + } + + function usedInUseServer() { + return 'hello' + } + + export default function defaultExport() { + return 'hello' + } + ` + + const client = compileDirectives({ ...clientConfig, code }) + const ssr = compileDirectives({ ...ssrConfig, code }) + const splitFiles = Object.entries(ssr.directiveFnsById) + .map(([_fnId, directive]) => { + return `// ${directive.functionName}\n\n${ + compileDirectives({ + ...serverConfig, + code, + filename: directive.splitFilename, + }).compiledResult.code + }` + }) + .join('\n\n\n') + + expect(client.compiledResult.code).toMatchInlineSnapshot(` + "'use server'; + + import { createClientRpc } from "my-rpc-lib-client"; + const useServer_1 = createClientRpc({ + filename: "test.ts", + functionId: "test--useServer" + }); + export const useServer = useServer_1; + const defaultExport_1 = createClientRpc({ + filename: "test.ts", + functionId: "test--defaultExport" + }); + export default defaultExport_1;" + `) + expect(ssr.compiledResult.code).toMatchInlineSnapshot(` + "'use server'; + + import { createSsrRpc } from "my-rpc-lib-server"; + const useServer_1 = createSsrRpc({ + filename: "test.ts", + functionId: "test--useServer" + }); + export const useServer = useServer_1; + const defaultExport_1 = createSsrRpc({ + filename: "test.ts", + functionId: "test--defaultExport" + }); + export default defaultExport_1;" + `) + expect(splitFiles).toMatchInlineSnapshot(` + "// useServer + + 'use server'; + + import { createServerRpc } from "my-rpc-lib-server"; + const useServer_1 = createServerRpc({ + fn: function useServer() { + return usedInUseServer(); + }, + filename: "test.ts", + functionId: "test--useServer" + }); + function usedInUseServer() { + return 'hello'; + } + export default useServer_1; + + + // defaultExport + + 'use server'; + + import { createServerRpc } from "my-rpc-lib-server"; + const defaultExport_1 = createServerRpc({ + fn: function defaultExport() { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--defaultExport" + }); + export default defaultExport_1;" + `) + }) + + test('createServerFn with identifier', () => { + // The following code is the client output of the tanstack-start-vite-plugin + // that compiles `createServerFn` calls to automatically add the `use server` + // directive in the right places. + const clientOrSsrCode = `import { createServerFn } from '@tanstack/start'; + export const myServerFn = createServerFn().handler(opts => { + "use server"; + + return myServerFn.__executeServer(opts); + }); + + export const myServerFn2 = createServerFn().handler(opts => { + "use server"; + + return myServerFn2.__executeServer(opts); + });` + + // The following code is the server output of the tanstack-start-vite-plugin + // that compiles `createServerFn` calls to automatically add the `use server` + // directive in the right places. + const serverCode = `import { createServerFn } from '@tanstack/start'; + const myFunc = () => { + return 'hello from the server' + }; + export const myServerFn = createServerFn().handler(opts => { + "use server"; + + return myServerFn.__executeServer(opts); + }, myFunc); + + const myFunc2 = () => { + return myServerFn({ data: 'hello 2 from the server' }); + }; + export const myServerFn2 = createServerFn().handler(opts => { + "use server"; + + return myServerFn2.__executeServer(opts); + }, myFunc2);` + + const client = compileDirectives({ ...clientConfig, code: clientOrSsrCode }) + const ssr = compileDirectives({ ...ssrConfig, code: clientOrSsrCode }) + const splitFiles = Object.entries(ssr.directiveFnsById) + .map(([_fnId, directiveFn]) => { + return `// ${directiveFn.functionId}\n\n${ + compileDirectives({ + ...serverConfig, + code: serverCode, + filename: directiveFn.splitFilename, + }).compiledResult.code + }` + }) + .join('\n\n\n') + + expect(client.compiledResult.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib-client"; + import { createServerFn } from '@tanstack/start'; + const myServerFn_createServerFn_handler = createClientRpc({ + filename: "test.ts", + functionId: "test--myServerFn_createServerFn_handler" + }); + export const myServerFn = createServerFn().handler(myServerFn_createServerFn_handler); + const myServerFn2_createServerFn_handler = createClientRpc({ + filename: "test.ts", + functionId: "test--myServerFn2_createServerFn_handler" + }); + export const myServerFn2 = createServerFn().handler(myServerFn2_createServerFn_handler);" + `) + expect(ssr.compiledResult.code).toMatchInlineSnapshot(` + "import { createSsrRpc } from "my-rpc-lib-server"; + import { createServerFn } from '@tanstack/start'; + const myServerFn_createServerFn_handler = createSsrRpc({ + filename: "test.ts", + functionId: "test--myServerFn_createServerFn_handler" + }); + export const myServerFn = createServerFn().handler(myServerFn_createServerFn_handler); + const myServerFn2_createServerFn_handler = createSsrRpc({ + filename: "test.ts", + functionId: "test--myServerFn2_createServerFn_handler" + }); + export const myServerFn2 = createServerFn().handler(myServerFn2_createServerFn_handler);" + `) + expect(splitFiles).toMatchInlineSnapshot(` + "// test--myServerFn_createServerFn_handler + + import { createServerRpc } from "my-rpc-lib-server"; + import { createServerFn } from '@tanstack/start'; + const myFunc = () => { + return 'hello from the server'; + }; + const myServerFn_createServerFn_handler = createServerRpc({ + fn: opts => { + return myServerFn.__executeServer(opts); + }, + filename: "test.ts", + functionId: "test--myServerFn_createServerFn_handler" + }); + const myServerFn = createServerFn().handler(myServerFn_createServerFn_handler, myFunc); + export default myServerFn_createServerFn_handler; + + + // test--myServerFn2_createServerFn_handler + + import { createServerRpc } from "my-rpc-lib-server"; + import { createServerFn } from '@tanstack/start'; + const myFunc = () => { + return 'hello from the server'; + }; + const myServerFn_createServerFn_handler = createServerRpc({ + fn: (...args) => devImport("test.ts?tsr-directive-use-server-split=test--myServerFn_createServerFn_handler").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--myServerFn_createServerFn_handler" + }); + const myFunc2 = () => { + return myServerFn({ + data: 'hello 2 from the server' + }); + }; + const myServerFn2_createServerFn_handler = createServerRpc({ + fn: opts => { + return myServerFn2.__executeServer(opts); + }, + filename: "test.ts", + functionId: "test--myServerFn2_createServerFn_handler" + }); + const myServerFn = createServerFn().handler(myServerFn_createServerFn_handler, myFunc); + const myServerFn2 = createServerFn().handler(myServerFn2_createServerFn_handler, myFunc2); + export default myServerFn2_createServerFn_handler;" + `) + }) +}) diff --git a/packages/server-functions-vite-plugin/tsconfig.json b/packages/server-functions-vite-plugin/tsconfig.json new file mode 100644 index 0000000000..37d21ef6ca --- /dev/null +++ b/packages/server-functions-vite-plugin/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "include": ["src", "vite.config.ts", "tests"], + "exclude": ["tests/**/test-files/**", "tests/**/snapshots/**"], + "compilerOptions": { + "jsx": "react-jsx" + } +} diff --git a/packages/server-functions-vite-plugin/vite.config.ts b/packages/server-functions-vite-plugin/vite.config.ts new file mode 100644 index 0000000000..5389f0f739 --- /dev/null +++ b/packages/server-functions-vite-plugin/vite.config.ts @@ -0,0 +1,20 @@ +import { defineConfig, mergeConfig } from 'vitest/config' +import { tanstackViteConfig } from '@tanstack/config/vite' +import packageJson from './package.json' + +const config = defineConfig({ + test: { + name: packageJson.name, + dir: './tests', + watch: false, + typecheck: { enabled: true }, + }, +}) + +export default mergeConfig( + config, + tanstackViteConfig({ + entry: './src/index.ts', + srcDir: './src', + }), +) diff --git a/packages/start-vite-plugin/src/ast.ts b/packages/start-vite-plugin/src/ast.ts index 4f1cb2f04e..99333fa6c4 100644 --- a/packages/start-vite-plugin/src/ast.ts +++ b/packages/start-vite-plugin/src/ast.ts @@ -4,7 +4,7 @@ export type ParseAstOptions = { code: string filename: string root: string - env: 'server' | 'client' + env: 'server' | 'client' | 'ssr' } export function parseAst(opts: ParseAstOptions) { diff --git a/packages/start-vite-plugin/src/compilers.ts b/packages/start-vite-plugin/src/compilers.ts index 365a38609d..2eaeb16fef 100644 --- a/packages/start-vite-plugin/src/compilers.ts +++ b/packages/start-vite-plugin/src/compilers.ts @@ -21,6 +21,8 @@ export function compileEliminateDeadCode(opts: ParseAstOptions) { deadCodeElimination(ast) return generate(ast, { sourceMaps: true, + sourceFileName: opts.filename, + minified: process.env.NODE_ENV === 'production', filename: opts.filename, }) } @@ -186,6 +188,7 @@ export function compileStartOutput(opts: ParseAstOptions) { return generate(ast, { sourceMaps: true, + sourceFileName: opts.filename, filename: opts.filename, minified: process.env.NODE_ENV === 'production', }) @@ -220,6 +223,18 @@ function handleCreateServerFnCallExpression( ) }) + let serverFnId: string | undefined + + calledOptions?.node.properties.find((prop) => { + return ( + t.isObjectProperty(prop) && + t.isIdentifier(prop.key) && + prop.key.name === 'id' && + t.isStringLiteral(prop.value) && + (serverFnId = prop.value.value) + ) + }) + const callExpressionPaths = { middleware: null as babel.NodePath | null, validator: null as babel.NodePath | null, @@ -315,7 +330,22 @@ function handleCreateServerFnCallExpression( // })(optsOut) // }) - removeUseServerDirective(handlerFnPath) + // If the handler function is an identifier and we're on the client, we need to + // remove the bound function from the file. + // If we're on the server, you can leave it, since it will get referenced + // as a second argument. + + if (t.isIdentifier(handlerFn)) { + if (opts.env === 'client' || opts.env === 'ssr') { + // Find the binding for the handler function + const binding = handlerFnPath.scope.getBinding(handlerFn.name) + // Remove it + if (binding) { + binding.path.remove() + } + } + // If the env is server, just leave it alone + } handlerFnPath.replaceWith( t.arrowFunctionExpression( @@ -331,7 +361,12 @@ function handleCreateServerFnCallExpression( ), ), ], - [t.directive(t.directiveLiteral('use server'))], + [ + t.directive(t.directiveLiteral('use server')), + serverFnId + ? t.directive(t.directiveLiteral(`id: ${serverFnId}`)) + : (undefined as any), + ].filter(Boolean), ), ), ) @@ -341,46 +376,10 @@ function handleCreateServerFnCallExpression( } } -function removeUseServerDirective(path: babel.NodePath) { - path.traverse({ - Directive(path) { - if (path.node.value.value === 'use server') { - path.remove() - } - }, - }) -} - function handleCreateMiddlewareCallExpression( path: babel.NodePath, opts: ParseAstOptions, ) { - // const firstArg = path.node.arguments[0] - - // if (!t.isObjectExpression(firstArg)) { - // throw new Error( - // 'createMiddleware must be called with an object of options!', - // ) - // } - - // const idProperty = firstArg.properties.find((prop) => { - // return ( - // t.isObjectProperty(prop) && - // t.isIdentifier(prop.key) && - // prop.key.name === 'id' - // ) - // }) - - // if ( - // !idProperty || - // !t.isObjectProperty(idProperty) || - // !t.isStringLiteral(idProperty.value) - // ) { - // throw new Error( - // 'createMiddleware must be called with an "id" property!', - // ) - // } - const rootCallExpression = getRootCallExpression(path) if (debug) @@ -389,106 +388,6 @@ function handleCreateMiddlewareCallExpression( rootCallExpression.toString(), ) - // Check if the call is assigned to a variable - // if (!rootCallExpression.parentPath.isVariableDeclarator()) { - // TODO: move this logic out to eslint or something like - // the router generator code that can do autofixes on save. - - // // If not assigned to a variable, wrap the call in a variable declaration - // const variableDeclaration = t.variableDeclaration('const', [ - // t.variableDeclarator(t.identifier(middlewareName), path.node), - // ]) - - // // The parent could be an expression statement, if it is, we need to replace - // // it with the variable declaration - // if (path.parentPath.isExpressionStatement()) { - // path.parentPath.replaceWith(variableDeclaration) - // } else { - // // If the parent is not an expression statement, then it is a statement - // // that is not an expression, like a variable declaration or a return statement. - // // In this case, we need to insert the variable declaration before the statement - // path.parentPath.insertBefore(variableDeclaration) - // } - - // // Now we need to export it. Just add an export statement - // // to the program body - // path.findParent((parentPath) => { - // if (parentPath.isProgram()) { - // parentPath.node.body.push( - // t.exportNamedDeclaration(null, [ - // t.exportSpecifier( - // t.identifier(middlewareName), - // t.identifier(middlewareName), - // ), - // ]), - // ) - // } - // return false - // }) - - // throw new Error( - // 'createMiddleware must be assigned to a variable and exported!', - // ) - // } - - // const variableDeclarator = rootCallExpression.parentPath.node - // const existingVariableName = (variableDeclarator.id as t.Identifier).name - - // const program = rootCallExpression.findParent((parentPath) => { - // return parentPath.isProgram() - // }) as babel.NodePath - - // let isExported = false as boolean - - // program.traverse({ - // ExportNamedDeclaration: (path) => { - // if ( - // path.isExportNamedDeclaration() && - // path.node.declaration && - // t.isVariableDeclaration(path.node.declaration) && - // path.node.declaration.declarations.some((decl) => { - // return ( - // t.isVariableDeclarator(decl) && - // t.isIdentifier(decl.id) && - // decl.id.name === existingVariableName - // ) - // }) - // ) { - // isExported = true - // } - // }, - // }) - - // If not exported, export it - // if (!isExported) { - // TODO: move this logic out to eslint or something like - // the router generator code that can do autofixes on save. - - // path.parentPath.parentPath.insertAfter( - // t.exportNamedDeclaration(null, [ - // t.exportSpecifier( - // t.identifier(existingVariableName), - // t.identifier(existingVariableName), - // ), - // ]), - // ) - - // throw new Error( - // 'createMiddleware must be exported as a named export!', - // ) - // } - - // The function is the 'fn' property of the object passed to createMiddleware - - // const firstArg = path.node.arguments[0] - // if (t.isObjectExpression(firstArg)) { - // // Was called with some options - // } - - // Traverse the member expression and find the call expressions for - // the validator, handler, and middleware methods. Check to make sure they - // are children of the createMiddleware call expression. - const callExpressionPaths = { middleware: null as babel.NodePath | null, validator: null as babel.NodePath | null, @@ -523,8 +422,8 @@ function handleCreateMiddlewareCallExpression( ) } - // If we're on the client, remove the validator call expression - if (opts.env === 'client') { + // If we're on the client or ssr, remove the validator call expression + if (opts.env === 'client' || opts.env === 'ssr') { if (t.isMemberExpression(callExpressionPaths.validator.node.callee)) { callExpressionPaths.validator.replaceWith( callExpressionPaths.validator.node.callee.object, @@ -541,9 +440,9 @@ function handleCreateMiddlewareCallExpression( throw new Error('createMiddleware must be called with a "use" property!') } - // If we're on the client, remove the use call expression + // If we're on the client, remove the server call expression - if (opts.env === 'client') { + if (opts.env === 'client' || opts.env === 'ssr') { if (t.isMemberExpression(callExpressionPaths.server.node.callee)) { callExpressionPaths.server.replaceWith( callExpressionPaths.server.node.callee.object, @@ -560,7 +459,12 @@ function buildEnvOnlyCallExpressionHandler(env: 'client' | 'server') { if (debug) console.info(`Handling ${env}Only call expression:`, path.toString()) - if (opts.env === env) { + const isEnvMatch = + env === 'client' + ? opts.env === 'client' + : opts.env === 'server' || opts.env === 'ssr' + + if (isEnvMatch) { // extract the inner function from the call expression const innerInputExpression = path.node.arguments[0] @@ -645,7 +549,9 @@ function handleCreateIsomorphicFnCallExpression( ) } - const envCallExpression = callExpressionPaths[opts.env] + const resolvedEnv = opts.env === 'ssr' ? 'client' : opts.env + + const envCallExpression = callExpressionPaths[resolvedEnv] if (!envCallExpression) { // if we don't have an implementation for this environment, default to a no-op @@ -659,7 +565,7 @@ function handleCreateIsomorphicFnCallExpression( if (!t.isExpression(innerInputExpression)) { throw new Error( - `createIsomorphicFn().${opts.env}(func) must be called with a function!`, + `createIsomorphicFn().${resolvedEnv}(func) must be called with a function!`, ) } diff --git a/packages/start-vite-plugin/src/index.ts b/packages/start-vite-plugin/src/index.ts index bd40710f2a..1245d7d082 100644 --- a/packages/start-vite-plugin/src/index.ts +++ b/packages/start-vite-plugin/src/index.ts @@ -7,7 +7,7 @@ import type { Plugin } from 'vite' const debug = Boolean(process.env.TSR_VITE_DEBUG) export type TanStackStartViteOptions = { - env: 'server' | 'client' + env: 'server' | 'ssr' | 'client' } const transformFuncs = [ @@ -22,7 +22,7 @@ const eitherFuncRegex = new RegExp( `(function ${transformFuncs.join('|function ')})`, ) -export function TanStackStartViteServerFn( +export function TanStackStartVitePlugin( opts: TanStackStartViteOptions, ): Plugin { let ROOT: string = process.cwd() diff --git a/packages/start-vite-plugin/tests/createServerFn/createServerFn.test.ts b/packages/start-vite-plugin/tests/createServerFn/createServerFn.test.ts index 19b86a0c01..d46d1babb7 100644 --- a/packages/start-vite-plugin/tests/createServerFn/createServerFn.test.ts +++ b/packages/start-vite-plugin/tests/createServerFn/createServerFn.test.ts @@ -59,4 +59,48 @@ describe('createServerFn compiles correctly', async () => { }) }).toThrowError() }) + + test('should work with identifiers of functions', () => { + const code = ` + import { createServerFn } from '@tanstack/start' + const myFunc = () => { + return 'hello from the server' + } + const myServerFn = createServerFn().handler(myFunc)` + + const compiledResultClient = compileStartOutput({ + root: '/test', + filename: 'test.ts', + code, + env: 'client', + }) + + const compiledResultServer = compileStartOutput({ + root: '/test', + filename: 'test.ts', + code, + env: 'server', + }) + + expect(compiledResultClient.code).toMatchInlineSnapshot(` + "import { createServerFn } from '@tanstack/start'; + const myServerFn = createServerFn().handler(opts => { + "use server"; + + return myServerFn.__executeServer(opts); + });" + `) + + expect(compiledResultServer.code).toMatchInlineSnapshot(` + "import { createServerFn } from '@tanstack/start'; + const myFunc = () => { + return 'hello from the server'; + }; + const myServerFn = createServerFn().handler(opts => { + "use server"; + + return myServerFn.__executeServer(opts); + }, myFunc);" + `) + }) }) diff --git a/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx b/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx index be1b58b186..752850e42e 100644 --- a/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx +++ b/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx @@ -35,11 +35,6 @@ export const withVariable = createServerFn({ return withVariable.__executeServer(opts); }); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { return async (input: unknown) => { return fn(schema.parse(input)); diff --git a/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx b/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx index f51f0ade21..55710f4321 100644 --- a/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx +++ b/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx @@ -21,11 +21,6 @@ export const withVariable = serverFn({ return withVariable.__executeServer(opts); }); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { return async (input: unknown) => { return fn(schema.parse(input)); diff --git a/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx b/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx index 750a52532a..b33435a9fe 100644 --- a/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx +++ b/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx @@ -21,11 +21,6 @@ export const withVariable = TanStackStart.createServerFn({ return withVariable.__executeServer(opts); }); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { return async (input: unknown) => { return fn(schema.parse(input)); diff --git a/packages/start-vite-plugin/tests/createServerFn/snapshots/server/createServerFnStarImport.tsx b/packages/start-vite-plugin/tests/createServerFn/snapshots/server/createServerFnStarImport.tsx index 66088cb181..3f79037fe7 100644 --- a/packages/start-vite-plugin/tests/createServerFn/snapshots/server/createServerFnStarImport.tsx +++ b/packages/start-vite-plugin/tests/createServerFn/snapshots/server/createServerFnStarImport.tsx @@ -7,6 +7,8 @@ export const withUseServer = TanStackStart.createServerFn({ return withUseServer.__executeServer(opts); }, async function () { + 'use server'; + console.info('Fetching posts...'); await new Promise(r => setTimeout(r, 500)); return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); diff --git a/packages/start/package.json b/packages/start/package.json index afde4bd213..c03e27a0ca 100644 --- a/packages/start/package.json +++ b/packages/start/package.json @@ -36,7 +36,8 @@ "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", - "build": "vite build && pnpm build:config && pnpm build:router-manifest", + "build": "pnpm build:vite && pnpm build:config && pnpm build:router-manifest", + "build:vite": "vite build", "build:config": "tsc --project tsconfigs/config.tsconfig.json", "build:router-manifest": "tsc --project tsconfigs/router-manifest.tsconfig.json" }, @@ -110,10 +111,10 @@ "default": "./dist/esm/server-runtime/index.js" } }, - "./react-server-runtime": { + "./ssr-runtime": { "import": { - "types": "./dist/esm/react-server-runtime/index.d.ts", - "default": "./dist/esm/react-server-runtime/index.js" + "types": "./dist/esm/ssr-runtime/index.d.ts", + "default": "./dist/esm/ssr-runtime/index.js" } }, "./server-handler": { @@ -138,6 +139,7 @@ "@tanstack/router-generator": "workspace:^", "@tanstack/router-plugin": "workspace:^", "@tanstack/start-vite-plugin": "workspace:^", + "@tanstack/directive-functions-plugin": "workspace:^", "@vinxi/react": "0.2.5", "@vinxi/react-server-dom": "^0.0.3", "@vinxi/server-components": "0.5.0", diff --git a/packages/start/src/client-runtime/getBaseUrl.tsx b/packages/start/src/client-runtime/getBaseUrl.tsx index dfcf7947ed..99cc564263 100644 --- a/packages/start/src/client-runtime/getBaseUrl.tsx +++ b/packages/start/src/client-runtime/getBaseUrl.tsx @@ -9,6 +9,6 @@ function sanitizeBase(base: string | undefined) { return base.replace(/^\/|\/$/g, '') } -export function getBaseUrl(base: string | undefined, id: string, name: string) { - return `${base}/${sanitizeBase(process.env.TSS_SERVER_BASE)}/?_serverFnId=${encodeURI(id)}&_serverFnName=${encodeURI(name)}` +export function getBaseUrl(base: string | undefined, functionId: string) { + return `${base}/${sanitizeBase(process.env.TSS_SERVER_BASE)}/${encodeURI(functionId)}` } diff --git a/packages/start/src/client-runtime/index.tsx b/packages/start/src/client-runtime/index.tsx index 9e4f2b67f6..c4bf7b8536 100644 --- a/packages/start/src/client-runtime/index.tsx +++ b/packages/start/src/client-runtime/index.tsx @@ -1,22 +1,16 @@ -import { fetcher } from './fetcher' +import { serverFnFetcher } from '../client' import { getBaseUrl } from './getBaseUrl' -import type { ServerFn } from '../client/createServerFn' +import type { CreateClientRpcFn } from '@tanstack/directive-functions-plugin' -export function createServerReference( - _fn: ServerFn, - id: string, - name: string, -) { - // let base = getBaseUrl(import.meta.env.SERVER_BASE_URL, id, name) - const base = getBaseUrl(window.location.origin, id, name) +export const createClientRpc: CreateClientRpcFn = (functionId) => { + const base = getBaseUrl(window.location.origin, functionId) - const proxyFn = (...args: Array) => fetcher(base, args, fetch) + const fn = (...args: Array) => serverFnFetcher(base, args, fetch) - return Object.assign(proxyFn, { + return Object.assign(fn, { url: base, - filename: id, - functionId: name, + functionId, }) } -export { fetcher } +export { serverFnFetcher } diff --git a/packages/start/src/client/createServerFn.ts b/packages/start/src/client/createServerFn.ts index 6408e783cd..40b0c6d4ab 100644 --- a/packages/start/src/client/createServerFn.ts +++ b/packages/start/src/client/createServerFn.ts @@ -96,6 +96,7 @@ type ServerFnBaseOptions< TMiddlewares = unknown, TInput = unknown, > = { + id?: string method: TMethod validateClient?: boolean middleware?: Constrain> @@ -173,7 +174,8 @@ export function createServerFn< TValidator = undefined, >( options?: { - method: TMethod + id?: string + method?: TMethod }, __opts?: ServerFnBaseOptions, ): ServerFnBuilder { @@ -221,7 +223,7 @@ export function createServerFn< invariant( extractedFn.url, - `createServerFn must be called with a function that is marked with the 'use server' pragma. Are you using the @tanstack/start-vite-plugin ?`, + `createServerFn must be called with a function that has a 'url' property. Are you using the @tanstack/start-vite-plugin properly?`, ) const resolvedMiddleware = [ diff --git a/packages/start/src/client/createServerFnClient.ts b/packages/start/src/client/createServerFnClient.ts new file mode 100644 index 0000000000..afb67f261e --- /dev/null +++ b/packages/start/src/client/createServerFnClient.ts @@ -0,0 +1,38 @@ +import { serverFnFetcher } from './serverFnFetcher' +import type { CompiledFetcherFnOptions } from './createServerFn' + +type ServerFnClient = { + fetch: ( + opts: Omit & { + data?: any + functionId: string + }, + ) => Promise +} + +export function createServerFnClient(clientOpts: { + baseUrl: string +}): ServerFnClient { + return { + fetch: (fetchOpts) => { + return serverFnFetcher( + joinPaths(clientOpts.baseUrl, fetchOpts.functionId), + [fetchOpts], + fetch, + ) + }, + } +} + +function joinPaths(...paths: Array) { + const firstPath = paths[0] || '' + const lastPath = paths[paths.length - 1] || '' + const prefix = firstPath.startsWith('/') ? '/' : '' + const suffix = lastPath.endsWith('/') ? '/' : '' + + return ( + prefix + + paths.map((path) => path.replace(/(^\/+|\/+$)/g, '')).join('/') + + suffix + ) +} diff --git a/packages/start/src/client/index.tsx b/packages/start/src/client/index.tsx index 08f8b6f2df..7e9155537a 100644 --- a/packages/start/src/client/index.tsx +++ b/packages/start/src/client/index.tsx @@ -50,3 +50,5 @@ export { StartClient } from './StartClient' export { mergeHeaders } from './headers' export { renderRsc } from './renderRSC' export { useServerFn } from './useServerFn' +export { serverFnFetcher } from './serverFnFetcher' +export { createServerFnClient } from './createServerFnClient' diff --git a/packages/start/src/client-runtime/fetcher.tsx b/packages/start/src/client/serverFnFetcher.tsx similarity index 91% rename from packages/start/src/client-runtime/fetcher.tsx rename to packages/start/src/client/serverFnFetcher.tsx index 70eea4b9ae..7aac71c7f1 100644 --- a/packages/start/src/client-runtime/fetcher.tsx +++ b/packages/start/src/client/serverFnFetcher.tsx @@ -5,10 +5,10 @@ import { isPlainObject, isRedirect, } from '@tanstack/react-router' -import type { MiddlewareOptions } from '../client/createServerFn' +import type { MiddlewareOptions } from './createServerFn' -export async function fetcher( - base: string, +export async function serverFnFetcher( + url: string, args: Array, handler: (request: Request) => Promise, ) { @@ -43,11 +43,17 @@ export async function fetcher( }), }) - if (encodedPayload) base += `&${encodedPayload}` + if (encodedPayload) { + if (url.includes('?')) { + url += `&${encodedPayload}` + } else { + url += `?${encodedPayload}` + } + } } // Create the request - const request = new Request(base, { + const request = new Request(url, { method: first.method, headers, ...getFetcherRequestOptions(first), @@ -77,7 +83,7 @@ export async function fetcher( // If not a custom fetcher, just proxy the arguments // through as a POST request - const request = new Request(base, { + const request = new Request(url, { method: 'POST', headers: { Accept: 'application/json', diff --git a/packages/start/src/config/index.ts b/packages/start/src/config/index.ts index f371997c8e..beb35e419e 100644 --- a/packages/start/src/config/index.ts +++ b/packages/start/src/config/index.ts @@ -7,17 +7,14 @@ import { resolve } from 'import-meta-resolve' import { TanStackRouterVite } from '@tanstack/router-plugin/vite' import { TanStackStartViteDeadCodeElimination, - TanStackStartViteServerFn, + TanStackStartVitePlugin, } from '@tanstack/start-vite-plugin' import { getConfig } from '@tanstack/router-generator' import { createApp } from 'vinxi' import { config } from 'vinxi/plugins/config' // // @ts-expect-error // import { serverComponents } from '@vinxi/server-components/plugin' -// @ts-expect-error -import { serverFunctions } from '@vinxi/server-functions/plugin' -// @ts-expect-error -import { serverTransform } from '@vinxi/server-functions/server' +import { createTanStackServerFnPlugin } from '@tanstack/directive-functions-plugin' import { tanstackStartVinxiFileRouter } from './vinxi-file-router.js' import { checkDeploymentPresetInput, @@ -123,6 +120,8 @@ export function defineConfig( const apiEntryExists = existsSync(apiEntry) + const TanStackServerFnsPlugin = createTanStackServerFnPlugin() + let vinxiApp = createApp({ server: { ...serverOptions, @@ -170,9 +169,7 @@ export function defineConfig( }), ...(viteConfig.plugins || []), ...(clientViteConfig.plugins || []), - serverFunctions.client({ - runtime: '@tanstack/start/client-runtime', - }), + TanStackServerFnsPlugin.client, viteReact(opts.react), // TODO: RSCS - enable this // serverComponents.client(), @@ -211,9 +208,7 @@ export function defineConfig( }), ...(getUserViteConfig(opts.vite).plugins || []), ...(getUserViteConfig(opts.routers?.ssr?.vite).plugins || []), - serverTransform({ - runtime: '@tanstack/start/server-runtime', - }), + TanStackServerFnsPlugin.ssr, config('start-ssr', { ssr: { external: ['@vinxi/react-server-dom/client'], @@ -254,13 +249,11 @@ export function defineConfig( ...injectDefineEnv('TSS_API_BASE', apiBase), }, }), - serverFunctions.server({ - runtime: '@tanstack/start/react-server-runtime', - // TODO: RSCS - remove this - resolve: { - conditions: [], - }, - }), + TanStackServerFnsPlugin.server, + // TODO: RSCS - remove this + // resolve: { + // conditions: [], + // }, // TODO: RSCs - add this // serverComponents.serverActions({ // resolve: { @@ -396,8 +389,8 @@ function withStartPlugins(opts: TanStackStartOutputConfig, router: RouterType) { ...tsrConfig.experimental, }, }), - TanStackStartViteServerFn({ - env: router === 'client' ? 'client' : 'server', + TanStackStartVitePlugin({ + env: router === 'server' ? 'server' : 'client', }), ], [ diff --git a/packages/start/src/react-server-runtime/index.tsx b/packages/start/src/react-server-runtime/index.tsx deleted file mode 100644 index d7fbea3fe7..0000000000 --- a/packages/start/src/react-server-runtime/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -// import { getBaseUrl } from '../client-runtime/getBaseUrl' - -export function createServerReference( - fn: any, - id: string, - name: string, -) { - // const functionUrl = getBaseUrl('http://localhost:3000', id, name) - const functionUrl = 'https://localhost:3000' - - return Object.assign(fn, { - url: functionUrl, - }) -} diff --git a/packages/start/src/server-handler/index.tsx b/packages/start/src/server-handler/index.tsx index 51c9881985..54151ba682 100644 --- a/packages/start/src/server-handler/index.tsx +++ b/packages/start/src/server-handler/index.tsx @@ -1,4 +1,6 @@ /// +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' import { defaultTransformer, isNotFound, @@ -11,7 +13,8 @@ import { getResponseStatus, toWebRequest, } from 'vinxi/http' -import { getManifest } from 'vinxi/manifest' +// @ts-expect-error +import serverFnManifest from 'tsr:server-fn-manifest' import type { H3Event } from 'vinxi/server' export default eventHandler(handleServerAction) @@ -23,28 +26,44 @@ async function handleServerAction(event: H3Event) { export async function handleServerRequest(request: Request, _event?: H3Event) { const method = request.method const url = new URL(request.url, 'http://localhost:3000') + // extract the serverFnId from the url as host/_server/:serverFnId + // Define a regex to match the path and extract the :thing part + const regex = /\/_server\/([^/?#]+)/ + + // Execute the regex + const match = url.pathname.match(regex) + const serverFnId = match ? match[1] : null const search = Object.fromEntries(url.searchParams.entries()) as { - _serverFnId?: string - _serverFnName?: string payload?: any } - const serverFnId = search._serverFnId - const serverFnName = search._serverFnName - - if (!serverFnId || !serverFnName) { - throw new Error('Invalid request') - } - invariant(typeof serverFnId === 'string', 'Invalid server action') - if (process.env.NODE_ENV === 'development') - console.info(`ServerFn Request: ${serverFnId} - ${serverFnName}`) - if (process.env.NODE_ENV === 'development') console.info() + const serverFnInfo = serverFnManifest[serverFnId] - const action = (await getManifest('server').chunks[serverFnId]?.import())?.[ - serverFnName - ] as Function + invariant(serverFnInfo, 'Server function not found') + + if (process.env.NODE_ENV === 'development') + console.info(`\nServerFn Request: ${serverFnId}`) + + let action: Function + if (process.env.NODE_ENV === 'development') { + action = (await (globalThis as any).app + .getRouter('server') + .internals.devServer.ssrLoadModule(serverFnInfo.splitFilename) + .then((d: any) => d.default)) as Function + } else { + const router = (globalThis as any).app.getRouter('server') + const filePath = join( + router.outDir, + router.base, + serverFnInfo.chunkName + '.mjs', + ) + const url = pathToFileURL(filePath).toString() + action = (await import(url).then((d) => d.default)) as Function + } + + invariant(action, 'Server function not found') const response = await (async () => { try { diff --git a/packages/start/src/server-runtime/index.tsx b/packages/start/src/server-runtime/index.tsx index eda1e96e91..4434abec24 100644 --- a/packages/start/src/server-runtime/index.tsx +++ b/packages/start/src/server-runtime/index.tsx @@ -1,159 +1,16 @@ -import { Readable } from 'node:stream' -import { getEvent, getRequestHeaders } from 'vinxi/http' -import invariant from 'tiny-invariant' -import { fetcher } from '../client-runtime/fetcher' import { getBaseUrl } from '../client-runtime/getBaseUrl' -import { handleServerRequest } from '../server-handler/index' -/** - * - * @returns {import('node:http').IncomingMessage} - */ -export function createIncomingMessage( - url: string, - method: string, - headers: HeadersInit, -): Readable { - const readable = new Readable({ objectMode: true }) as any - readable._read = () => {} - - readable.url = url - readable.method = method - readable.headers = headers - readable.connection = {} - readable.getHeaders = () => { - return headers - } - return readable -} - -// function createAsyncStream(options?: WritableOptions) { -// let firstActivity = false -// let resolveActivity: () => void -// let finishActivity: () => void - -// const initialPromise = new Promise((resolve) => { -// resolveActivity = resolve -// }) - -// const finishPromise = new Promise((resolve) => { -// finishActivity = resolve -// }) - -// const readable = new Readable({ -// objectMode: true, -// }) - -// readable._read = () => {} - -// const writable = new Writable({ -// ...options, -// write(chunk, encoding, callback) { -// if (!firstActivity) { -// firstActivity = true -// resolveActivity() -// } -// readable.push(chunk, encoding) -// callback() -// }, -// }) as any - -// const headers = new Headers() - -// writable.setHeader = (key: string, value: string) => { -// headers.set(key, value) -// } - -// writable.on('finish', () => { -// readable.push(null) -// readable.destroy() -// finishActivity() -// }) - -// return { -// readable, -// writable, -// headers, -// initialPromise, -// finishPromise, -// } as const -// } +import type { CreateServerRpcFn } from '@tanstack/directive-functions-plugin' const fakeHost = 'http://localhost:3000' -export function createServerReference(_fn: any, id: string, name: string) { - const functionUrl = getBaseUrl(fakeHost, id, name) +export const createServerRpc: CreateServerRpcFn = ( + functionId, + splitImportFn, +) => { + const functionUrl = getBaseUrl(fakeHost, functionId) - const proxyFn = (...args: Array) => { - invariant( - args.length === 1, - 'Server functions can only accept a single argument', - ) - - return fetcher(functionUrl, args, async (request) => { - const event = getEvent() - - const ogRequestHeaders = getRequestHeaders(event) - - Object.entries(ogRequestHeaders).forEach(([key, value]) => { - if (!request.headers.has(key)) { - request.headers.append(key, value!) - } - }) - - // // For RSC, we need to proxy this request back to the server under - // // the /_server path and let the RSC/Server-fn router handle it - // if (RSC) { - - // const incomingMessage = createIncomingMessage( - // new URL(request.url).pathname + new URL(request.url).search, - // request.method, - // Object.fromEntries(request.headers.entries()), - // ) - - // const asyncStream = createAsyncStream() - - // const result = await handleHTTPEvent( - // new H3Event(incomingMessage as any, asyncStream.writable), - // ) - - // console.info('awaiting initial promise', result, asyncStream) - - // await asyncStream.initialPromise - - // // Only augment the headers of the underlying document request - // // if the response headers have not been sent yet - // if (!(event as any).__tsrHeadersSent) { - // const ogResponseHeaders = getResponseHeaders(event) - - // asyncStream.headers.forEach((value, key) => { - // if (!Object.hasOwn(ogResponseHeaders, key)) { - // ogResponseHeaders[key] = value - // } - // }) - - // setResponseHeaders(event, ogResponseHeaders as any) - // } - - // console.info(asyncStream.readable) - - // // if (asyncStream.headers.get('content-type') === 'application/json') { - // // await asyncStream.finishPromise - // // } - - // return new Response(Readable.toWeb(asyncStream.readable) as any, { - // headers: asyncStream.headers, - // }) - // } - - // For now, we're not doing RSC, so we just handle the request - // in the current non-worker scope - return handleServerRequest(request, event) - }) - } - - return Object.assign(proxyFn, { + return Object.assign(splitImportFn, { url: functionUrl.replace(fakeHost, ''), - filename: id, - functionId: name, + functionId, }) } diff --git a/packages/start/src/server/defaultStreamHandler.tsx b/packages/start/src/server/defaultStreamHandler.tsx index af86e4fc85..3a8707017a 100644 --- a/packages/start/src/server/defaultStreamHandler.tsx +++ b/packages/start/src/server/defaultStreamHandler.tsx @@ -63,12 +63,12 @@ export const defaultStreamHandler: HandlerCallback = async ({ }, }), onError: (error, info) => { - console.log('Error in renderToPipeableStream:', error, info) + console.error('Error in renderToPipeableStream:', error, info) }, }, ) } catch (e) { - console.log('Error in renderToPipeableStream:', e) + console.error('Error in renderToPipeableStream:', e) } const transforms = [transformStreamWithRouter(router)] diff --git a/packages/start/src/ssr-runtime/index.tsx b/packages/start/src/ssr-runtime/index.tsx new file mode 100644 index 0000000000..5547b756ee --- /dev/null +++ b/packages/start/src/ssr-runtime/index.tsx @@ -0,0 +1,156 @@ +import { Readable } from 'node:stream' +import { getEvent, getRequestHeaders } from 'vinxi/http' +import invariant from 'tiny-invariant' +import { serverFnFetcher } from '../client' +import { getBaseUrl } from '../client-runtime/getBaseUrl' +import { handleServerRequest } from '../server-handler/index' +import type { CreateSsrRpcFn } from '@tanstack/directive-functions-plugin' + +export function createIncomingMessage( + url: string, + method: string, + headers: HeadersInit, +): Readable { + const readable = new Readable({ objectMode: true }) as any + readable._read = () => {} + + readable.url = url + readable.method = method + readable.headers = headers + readable.connection = {} + readable.getHeaders = () => { + return headers + } + return readable +} + +// function createAsyncStream(options?: WritableOptions) { +// let firstActivity = false +// let resolveActivity: () => void +// let finishActivity: () => void + +// const initialPromise = new Promise((resolve) => { +// resolveActivity = resolve +// }) + +// const finishPromise = new Promise((resolve) => { +// finishActivity = resolve +// }) + +// const readable = new Readable({ +// objectMode: true, +// }) + +// readable._read = () => {} + +// const writable = new Writable({ +// ...options, +// write(chunk, encoding, callback) { +// if (!firstActivity) { +// firstActivity = true +// resolveActivity() +// } +// readable.push(chunk, encoding) +// callback() +// }, +// }) as any + +// const headers = new Headers() + +// writable.setHeader = (key: string, value: string) => { +// headers.set(key, value) +// } + +// writable.on('finish', () => { +// readable.push(null) +// readable.destroy() +// finishActivity() +// }) + +// return { +// readable, +// writable, +// headers, +// initialPromise, +// finishPromise, +// } as const +// } + +const fakeHost = 'http://localhost:3000' + +export const createSsrRpc: CreateSsrRpcFn = (functionId) => { + const functionUrl = getBaseUrl(fakeHost, functionId) + + const ssrFn = (...args: Array) => { + invariant( + args.length === 1, + 'Server functions can only accept a single argument', + ) + + return serverFnFetcher(functionUrl, args, async (request) => { + const event = getEvent() + + const ogRequestHeaders = getRequestHeaders(event) + + Object.entries(ogRequestHeaders).forEach(([key, value]) => { + if (!request.headers.has(key)) { + request.headers.append(key, value!) + } + }) + + // // For RSC, we need to proxy this request back to the server under + // // the /_server path and let the RSC/Server-fn router handle it + // if (RSC) { + + // const incomingMessage = createIncomingMessage( + // new URL(request.url).pathname + new URL(request.url).search, + // request.method, + // Object.fromEntries(request.headers.entries()), + // ) + + // const asyncStream = createAsyncStream() + + // const result = await handleHTTPEvent( + // new H3Event(incomingMessage as any, asyncStream.writable), + // ) + + // console.info('awaiting initial promise', result, asyncStream) + + // await asyncStream.initialPromise + + // // Only augment the headers of the underlying document request + // // if the response headers have not been sent yet + // if (!(event as any).__tsrHeadersSent) { + // const ogResponseHeaders = getResponseHeaders(event) + + // asyncStream.headers.forEach((value, key) => { + // if (!Object.hasOwn(ogResponseHeaders, key)) { + // ogResponseHeaders[key] = value + // } + // }) + + // setResponseHeaders(event, ogResponseHeaders as any) + // } + + // console.info(asyncStream.readable) + + // // if (asyncStream.headers.get('content-type') === 'application/json') { + // // await asyncStream.finishPromise + // // } + + // return new Response(Readable.toWeb(asyncStream.readable) as any, { + // headers: asyncStream.headers, + // }) + // } + + // For now, we're not doing RSC, so we just handle the request + // in the current non-worker scope + return handleServerRequest(request, event) + }) + } + + return Object.assign(ssrFn, { + url: functionUrl.replace(fakeHost, ''), + functionId, + }) +} diff --git a/packages/start/tsconfig.json b/packages/start/tsconfig.json index fe3fb37c9e..51dda9abf2 100644 --- a/packages/start/tsconfig.json +++ b/packages/start/tsconfig.json @@ -4,5 +4,5 @@ "jsx": "react-jsx", "module": "esnext" }, - "include": ["src", "vite.config.ts", "src/client/DehydrateRouter.tsx"] + "include": ["src", "vite.config.ts"] } diff --git a/packages/start/tsconfigs/config.tsconfig.json b/packages/start/tsconfigs/config.tsconfig.json index 948b455bbc..58fc33fb0a 100644 --- a/packages/start/tsconfigs/config.tsconfig.json +++ b/packages/start/tsconfigs/config.tsconfig.json @@ -2,6 +2,7 @@ "extends": "../../../tsconfig.json", "include": ["../src/config/index.ts"], "compilerOptions": { + "rootDir": "../src/config", "outDir": "../dist/esm/config", "target": "esnext", "noEmit": false diff --git a/packages/start/tsconfigs/router-manifest.tsconfig.json b/packages/start/tsconfigs/router-manifest.tsconfig.json index 4849ec7e6a..cc108d2494 100644 --- a/packages/start/tsconfigs/router-manifest.tsconfig.json +++ b/packages/start/tsconfigs/router-manifest.tsconfig.json @@ -2,6 +2,7 @@ "extends": "../../../tsconfig.json", "include": ["../src/router-manifest/index.ts"], "compilerOptions": { + "rootDir": "../src/router-manifest", "outDir": "../dist/esm/router-manifest", "target": "esnext", "noEmit": false diff --git a/packages/start/vite.config.ts b/packages/start/vite.config.ts index 82a14ae09b..196e0fc33a 100644 --- a/packages/start/vite.config.ts +++ b/packages/start/vite.config.ts @@ -16,14 +16,14 @@ const config = defineConfig({ export default mergeConfig( config, tanstackViteConfig({ - externalDeps: ['@tanstack/start/router-manifest'], + externalDeps: ['@tanstack/start/router-manifest', 'tsr:server-fn-manifest'], entry: [ './src/client/index.tsx', './src/server/index.tsx', - './src/client-runtime/index.tsx', './src/api/index.ts', + './src/client-runtime/index.tsx', './src/server-runtime/index.tsx', - './src/react-server-runtime/index.tsx', + './src/ssr-runtime/index.tsx', './src/server-handler/index.tsx', ], srcDir: './src', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index af6cc1cdad..b4adb9bbf2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -23,8 +23,6 @@ overrides: '@tanstack/start': workspace:* '@tanstack/start-vite-plugin': workspace:* '@tanstack/eslint-plugin-router': workspace:* - temp-react: 0.0.0-experimental-035a41c4e-20230704 - temp-react-dom: 0.0.0-experimental-035a41c4e-20230704 importers: @@ -3501,8 +3499,74 @@ importers: specifier: workspace:* version: link:../router-plugin + packages/server-functions-vite-plugin: + dependencies: + '@babel/code-frame': + specifier: 7.26.2 + version: 7.26.2 + '@babel/core': + specifier: ^7.26.0 + version: 7.26.0 + '@babel/generator': + specifier: ^7.26.3 + version: 7.26.3 + '@babel/parser': + specifier: ^7.26.3 + version: 7.26.3 + '@babel/plugin-syntax-jsx': + specifier: ^7.25.9 + version: 7.25.9(@babel/core@7.26.0) + '@babel/plugin-syntax-typescript': + specifier: ^7.25.9 + version: 7.25.9(@babel/core@7.26.0) + '@babel/template': + specifier: ^7.25.9 + version: 7.25.9 + '@babel/traverse': + specifier: ^7.26.4 + version: 7.26.4 + '@babel/types': + specifier: ^7.26.3 + version: 7.26.3 + '@types/babel__code-frame': + specifier: ^7.0.6 + version: 7.0.6 + '@types/babel__core': + specifier: ^7.20.5 + version: 7.20.5 + '@types/babel__generator': + specifier: ^7.6.8 + version: 7.6.8 + '@types/babel__template': + specifier: ^7.4.4 + version: 7.4.4 + '@types/babel__traverse': + specifier: ^7.20.6 + version: 7.20.6 + '@types/diff': + specifier: ^6.0.0 + version: 6.0.0 + babel-dead-code-elimination: + specifier: ^1.0.6 + version: 1.0.8 + chalk: + specifier: ^5.3.0 + version: 5.3.0 + dedent: + specifier: ^1.5.3 + version: 1.5.3 + diff: + specifier: ^7.0.0 + version: 7.0.0 + tiny-invariant: + specifier: ^1.3.3 + version: 1.3.3 + packages/start: dependencies: + '@tanstack/directive-functions-plugin': + specifier: workspace:^ + version: link:../server-functions-vite-plugin '@tanstack/react-cross-context': specifier: workspace:* version: link:../react-cross-context @@ -5966,6 +6030,9 @@ packages: '@types/cross-spawn@6.0.6': resolution: {integrity: sha512-fXRhhUkG4H3TQk5dBhQ7m/JDdSNHKwR2BBia62lhwEIq9xGiQKLxd6LymNhn47SjXhsUEPmxi+PKw2OkW4LLjA==} + '@types/diff@6.0.0': + resolution: {integrity: sha512-dhVCYGv3ZSbzmQaBSagrv1WJ6rXCdkyTcDyoNu1MD8JohI7pR7k8wdZEm+mvdxRKXyHVwckFzWU1vJc+Z29MlA==} + '@types/eslint-scope@3.7.7': resolution: {integrity: sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg==} @@ -7145,6 +7212,14 @@ packages: decimal.js@10.4.3: resolution: {integrity: sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA==} + dedent@1.5.3: + resolution: {integrity: sha512-NHQtfOOW68WD8lgypbLA5oT+Bt0xXJhiYvoR6SmmNXZfpzOGXwdKWmcwG8N7PwVVWV3eF/68nmD9BaJSsTBhyQ==} + peerDependencies: + babel-plugin-macros: ^3.1.0 + peerDependenciesMeta: + babel-plugin-macros: + optional: true + deep-eql@5.0.2: resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==} engines: {node: '>=6'} @@ -7238,6 +7313,10 @@ packages: resolution: {integrity: sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==} engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + diff@7.0.0: + resolution: {integrity: sha512-PJWHUb1RFevKCwaFA9RlG5tCd+FO5iRh9A8HEtkmBH2Li03iJriB6m6JIN4rGz3K3JLawI7/veA1xzRKP6ISBw==} + engines: {node: '>=0.3.1'} + dir-glob@3.0.1: resolution: {integrity: sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==} engines: {node: '>=8'} @@ -12957,6 +13036,8 @@ snapshots: dependencies: '@types/node': 22.10.1 + '@types/diff@6.0.0': {} + '@types/eslint-scope@3.7.7': dependencies: '@types/eslint': 9.6.1 @@ -14309,6 +14390,8 @@ snapshots: decimal.js@10.4.3: {} + dedent@1.5.3: {} + deep-eql@5.0.2: {} deep-is@0.1.4: {} @@ -14368,6 +14451,8 @@ snapshots: diff-sequences@29.6.3: {} + diff@7.0.0: {} + dir-glob@3.0.1: dependencies: path-type: 4.0.0