@tanstack/start-plugin-core 1.121.0-alpha.25 → 1.121.0-alpha.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/compilers.cjs +24 -10
- package/dist/cjs/compilers.cjs.map +1 -1
- package/dist/cjs/debug.cjs +5 -0
- package/dist/cjs/debug.cjs.map +1 -0
- package/dist/cjs/debug.d.cts +1 -0
- package/dist/cjs/nitro-plugin/build-sitemap.cjs +3 -3
- package/dist/cjs/nitro-plugin/build-sitemap.cjs.map +1 -1
- package/dist/cjs/nitro-plugin/plugin.cjs +2 -2
- package/dist/cjs/nitro-plugin/plugin.cjs.map +1 -1
- package/dist/cjs/nitro-plugin/prerender.cjs +3 -3
- package/dist/cjs/nitro-plugin/prerender.cjs.map +1 -1
- package/dist/cjs/plugin.cjs +19 -30
- package/dist/cjs/plugin.cjs.map +1 -1
- package/dist/cjs/plugin.d.cts +2 -4
- package/dist/cjs/schema.cjs +5 -5
- package/dist/cjs/schema.cjs.map +1 -1
- package/dist/cjs/schema.d.cts +32 -16
- package/dist/cjs/start-compiler-plugin.cjs +19 -17
- package/dist/cjs/start-compiler-plugin.cjs.map +1 -1
- package/dist/cjs/start-manifest-plugin/plugin.cjs +207 -0
- package/dist/cjs/start-manifest-plugin/plugin.cjs.map +1 -0
- package/dist/cjs/start-manifest-plugin/plugin.d.cts +3 -0
- package/dist/cjs/start-router-plugin/generator-plugins/routes-manifest-plugin.cjs +39 -0
- package/dist/cjs/start-router-plugin/generator-plugins/routes-manifest-plugin.cjs.map +1 -0
- package/dist/cjs/start-router-plugin/generator-plugins/routes-manifest-plugin.d.cts +6 -0
- package/dist/cjs/start-router-plugin/generator-plugins/server-routes-plugin.cjs +121 -0
- package/dist/cjs/start-router-plugin/generator-plugins/server-routes-plugin.cjs.map +1 -0
- package/dist/cjs/start-router-plugin/generator-plugins/server-routes-plugin.d.cts +2 -0
- package/dist/cjs/start-router-plugin/plugin.cjs +21 -0
- package/dist/cjs/start-router-plugin/plugin.cjs.map +1 -0
- package/dist/cjs/start-router-plugin/plugin.d.cts +3 -0
- package/dist/cjs/start-router-plugin/route-tree-client-plugin.cjs +72 -0
- package/dist/cjs/start-router-plugin/route-tree-client-plugin.cjs.map +1 -0
- package/dist/cjs/start-router-plugin/route-tree-client-plugin.d.cts +6 -0
- package/dist/cjs/start-router-plugin/virtual-route-tree-plugin.cjs +30 -0
- package/dist/cjs/start-router-plugin/virtual-route-tree-plugin.cjs.map +1 -0
- package/dist/cjs/start-router-plugin/virtual-route-tree-plugin.d.cts +4 -0
- package/dist/esm/compilers.js +24 -10
- package/dist/esm/compilers.js.map +1 -1
- package/dist/esm/debug.d.ts +1 -0
- package/dist/esm/debug.js +5 -0
- package/dist/esm/debug.js.map +1 -0
- package/dist/esm/plugin.d.ts +2 -4
- package/dist/esm/plugin.js +10 -21
- package/dist/esm/plugin.js.map +1 -1
- package/dist/esm/schema.d.ts +32 -16
- package/dist/esm/start-compiler-plugin.js +19 -17
- package/dist/esm/start-compiler-plugin.js.map +1 -1
- package/dist/esm/start-manifest-plugin/plugin.d.ts +3 -0
- package/dist/esm/start-manifest-plugin/plugin.js +207 -0
- package/dist/esm/start-manifest-plugin/plugin.js.map +1 -0
- package/dist/esm/start-router-plugin/generator-plugins/routes-manifest-plugin.d.ts +6 -0
- package/dist/esm/start-router-plugin/generator-plugins/routes-manifest-plugin.js +39 -0
- package/dist/esm/start-router-plugin/generator-plugins/routes-manifest-plugin.js.map +1 -0
- package/dist/esm/start-router-plugin/generator-plugins/server-routes-plugin.d.ts +2 -0
- package/dist/esm/start-router-plugin/generator-plugins/server-routes-plugin.js +121 -0
- package/dist/esm/start-router-plugin/generator-plugins/server-routes-plugin.js.map +1 -0
- package/dist/esm/start-router-plugin/plugin.d.ts +3 -0
- package/dist/esm/start-router-plugin/plugin.js +21 -0
- package/dist/esm/start-router-plugin/plugin.js.map +1 -0
- package/dist/esm/start-router-plugin/route-tree-client-plugin.d.ts +6 -0
- package/dist/esm/start-router-plugin/route-tree-client-plugin.js +55 -0
- package/dist/esm/start-router-plugin/route-tree-client-plugin.js.map +1 -0
- package/dist/esm/start-router-plugin/virtual-route-tree-plugin.d.ts +4 -0
- package/dist/esm/start-router-plugin/virtual-route-tree-plugin.js +30 -0
- package/dist/esm/start-router-plugin/virtual-route-tree-plugin.js.map +1 -0
- package/package.json +6 -5
- package/src/compilers.ts +31 -131
- package/src/debug.ts +3 -0
- package/src/global.d.ts +8 -0
- package/src/plugin.ts +8 -24
- package/src/start-compiler-plugin.ts +24 -24
- package/src/start-manifest-plugin/plugin.ts +275 -0
- package/src/start-router-plugin/generator-plugins/routes-manifest-plugin.ts +43 -0
- package/src/start-router-plugin/generator-plugins/server-routes-plugin.ts +138 -0
- package/src/start-router-plugin/plugin.ts +35 -0
- package/src/start-router-plugin/route-tree-client-plugin.ts +76 -0
- package/src/start-router-plugin/virtual-route-tree-plugin.ts +30 -0
- package/dist/cjs/start-routes-manifest-plugin/plugin.cjs +0 -207
- package/dist/cjs/start-routes-manifest-plugin/plugin.cjs.map +0 -1
- package/dist/cjs/start-routes-manifest-plugin/plugin.d.cts +0 -3
- package/dist/cjs/start-server-routes-plugin/config.d.cts +0 -49
- package/dist/cjs/start-server-routes-plugin/plugin.cjs +0 -614
- package/dist/cjs/start-server-routes-plugin/plugin.cjs.map +0 -1
- package/dist/cjs/start-server-routes-plugin/plugin.d.cts +0 -3
- package/dist/cjs/start-server-routes-plugin/template.cjs +0 -111
- package/dist/cjs/start-server-routes-plugin/template.cjs.map +0 -1
- package/dist/cjs/start-server-routes-plugin/template.d.cts +0 -34
- package/dist/esm/start-routes-manifest-plugin/plugin.d.ts +0 -3
- package/dist/esm/start-routes-manifest-plugin/plugin.js +0 -207
- package/dist/esm/start-routes-manifest-plugin/plugin.js.map +0 -1
- package/dist/esm/start-server-routes-plugin/config.d.ts +0 -49
- package/dist/esm/start-server-routes-plugin/plugin.d.ts +0 -3
- package/dist/esm/start-server-routes-plugin/plugin.js +0 -614
- package/dist/esm/start-server-routes-plugin/plugin.js.map +0 -1
- package/dist/esm/start-server-routes-plugin/template.d.ts +0 -34
- package/dist/esm/start-server-routes-plugin/template.js +0 -111
- package/dist/esm/start-server-routes-plugin/template.js.map +0 -1
- package/src/start-routes-manifest-plugin/plugin.ts +0 -282
- package/src/start-server-routes-plugin/config.ts +0 -8
- package/src/start-server-routes-plugin/plugin.ts +0 -900
- package/src/start-server-routes-plugin/template.ts +0 -164
package/dist/cjs/compilers.cjs
CHANGED
|
@@ -32,9 +32,28 @@ function compileStartOutputFactory(framework) {
|
|
|
32
32
|
Program: {
|
|
33
33
|
enter(programPath) {
|
|
34
34
|
const identifiers = {
|
|
35
|
+
createServerRootRoute: {
|
|
36
|
+
name: "createServerRootRoute",
|
|
37
|
+
handleCallExpression: handleCreateServerFileRouteCallExpressionFactory(
|
|
38
|
+
framework,
|
|
39
|
+
"createServerRootRoute"
|
|
40
|
+
),
|
|
41
|
+
paths: []
|
|
42
|
+
},
|
|
43
|
+
createServerRoute: {
|
|
44
|
+
name: "createServerRoute",
|
|
45
|
+
handleCallExpression: handleCreateServerFileRouteCallExpressionFactory(
|
|
46
|
+
framework,
|
|
47
|
+
"createServerRoute"
|
|
48
|
+
),
|
|
49
|
+
paths: []
|
|
50
|
+
},
|
|
35
51
|
createServerFileRoute: {
|
|
36
52
|
name: "createServerFileRoute",
|
|
37
|
-
handleCallExpression: handleCreateServerFileRouteCallExpressionFactory(
|
|
53
|
+
handleCallExpression: handleCreateServerFileRouteCallExpressionFactory(
|
|
54
|
+
framework,
|
|
55
|
+
"createServerFileRoute"
|
|
56
|
+
),
|
|
38
57
|
paths: []
|
|
39
58
|
},
|
|
40
59
|
createServerFn: {
|
|
@@ -66,7 +85,7 @@ function compileStartOutputFactory(framework) {
|
|
|
66
85
|
const identifierKeys = Object.keys(identifiers);
|
|
67
86
|
programPath.traverse({
|
|
68
87
|
ImportDeclaration: (path) => {
|
|
69
|
-
if (path.node.source.value !==
|
|
88
|
+
if (path.node.source.value !== `@tanstack/${framework}-start`) {
|
|
70
89
|
return;
|
|
71
90
|
}
|
|
72
91
|
path.node.specifiers.forEach((specifier) => {
|
|
@@ -128,7 +147,7 @@ function compileStartOutputFactory(framework) {
|
|
|
128
147
|
});
|
|
129
148
|
};
|
|
130
149
|
}
|
|
131
|
-
function handleCreateServerFileRouteCallExpressionFactory(factory) {
|
|
150
|
+
function handleCreateServerFileRouteCallExpressionFactory(factory, method) {
|
|
132
151
|
return function handleCreateServerFileRouteCallExpression(path, opts) {
|
|
133
152
|
const PACKAGES = { start: `@tanstack/${factory}-start/server` };
|
|
134
153
|
let highestParent = path;
|
|
@@ -147,19 +166,14 @@ function handleCreateServerFileRouteCallExpressionFactory(factory) {
|
|
|
147
166
|
if (importSource === PACKAGES.start) {
|
|
148
167
|
const specifiers = importPath.node.specifiers;
|
|
149
168
|
isCreateServerFileRouteImported = specifiers.some((specifier) => {
|
|
150
|
-
return t__namespace.isImportSpecifier(specifier) && t__namespace.isIdentifier(specifier.imported) && specifier.imported.name ===
|
|
169
|
+
return t__namespace.isImportSpecifier(specifier) && t__namespace.isIdentifier(specifier.imported) && specifier.imported.name === method;
|
|
151
170
|
});
|
|
152
171
|
}
|
|
153
172
|
}
|
|
154
173
|
});
|
|
155
174
|
if (!isCreateServerFileRouteImported) {
|
|
156
175
|
const importDeclaration = t__namespace.importDeclaration(
|
|
157
|
-
[
|
|
158
|
-
t__namespace.importSpecifier(
|
|
159
|
-
t__namespace.identifier("createServerFileRoute"),
|
|
160
|
-
t__namespace.identifier("createServerFileRoute")
|
|
161
|
-
)
|
|
162
|
-
],
|
|
176
|
+
[t__namespace.importSpecifier(t__namespace.identifier(method), t__namespace.identifier(method))],
|
|
163
177
|
t__namespace.stringLiteral(PACKAGES.start)
|
|
164
178
|
);
|
|
165
179
|
programPath.node.body.unshift(importDeclaration);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compilers.cjs","sources":["../../src/compilers.ts"],"sourcesContent":["import * as babel from '@babel/core'\nimport * as t from '@babel/types'\nimport { codeFrameColumns } from '@babel/code-frame'\n\nimport {\n deadCodeElimination,\n findReferencedIdentifiers,\n} from 'babel-dead-code-elimination'\nimport { generateFromAst, parseAst } from '@tanstack/router-utils'\nimport type { GeneratorResult, ParseAstOptions } from '@tanstack/router-utils'\n\nexport type CompileStartFrameworkOptions = 'react' | 'solid'\n\nexport function compileStartOutputFactory(\n framework: CompileStartFrameworkOptions,\n) {\n return function compileStartOutput(opts: CompileOptions): GeneratorResult {\n const ast = parseAst(opts)\n\n const doDce = opts.dce ?? true\n // find referenced identifiers *before* we transform anything\n const refIdents = doDce ? findReferencedIdentifiers(ast) : undefined\n\n babel.traverse(ast, {\n Program: {\n enter(programPath) {\n const identifiers: {\n createServerFileRoute: IdentifierConfig\n createServerFn: IdentifierConfig\n createMiddleware: IdentifierConfig\n serverOnly: IdentifierConfig\n clientOnly: IdentifierConfig\n createIsomorphicFn: IdentifierConfig\n } = {\n createServerFileRoute: {\n name: 'createServerFileRoute',\n handleCallExpression:\n handleCreateServerFileRouteCallExpressionFactory(framework),\n paths: [],\n },\n createServerFn: {\n name: 'createServerFn',\n handleCallExpression: handleCreateServerFnCallExpression,\n paths: [],\n },\n createMiddleware: {\n name: 'createMiddleware',\n handleCallExpression: handleCreateMiddlewareCallExpression,\n paths: [],\n },\n serverOnly: {\n name: 'serverOnly',\n handleCallExpression: handleServerOnlyCallExpression,\n paths: [],\n },\n clientOnly: {\n name: 'clientOnly',\n handleCallExpression: handleClientOnlyCallExpression,\n paths: [],\n },\n createIsomorphicFn: {\n name: 'createIsomorphicFn',\n handleCallExpression: handleCreateIsomorphicFnCallExpression,\n paths: [],\n },\n }\n\n const identifierKeys = Object.keys(identifiers) as Array<\n keyof typeof identifiers\n >\n\n programPath.traverse({\n ImportDeclaration: (path) => {\n if (\n path.node.source.value !== '@tanstack/react-start' &&\n path.node.source.value !== '@tanstack/solid-start'\n ) {\n return\n }\n\n // handle a destructured imports being renamed like \"import { createServerFn as myCreateServerFn } from '@tanstack/react-start';\"\n path.node.specifiers.forEach((specifier) => {\n identifierKeys.forEach((identifierKey) => {\n const identifier = identifiers[identifierKey]\n\n if (\n specifier.type === 'ImportSpecifier' &&\n specifier.imported.type === 'Identifier'\n ) {\n if (specifier.imported.name === identifierKey) {\n identifier.name = specifier.local.name\n }\n }\n\n // handle namespace imports like \"import * as TanStackStart from '@tanstack/react-start';\"\n if (specifier.type === 'ImportNamespaceSpecifier') {\n identifier.name = `${specifier.local.name}.${identifierKey}`\n }\n })\n })\n },\n CallExpression: (path) => {\n identifierKeys.forEach((identifierKey) => {\n // Check to see if the call expression is a call to the\n // identifiers[identifierKey].name\n if (\n t.isIdentifier(path.node.callee) &&\n path.node.callee.name === identifiers[identifierKey].name\n ) {\n // The identifier could be a call to the original function\n // in the source code. If this is case, we need to ignore it.\n // Check the scope to see if the identifier is a function declaration.\n // if it is, then we can ignore it.\n\n if (\n path.scope.getBinding(identifiers[identifierKey].name)?.path\n .node.type === 'FunctionDeclaration'\n ) {\n return\n }\n\n return identifiers[identifierKey].paths.push(path)\n }\n\n if (t.isMemberExpression(path.node.callee)) {\n if (\n t.isIdentifier(path.node.callee.object) &&\n t.isIdentifier(path.node.callee.property)\n ) {\n const callname = [\n path.node.callee.object.name,\n path.node.callee.property.name,\n ].join('.')\n\n if (callname === identifiers[identifierKey].name) {\n identifiers[identifierKey].paths.push(path)\n }\n }\n }\n\n return\n })\n },\n })\n\n identifierKeys.forEach((identifierKey) => {\n identifiers[identifierKey].paths.forEach((path) => {\n identifiers[identifierKey].handleCallExpression(\n path as babel.NodePath<t.CallExpression>,\n opts,\n )\n })\n })\n },\n },\n })\n\n if (doDce) {\n deadCodeElimination(ast, refIdents)\n }\n\n return generateFromAst(ast, {\n sourceMaps: true,\n sourceFileName: opts.filename,\n filename: opts.filename,\n })\n }\n}\n\nfunction handleCreateServerFileRouteCallExpressionFactory(\n factory: CompileStartFrameworkOptions,\n) {\n return function handleCreateServerFileRouteCallExpression(\n path: babel.NodePath<t.CallExpression>,\n opts: CompileOptions,\n ) {\n const PACKAGES = { start: `@tanstack/${factory}-start/server` }\n\n let highestParent: babel.NodePath<any> = path\n\n while (highestParent.parentPath && !highestParent.parentPath.isProgram()) {\n highestParent = highestParent.parentPath\n }\n\n const programPath = highestParent.parentPath as babel.NodePath<t.Program>\n\n // // Find the root call expression and all of the methods that are called on it\n // const rootCallExpression = getRootCallExpression(path)\n\n // const callExpressionPaths = {\n // validator: null as babel.NodePath<t.CallExpression> | null,\n // middleware: null as babel.NodePath<t.CallExpression> | null,\n // methods: null as babel.NodePath<t.CallExpression> | null,\n // }\n\n // const validMethods = Object.keys(callExpressionPaths)\n\n // rootCallExpression.traverse({\n // MemberExpression(memberExpressionPath) {\n // if (t.isIdentifier(memberExpressionPath.node.property)) {\n // const name = memberExpressionPath.node.property\n // .name as keyof typeof callExpressionPaths\n\n // if (\n // validMethods.includes(name) &&\n // memberExpressionPath.parentPath.isCallExpression()\n // ) {\n // callExpressionPaths[name] = memberExpressionPath.parentPath\n // }\n // }\n // },\n // })\n\n // const manifest = { middleware: false, methods: {} as any }\n\n // Object.entries(callExpressionPaths).forEach(([key, callPath]) => {\n // if (callPath && t.isMemberExpression(callPath.node.callee)) {\n // if (key === 'middleware') {\n // manifest.middleware = true\n // } else if (key === 'methods') {\n // // Get the methods object from the methods call\n // const methodsArg = callPath.node.arguments[0]\n\n // // Handle the case where methods is a function that returns an object\n // if (\n // t.isArrowFunctionExpression(methodsArg) &&\n // t.isObjectExpression(methodsArg.body)\n // ) {\n // methodsArg.body.properties.forEach((prop) => {\n // if (t.isObjectProperty(prop) && t.isIdentifier(prop.key)) {\n // const methodName = prop.key.name\n // manifest.methods[methodName] = {\n // middleware: false,\n // }\n\n // // Check if this method has a middleware\n // if (t.isCallExpression(prop.value)) {\n // const method = prop.value\n // method.arguments.forEach((arg) => {\n // if (t.isObjectExpression(arg)) {\n // arg.properties.forEach((methodProp) => {\n // if (\n // t.isObjectProperty(methodProp) &&\n // t.isIdentifier(methodProp.key)\n // ) {\n // if (methodProp.key.name === 'middleware') {\n // manifest.methods[methodName].middleware = true\n // }\n // }\n // })\n // }\n // })\n // }\n // }\n // })\n // }\n // // Handle the case where methods is a direct object\n // else if (t.isObjectExpression(methodsArg)) {\n // methodsArg.properties.forEach((prop) => {\n // if (t.isObjectProperty(prop) && t.isIdentifier(prop.key)) {\n // const methodName = prop.key.name\n // manifest.methods[methodName] = {\n // middleware: false,\n // }\n // }\n // })\n // }\n // }\n\n // if (opts.env === 'client') {\n // callPath.replaceWith(callPath.node.callee.object)\n // }\n // }\n // })\n\n // If we're on the client, remove the entire variable\n if (opts.env === 'client') {\n // console.debug('createServerFileRoute -> manifest:\\n', manifest)\n highestParent.remove()\n return\n }\n\n // path.replaceWith(\n // t.callExpression(t.identifier('createServerFileRoute'), [\n // t.identifier('undefined'),\n // t.callExpression(\n // t.memberExpression(t.identifier('Object'), t.identifier('assign')),\n // [\n // t.objectExpression(\n // path.node.arguments\n // .map((arg) => {\n // if (t.isIdentifier(arg)) {\n // return t.objectProperty(t.identifier(arg.name), arg)\n // }\n // // Handle other cases or return a default value if necessary\n // return null // or throw an error, or handle accordingly\n // })\n // .filter(\n // (property): property is t.ObjectProperty => property !== null,\n // ),\n // ),\n // t.objectExpression([\n // t.objectProperty(\n // t.identifier('manifest'),\n // t.valueToNode(manifest),\n // ),\n // ]),\n // ],\n // ),\n // ]),\n // )\n\n let isCreateServerFileRouteImported = false as boolean\n\n programPath.traverse({\n ImportDeclaration(importPath) {\n const importSource = importPath.node.source.value\n if (importSource === PACKAGES.start) {\n const specifiers = importPath.node.specifiers\n isCreateServerFileRouteImported = specifiers.some((specifier) => {\n return (\n t.isImportSpecifier(specifier) &&\n t.isIdentifier(specifier.imported) &&\n specifier.imported.name === 'createServerFileRoute'\n )\n })\n }\n },\n })\n\n if (!isCreateServerFileRouteImported) {\n const importDeclaration = t.importDeclaration(\n [\n t.importSpecifier(\n t.identifier('createServerFileRoute'),\n t.identifier('createServerFileRoute'),\n ),\n ],\n t.stringLiteral(PACKAGES.start),\n )\n programPath.node.body.unshift(importDeclaration)\n }\n }\n}\n\n// build these once and reuse them\nexport const handleServerOnlyCallExpression =\n buildEnvOnlyCallExpressionHandler('server')\nexport const handleClientOnlyCallExpression =\n buildEnvOnlyCallExpressionHandler('client')\n\nexport type CompileOptions = ParseAstOptions & {\n env: 'server' | 'client'\n dce?: boolean\n filename: string\n}\n\nexport type IdentifierConfig = {\n name: string\n handleCallExpression: (\n path: babel.NodePath<t.CallExpression>,\n opts: CompileOptions,\n ) => void\n paths: Array<babel.NodePath>\n}\n\nexport function handleCreateServerFnCallExpression(\n path: babel.NodePath<t.CallExpression>,\n opts: CompileOptions,\n) {\n // The function is the 'fn' property of the object passed to createServerFn\n\n // const firstArg = path.node.arguments[0]\n // if (t.isObjectExpression(firstArg)) {\n // // Was called with some options\n // }\n\n // Traverse the member expression and find the call expressions for\n // the validator, handler, and middleware methods. Check to make sure they\n // are children of the createServerFn call expression.\n\n const calledOptions = path.node.arguments[0]\n ? (path.get('arguments.0') as babel.NodePath<t.ObjectExpression>)\n : null\n\n const shouldValidateClient = !!calledOptions?.node.properties.find((prop) => {\n return (\n t.isObjectProperty(prop) &&\n t.isIdentifier(prop.key) &&\n prop.key.name === 'validateClient' &&\n t.isBooleanLiteral(prop.value) &&\n prop.value.value === true\n )\n })\n\n const callExpressionPaths = {\n middleware: null as babel.NodePath<t.CallExpression> | null,\n validator: null as babel.NodePath<t.CallExpression> | null,\n handler: null as babel.NodePath<t.CallExpression> | null,\n }\n\n const validMethods = Object.keys(callExpressionPaths)\n\n const rootCallExpression = getRootCallExpression(path)\n\n // if (debug)\n // console.info(\n // 'Handling createServerFn call expression:',\n // rootCallExpression.toString(),\n // )\n\n // Check if the call is assigned to a variable\n if (!rootCallExpression.parentPath.isVariableDeclarator()) {\n throw new Error('createServerFn must be assigned to a variable!')\n }\n\n // Get the identifier name of the variable\n const variableDeclarator = rootCallExpression.parentPath.node\n const existingVariableName = (variableDeclarator.id as t.Identifier).name\n\n rootCallExpression.traverse({\n MemberExpression(memberExpressionPath) {\n if (t.isIdentifier(memberExpressionPath.node.property)) {\n const name = memberExpressionPath.node.property\n .name as keyof typeof callExpressionPaths\n\n if (\n validMethods.includes(name) &&\n memberExpressionPath.parentPath.isCallExpression()\n ) {\n callExpressionPaths[name] = memberExpressionPath.parentPath\n }\n }\n },\n })\n\n if (callExpressionPaths.validator) {\n const innerInputExpression = callExpressionPaths.validator.node.arguments[0]\n\n if (!innerInputExpression) {\n throw new Error(\n 'createServerFn().validator() must be called with a validator!',\n )\n }\n\n // If we're on the client, and we're not validating the client, remove the validator call expression\n if (\n opts.env === 'client' &&\n !shouldValidateClient &&\n t.isMemberExpression(callExpressionPaths.validator.node.callee)\n ) {\n callExpressionPaths.validator.replaceWith(\n callExpressionPaths.validator.node.callee.object,\n )\n }\n }\n\n // First, we need to move the handler function to a nested function call\n // that is applied to the arguments passed to the server function.\n\n const handlerFnPath = callExpressionPaths.handler?.get(\n 'arguments.0',\n ) as babel.NodePath<any>\n\n if (!callExpressionPaths.handler || !handlerFnPath.node) {\n throw codeFrameError(\n opts.code,\n path.node.callee.loc!,\n `createServerFn must be called with a \"handler\" property!`,\n )\n }\n\n const handlerFn = handlerFnPath.node\n\n // So, the way we do this is we give the handler function a way\n // to access the serverFn ctx on the server via function scope.\n // The 'use server' extracted function will be called with the\n // payload from the client, then use the scoped serverFn ctx\n // to execute the handler function.\n // This way, we can do things like data and middleware validation\n // in the __execute function without having to AST transform the\n // handler function too much itself.\n\n // .handler((optsOut, ctx) => {\n // return ((optsIn) => {\n // 'use server'\n // ctx.__execute(handlerFn, optsIn)\n // })(optsOut)\n // })\n\n // If the handler function is an identifier and we're on the client, we need to\n // remove the bound function from the file.\n // If we're on the server, you can leave it, since it will get referenced\n // as a second argument.\n\n if (t.isIdentifier(handlerFn)) {\n if (opts.env === 'client') {\n // Find the binding for the handler function\n const binding = handlerFnPath.scope.getBinding(handlerFn.name)\n // Remove it\n if (binding) {\n binding.path.remove()\n }\n }\n // If the env is server, just leave it alone\n }\n\n handlerFnPath.replaceWith(\n t.arrowFunctionExpression(\n [t.identifier('opts'), t.identifier('signal')],\n t.blockStatement(\n // Everything in here is server-only, since the client\n // will strip out anything in the 'use server' directive.\n [\n t.returnStatement(\n t.callExpression(\n t.identifier(`${existingVariableName}.__executeServer`),\n [t.identifier('opts'), t.identifier('signal')],\n ),\n ),\n ],\n [t.directive(t.directiveLiteral('use server'))],\n ),\n ),\n )\n\n if (opts.env === 'server') {\n callExpressionPaths.handler.node.arguments.push(handlerFn)\n }\n}\n\nexport function handleCreateMiddlewareCallExpression(\n path: babel.NodePath<t.CallExpression>,\n opts: CompileOptions,\n) {\n const rootCallExpression = getRootCallExpression(path)\n\n // if (debug)\n // console.info(\n // 'Handling createMiddleware call expression:',\n // rootCallExpression.toString(),\n // )\n\n const callExpressionPaths = {\n middleware: null as babel.NodePath<t.CallExpression> | null,\n validator: null as babel.NodePath<t.CallExpression> | null,\n client: null as babel.NodePath<t.CallExpression> | null,\n server: null as babel.NodePath<t.CallExpression> | null,\n }\n\n const validMethods = Object.keys(callExpressionPaths)\n\n rootCallExpression.traverse({\n MemberExpression(memberExpressionPath) {\n if (t.isIdentifier(memberExpressionPath.node.property)) {\n const name = memberExpressionPath.node.property\n .name as keyof typeof callExpressionPaths\n\n if (\n validMethods.includes(name) &&\n memberExpressionPath.parentPath.isCallExpression()\n ) {\n callExpressionPaths[name] = memberExpressionPath.parentPath\n }\n }\n },\n })\n\n if (callExpressionPaths.validator) {\n const innerInputExpression = callExpressionPaths.validator.node.arguments[0]\n\n if (!innerInputExpression) {\n throw new Error(\n 'createMiddleware().validator() must be called with a validator!',\n )\n }\n\n // If we're on the client, remove the validator call expression\n if (opts.env === 'client') {\n if (t.isMemberExpression(callExpressionPaths.validator.node.callee)) {\n callExpressionPaths.validator.replaceWith(\n callExpressionPaths.validator.node.callee.object,\n )\n }\n }\n }\n\n const serverFnPath = callExpressionPaths.server?.get(\n 'arguments.0',\n ) as babel.NodePath<any>\n\n if (\n callExpressionPaths.server &&\n serverFnPath.node &&\n opts.env === 'client'\n ) {\n // If we're on the client, remove the server call expression\n if (t.isMemberExpression(callExpressionPaths.server.node.callee)) {\n callExpressionPaths.server.replaceWith(\n callExpressionPaths.server.node.callee.object,\n )\n }\n }\n}\n\nfunction buildEnvOnlyCallExpressionHandler(env: 'client' | 'server') {\n return function envOnlyCallExpressionHandler(\n path: babel.NodePath<t.CallExpression>,\n opts: CompileOptions,\n ) {\n // if (debug)\n // console.info(`Handling ${env}Only call expression:`, path.toString())\n\n const isEnvMatch =\n env === 'client' ? opts.env === 'client' : opts.env === 'server'\n\n if (isEnvMatch) {\n // extract the inner function from the call expression\n const innerInputExpression = path.node.arguments[0]\n\n if (!t.isExpression(innerInputExpression)) {\n throw new Error(\n `${env}Only() functions must be called with a function!`,\n )\n }\n\n path.replaceWith(innerInputExpression)\n return\n }\n\n // If we're on the wrong environment, replace the call expression\n // with a function that always throws an error.\n path.replaceWith(\n t.arrowFunctionExpression(\n [],\n t.blockStatement([\n t.throwStatement(\n t.newExpression(t.identifier('Error'), [\n t.stringLiteral(\n `${env}Only() functions can only be called on the ${env}!`,\n ),\n ]),\n ),\n ]),\n ),\n )\n }\n}\n\nexport function handleCreateIsomorphicFnCallExpression(\n path: babel.NodePath<t.CallExpression>,\n opts: CompileOptions,\n) {\n const rootCallExpression = getRootCallExpression(path)\n\n // if (debug)\n // console.info(\n // 'Handling createIsomorphicFn call expression:',\n // rootCallExpression.toString(),\n // )\n\n const callExpressionPaths = {\n client: null as babel.NodePath<t.CallExpression> | null,\n server: null as babel.NodePath<t.CallExpression> | null,\n }\n\n const validMethods = Object.keys(callExpressionPaths)\n\n rootCallExpression.traverse({\n MemberExpression(memberExpressionPath) {\n if (t.isIdentifier(memberExpressionPath.node.property)) {\n const name = memberExpressionPath.node.property\n .name as keyof typeof callExpressionPaths\n\n if (\n validMethods.includes(name) &&\n memberExpressionPath.parentPath.isCallExpression()\n ) {\n callExpressionPaths[name] = memberExpressionPath.parentPath\n }\n }\n },\n })\n\n if (\n validMethods.every(\n (method) =>\n !callExpressionPaths[method as keyof typeof callExpressionPaths],\n )\n ) {\n const variableId = rootCallExpression.parentPath.isVariableDeclarator()\n ? rootCallExpression.parentPath.node.id\n : null\n console.warn(\n 'createIsomorphicFn called without a client or server implementation!',\n 'This will result in a no-op function.',\n 'Variable name:',\n t.isIdentifier(variableId) ? variableId.name : 'unknown',\n )\n }\n\n const envCallExpression = callExpressionPaths[opts.env]\n\n if (!envCallExpression) {\n // if we don't have an implementation for this environment, default to a no-op\n rootCallExpression.replaceWith(\n t.arrowFunctionExpression([], t.blockStatement([])),\n )\n return\n }\n\n const innerInputExpression = envCallExpression.node.arguments[0]\n\n if (!t.isExpression(innerInputExpression)) {\n throw new Error(\n `createIsomorphicFn().${opts.env}(func) must be called with a function!`,\n )\n }\n\n rootCallExpression.replaceWith(innerInputExpression)\n}\n\nexport function getRootCallExpression(path: babel.NodePath<t.CallExpression>) {\n // Find the highest callExpression parent\n let rootCallExpression: babel.NodePath<t.CallExpression> = path\n\n // Traverse up the chain of CallExpressions\n while (rootCallExpression.parentPath.isMemberExpression()) {\n const parent = rootCallExpression.parentPath\n if (parent.parentPath.isCallExpression()) {\n rootCallExpression = parent.parentPath\n }\n }\n\n return rootCallExpression\n}\n\nfunction codeFrameError(\n code: string,\n loc: {\n start: { line: number; column: number }\n end: { line: number; column: number }\n },\n message: string,\n) {\n const frame = codeFrameColumns(\n code,\n {\n start: loc.start,\n end: loc.end,\n },\n {\n highlightCode: true,\n message,\n },\n )\n\n return new Error(frame)\n}\n"],"names":["parseAst","findReferencedIdentifiers","babel","t","deadCodeElimination","generateFromAst","codeFrameColumns"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAaO,SAAS,0BACd,WACA;AACO,SAAA,SAAS,mBAAmB,MAAuC;AAClE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AM,IAAI;AAAA,MACR,wBAAwB,KAAK,GAAG;AAAA,IAClC;AAAA,EAAA;AAGF,qBAAmB,YAAY,oBAAoB;AACrD;AAEO,SAAS,sBAAsB,MAAwC;AAE5E,MAAI,qBAAuD;AAGpD,SAAA,mBAAmB,WAAW,sBAAsB;AACzD,UAAM,SAAS,mBAAmB;AAC9B,QAAA,OAAO,WAAW,oBAAoB;AACxC,2BAAqB,OAAO;AAAA,IAAA;AAAA,EAC9B;AAGK,SAAA;AACT;AAEA,SAAS,eACP,MACA,KAIA,SACA;AACA,QAAM,QAAQG,UAAA;AAAA,IACZ;AAAA,IACA;AAAA,MACE,OAAO,IAAI;AAAA,MACX,KAAK,IAAI;AAAA,IACX;AAAA,IACA;AAAA,MACE,eAAe;AAAA,MACf;AAAA,IAAA;AAAA,EAEJ;AAEO,SAAA,IAAI,MAAM,KAAK;AACxB;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"compilers.cjs","sources":["../../src/compilers.ts"],"sourcesContent":["import * as babel from '@babel/core'\nimport * as t from '@babel/types'\nimport { codeFrameColumns } from '@babel/code-frame'\n\nimport {\n deadCodeElimination,\n findReferencedIdentifiers,\n} from 'babel-dead-code-elimination'\nimport { generateFromAst, parseAst } from '@tanstack/router-utils'\nimport type { GeneratorResult, ParseAstOptions } from '@tanstack/router-utils'\n\nexport type CompileStartFrameworkOptions = 'react' | 'solid'\n\nexport function compileStartOutputFactory(\n framework: CompileStartFrameworkOptions,\n) {\n return function compileStartOutput(opts: CompileOptions): GeneratorResult {\n const ast = parseAst(opts)\n\n const doDce = opts.dce ?? true\n // find referenced identifiers *before* we transform anything\n const refIdents = doDce ? findReferencedIdentifiers(ast) : undefined\n\n babel.traverse(ast, {\n Program: {\n enter(programPath) {\n const identifiers: {\n createServerRoute: IdentifierConfig\n createServerFileRoute: IdentifierConfig\n createServerFn: IdentifierConfig\n createMiddleware: IdentifierConfig\n serverOnly: IdentifierConfig\n clientOnly: IdentifierConfig\n createIsomorphicFn: IdentifierConfig\n createServerRootRoute: IdentifierConfig\n } = {\n createServerRootRoute: {\n name: 'createServerRootRoute',\n handleCallExpression:\n handleCreateServerFileRouteCallExpressionFactory(\n framework,\n 'createServerRootRoute',\n ),\n paths: [],\n },\n createServerRoute: {\n name: 'createServerRoute',\n handleCallExpression:\n handleCreateServerFileRouteCallExpressionFactory(\n framework,\n 'createServerRoute',\n ),\n paths: [],\n },\n createServerFileRoute: {\n name: 'createServerFileRoute',\n handleCallExpression:\n handleCreateServerFileRouteCallExpressionFactory(\n framework,\n 'createServerFileRoute',\n ),\n paths: [],\n },\n createServerFn: {\n name: 'createServerFn',\n handleCallExpression: handleCreateServerFnCallExpression,\n paths: [],\n },\n createMiddleware: {\n name: 'createMiddleware',\n handleCallExpression: handleCreateMiddlewareCallExpression,\n paths: [],\n },\n serverOnly: {\n name: 'serverOnly',\n handleCallExpression: handleServerOnlyCallExpression,\n paths: [],\n },\n clientOnly: {\n name: 'clientOnly',\n handleCallExpression: handleClientOnlyCallExpression,\n paths: [],\n },\n createIsomorphicFn: {\n name: 'createIsomorphicFn',\n handleCallExpression: handleCreateIsomorphicFnCallExpression,\n paths: [],\n },\n }\n\n const identifierKeys = Object.keys(identifiers) as Array<\n keyof typeof identifiers\n >\n\n programPath.traverse({\n ImportDeclaration: (path) => {\n if (path.node.source.value !== `@tanstack/${framework}-start`) {\n return\n }\n\n // handle a destructured imports being renamed like \"import { createServerFn as myCreateServerFn } from '@tanstack/react-start';\"\n path.node.specifiers.forEach((specifier) => {\n identifierKeys.forEach((identifierKey) => {\n const identifier = identifiers[identifierKey]\n\n if (\n specifier.type === 'ImportSpecifier' &&\n specifier.imported.type === 'Identifier'\n ) {\n if (specifier.imported.name === identifierKey) {\n identifier.name = specifier.local.name\n }\n }\n\n // handle namespace imports like \"import * as TanStackStart from '@tanstack/react-start';\"\n if (specifier.type === 'ImportNamespaceSpecifier') {\n identifier.name = `${specifier.local.name}.${identifierKey}`\n }\n })\n })\n },\n CallExpression: (path) => {\n identifierKeys.forEach((identifierKey) => {\n // Check to see if the call expression is a call to the\n // identifiers[identifierKey].name\n if (\n t.isIdentifier(path.node.callee) &&\n path.node.callee.name === identifiers[identifierKey].name\n ) {\n // The identifier could be a call to the original function\n // in the source code. If this is case, we need to ignore it.\n // Check the scope to see if the identifier is a function declaration.\n // if it is, then we can ignore it.\n\n if (\n path.scope.getBinding(identifiers[identifierKey].name)?.path\n .node.type === 'FunctionDeclaration'\n ) {\n return\n }\n\n return identifiers[identifierKey].paths.push(path)\n }\n\n if (t.isMemberExpression(path.node.callee)) {\n if (\n t.isIdentifier(path.node.callee.object) &&\n t.isIdentifier(path.node.callee.property)\n ) {\n const callname = [\n path.node.callee.object.name,\n path.node.callee.property.name,\n ].join('.')\n\n if (callname === identifiers[identifierKey].name) {\n identifiers[identifierKey].paths.push(path)\n }\n }\n }\n\n return\n })\n },\n })\n\n identifierKeys.forEach((identifierKey) => {\n identifiers[identifierKey].paths.forEach((path) => {\n identifiers[identifierKey].handleCallExpression(\n path as babel.NodePath<t.CallExpression>,\n opts,\n )\n })\n })\n },\n },\n })\n\n if (doDce) {\n deadCodeElimination(ast, refIdents)\n }\n\n return generateFromAst(ast, {\n sourceMaps: true,\n sourceFileName: opts.filename,\n filename: opts.filename,\n })\n }\n}\n\nfunction handleCreateServerFileRouteCallExpressionFactory(\n factory: CompileStartFrameworkOptions,\n method:\n | 'createServerFileRoute'\n | 'createServerRoute'\n | 'createServerRootRoute',\n) {\n return function handleCreateServerFileRouteCallExpression(\n path: babel.NodePath<t.CallExpression>,\n opts: CompileOptions,\n ) {\n const PACKAGES = { start: `@tanstack/${factory}-start/server` }\n\n let highestParent: babel.NodePath<any> = path\n\n while (highestParent.parentPath && !highestParent.parentPath.isProgram()) {\n highestParent = highestParent.parentPath\n }\n\n const programPath = highestParent.parentPath as babel.NodePath<t.Program>\n\n // If we're on the client, remove the entire variable\n if (opts.env === 'client') {\n // console.debug('createServerFileRoute -> manifest:\\n', manifest)\n highestParent.remove()\n return\n }\n\n let isCreateServerFileRouteImported = false as boolean\n\n programPath.traverse({\n ImportDeclaration(importPath) {\n const importSource = importPath.node.source.value\n if (importSource === PACKAGES.start) {\n const specifiers = importPath.node.specifiers\n isCreateServerFileRouteImported = specifiers.some((specifier) => {\n return (\n t.isImportSpecifier(specifier) &&\n t.isIdentifier(specifier.imported) &&\n specifier.imported.name === method\n )\n })\n }\n },\n })\n\n if (!isCreateServerFileRouteImported) {\n const importDeclaration = t.importDeclaration(\n [t.importSpecifier(t.identifier(method), t.identifier(method))],\n t.stringLiteral(PACKAGES.start),\n )\n programPath.node.body.unshift(importDeclaration)\n }\n }\n}\n\n// build these once and reuse them\nexport const handleServerOnlyCallExpression =\n buildEnvOnlyCallExpressionHandler('server')\nexport const handleClientOnlyCallExpression =\n buildEnvOnlyCallExpressionHandler('client')\n\nexport type CompileOptions = ParseAstOptions & {\n env: 'server' | 'client'\n dce?: boolean\n filename: string\n}\n\nexport type IdentifierConfig = {\n name: string\n handleCallExpression: (\n path: babel.NodePath<t.CallExpression>,\n opts: CompileOptions,\n ) => void\n paths: Array<babel.NodePath>\n}\n\nexport function handleCreateServerFnCallExpression(\n path: babel.NodePath<t.CallExpression>,\n opts: CompileOptions,\n) {\n // The function is the 'fn' property of the object passed to createServerFn\n\n // const firstArg = path.node.arguments[0]\n // if (t.isObjectExpression(firstArg)) {\n // // Was called with some options\n // }\n\n // Traverse the member expression and find the call expressions for\n // the validator, handler, and middleware methods. Check to make sure they\n // are children of the createServerFn call expression.\n\n const calledOptions = path.node.arguments[0]\n ? (path.get('arguments.0') as babel.NodePath<t.ObjectExpression>)\n : null\n\n const shouldValidateClient = !!calledOptions?.node.properties.find((prop) => {\n return (\n t.isObjectProperty(prop) &&\n t.isIdentifier(prop.key) &&\n prop.key.name === 'validateClient' &&\n t.isBooleanLiteral(prop.value) &&\n prop.value.value === true\n )\n })\n\n const callExpressionPaths = {\n middleware: null as babel.NodePath<t.CallExpression> | null,\n validator: null as babel.NodePath<t.CallExpression> | null,\n handler: null as babel.NodePath<t.CallExpression> | null,\n }\n\n const validMethods = Object.keys(callExpressionPaths)\n\n const rootCallExpression = getRootCallExpression(path)\n\n // if (debug)\n // console.info(\n // 'Handling createServerFn call expression:',\n // rootCallExpression.toString(),\n // )\n\n // Check if the call is assigned to a variable\n if (!rootCallExpression.parentPath.isVariableDeclarator()) {\n throw new Error('createServerFn must be assigned to a variable!')\n }\n\n // Get the identifier name of the variable\n const variableDeclarator = rootCallExpression.parentPath.node\n const existingVariableName = (variableDeclarator.id as t.Identifier).name\n\n rootCallExpression.traverse({\n MemberExpression(memberExpressionPath) {\n if (t.isIdentifier(memberExpressionPath.node.property)) {\n const name = memberExpressionPath.node.property\n .name as keyof typeof callExpressionPaths\n\n if (\n validMethods.includes(name) &&\n memberExpressionPath.parentPath.isCallExpression()\n ) {\n callExpressionPaths[name] = memberExpressionPath.parentPath\n }\n }\n },\n })\n\n if (callExpressionPaths.validator) {\n const innerInputExpression = callExpressionPaths.validator.node.arguments[0]\n\n if (!innerInputExpression) {\n throw new Error(\n 'createServerFn().validator() must be called with a validator!',\n )\n }\n\n // If we're on the client, and we're not validating the client, remove the validator call expression\n if (\n opts.env === 'client' &&\n !shouldValidateClient &&\n t.isMemberExpression(callExpressionPaths.validator.node.callee)\n ) {\n callExpressionPaths.validator.replaceWith(\n callExpressionPaths.validator.node.callee.object,\n )\n }\n }\n\n // First, we need to move the handler function to a nested function call\n // that is applied to the arguments passed to the server function.\n\n const handlerFnPath = callExpressionPaths.handler?.get(\n 'arguments.0',\n ) as babel.NodePath<any>\n\n if (!callExpressionPaths.handler || !handlerFnPath.node) {\n throw codeFrameError(\n opts.code,\n path.node.callee.loc!,\n `createServerFn must be called with a \"handler\" property!`,\n )\n }\n\n const handlerFn = handlerFnPath.node\n\n // So, the way we do this is we give the handler function a way\n // to access the serverFn ctx on the server via function scope.\n // The 'use server' extracted function will be called with the\n // payload from the client, then use the scoped serverFn ctx\n // to execute the handler function.\n // This way, we can do things like data and middleware validation\n // in the __execute function without having to AST transform the\n // handler function too much itself.\n\n // .handler((optsOut, ctx) => {\n // return ((optsIn) => {\n // 'use server'\n // ctx.__execute(handlerFn, optsIn)\n // })(optsOut)\n // })\n\n // If the handler function is an identifier and we're on the client, we need to\n // remove the bound function from the file.\n // If we're on the server, you can leave it, since it will get referenced\n // as a second argument.\n\n if (t.isIdentifier(handlerFn)) {\n if (opts.env === 'client') {\n // Find the binding for the handler function\n const binding = handlerFnPath.scope.getBinding(handlerFn.name)\n // Remove it\n if (binding) {\n binding.path.remove()\n }\n }\n // If the env is server, just leave it alone\n }\n\n handlerFnPath.replaceWith(\n t.arrowFunctionExpression(\n [t.identifier('opts'), t.identifier('signal')],\n t.blockStatement(\n // Everything in here is server-only, since the client\n // will strip out anything in the 'use server' directive.\n [\n t.returnStatement(\n t.callExpression(\n t.identifier(`${existingVariableName}.__executeServer`),\n [t.identifier('opts'), t.identifier('signal')],\n ),\n ),\n ],\n [t.directive(t.directiveLiteral('use server'))],\n ),\n ),\n )\n\n if (opts.env === 'server') {\n callExpressionPaths.handler.node.arguments.push(handlerFn)\n }\n}\n\nexport function handleCreateMiddlewareCallExpression(\n path: babel.NodePath<t.CallExpression>,\n opts: CompileOptions,\n) {\n const rootCallExpression = getRootCallExpression(path)\n\n // if (debug)\n // console.info(\n // 'Handling createMiddleware call expression:',\n // rootCallExpression.toString(),\n // )\n\n const callExpressionPaths = {\n middleware: null as babel.NodePath<t.CallExpression> | null,\n validator: null as babel.NodePath<t.CallExpression> | null,\n client: null as babel.NodePath<t.CallExpression> | null,\n server: null as babel.NodePath<t.CallExpression> | null,\n }\n\n const validMethods = Object.keys(callExpressionPaths)\n\n rootCallExpression.traverse({\n MemberExpression(memberExpressionPath) {\n if (t.isIdentifier(memberExpressionPath.node.property)) {\n const name = memberExpressionPath.node.property\n .name as keyof typeof callExpressionPaths\n\n if (\n validMethods.includes(name) &&\n memberExpressionPath.parentPath.isCallExpression()\n ) {\n callExpressionPaths[name] = memberExpressionPath.parentPath\n }\n }\n },\n })\n\n if (callExpressionPaths.validator) {\n const innerInputExpression = callExpressionPaths.validator.node.arguments[0]\n\n if (!innerInputExpression) {\n throw new Error(\n 'createMiddleware().validator() must be called with a validator!',\n )\n }\n\n // If we're on the client, remove the validator call expression\n if (opts.env === 'client') {\n if (t.isMemberExpression(callExpressionPaths.validator.node.callee)) {\n callExpressionPaths.validator.replaceWith(\n callExpressionPaths.validator.node.callee.object,\n )\n }\n }\n }\n\n const serverFnPath = callExpressionPaths.server?.get(\n 'arguments.0',\n ) as babel.NodePath<any>\n\n if (\n callExpressionPaths.server &&\n serverFnPath.node &&\n opts.env === 'client'\n ) {\n // If we're on the client, remove the server call expression\n if (t.isMemberExpression(callExpressionPaths.server.node.callee)) {\n callExpressionPaths.server.replaceWith(\n callExpressionPaths.server.node.callee.object,\n )\n }\n }\n}\n\nfunction buildEnvOnlyCallExpressionHandler(env: 'client' | 'server') {\n return function envOnlyCallExpressionHandler(\n path: babel.NodePath<t.CallExpression>,\n opts: CompileOptions,\n ) {\n // if (debug)\n // console.info(`Handling ${env}Only call expression:`, path.toString())\n\n const isEnvMatch =\n env === 'client' ? opts.env === 'client' : opts.env === 'server'\n\n if (isEnvMatch) {\n // extract the inner function from the call expression\n const innerInputExpression = path.node.arguments[0]\n\n if (!t.isExpression(innerInputExpression)) {\n throw new Error(\n `${env}Only() functions must be called with a function!`,\n )\n }\n\n path.replaceWith(innerInputExpression)\n return\n }\n\n // If we're on the wrong environment, replace the call expression\n // with a function that always throws an error.\n path.replaceWith(\n t.arrowFunctionExpression(\n [],\n t.blockStatement([\n t.throwStatement(\n t.newExpression(t.identifier('Error'), [\n t.stringLiteral(\n `${env}Only() functions can only be called on the ${env}!`,\n ),\n ]),\n ),\n ]),\n ),\n )\n }\n}\n\nexport function handleCreateIsomorphicFnCallExpression(\n path: babel.NodePath<t.CallExpression>,\n opts: CompileOptions,\n) {\n const rootCallExpression = getRootCallExpression(path)\n\n // if (debug)\n // console.info(\n // 'Handling createIsomorphicFn call expression:',\n // rootCallExpression.toString(),\n // )\n\n const callExpressionPaths = {\n client: null as babel.NodePath<t.CallExpression> | null,\n server: null as babel.NodePath<t.CallExpression> | null,\n }\n\n const validMethods = Object.keys(callExpressionPaths)\n\n rootCallExpression.traverse({\n MemberExpression(memberExpressionPath) {\n if (t.isIdentifier(memberExpressionPath.node.property)) {\n const name = memberExpressionPath.node.property\n .name as keyof typeof callExpressionPaths\n\n if (\n validMethods.includes(name) &&\n memberExpressionPath.parentPath.isCallExpression()\n ) {\n callExpressionPaths[name] = memberExpressionPath.parentPath\n }\n }\n },\n })\n\n if (\n validMethods.every(\n (method) =>\n !callExpressionPaths[method as keyof typeof callExpressionPaths],\n )\n ) {\n const variableId = rootCallExpression.parentPath.isVariableDeclarator()\n ? rootCallExpression.parentPath.node.id\n : null\n console.warn(\n 'createIsomorphicFn called without a client or server implementation!',\n 'This will result in a no-op function.',\n 'Variable name:',\n t.isIdentifier(variableId) ? variableId.name : 'unknown',\n )\n }\n\n const envCallExpression = callExpressionPaths[opts.env]\n\n if (!envCallExpression) {\n // if we don't have an implementation for this environment, default to a no-op\n rootCallExpression.replaceWith(\n t.arrowFunctionExpression([], t.blockStatement([])),\n )\n return\n }\n\n const innerInputExpression = envCallExpression.node.arguments[0]\n\n if (!t.isExpression(innerInputExpression)) {\n throw new Error(\n `createIsomorphicFn().${opts.env}(func) must be called with a function!`,\n )\n }\n\n rootCallExpression.replaceWith(innerInputExpression)\n}\n\nexport function getRootCallExpression(path: babel.NodePath<t.CallExpression>) {\n // Find the highest callExpression parent\n let rootCallExpression: babel.NodePath<t.CallExpression> = path\n\n // Traverse up the chain of CallExpressions\n while (rootCallExpression.parentPath.isMemberExpression()) {\n const parent = rootCallExpression.parentPath\n if (parent.parentPath.isCallExpression()) {\n rootCallExpression = parent.parentPath\n }\n }\n\n return rootCallExpression\n}\n\nfunction codeFrameError(\n code: string,\n loc: {\n start: { line: number; column: number }\n end: { line: number; column: number }\n },\n message: string,\n) {\n const frame = codeFrameColumns(\n code,\n {\n start: loc.start,\n end: loc.end,\n },\n {\n highlightCode: true,\n message,\n },\n )\n\n return new Error(frame)\n}\n"],"names":["parseAst","findReferencedIdentifiers","babel","t","deadCodeElimination","generateFromAst","codeFrameColumns"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAaO,SAAS,0BACd,WACA;AACO,SAAA,SAAS,mBAAmB,MAAuC;AAClE,UAAA,MAAMA,qBAAS,IAAI;AAEnB,UAAA,QAAQ,KAAK,OAAO;AAE1B,UAAM,YAAY,QAAQC,mDAA0B,GAAG,IAAI;AAE3DC,qBAAM,SAAS,KAAK;AAAA,MAClB,SAAS;AAAA,QACP,MAAM,aAAa;AACjB,gBAAM,cASF;AAAA,YACF,uBAAuB;AAAA,cACrB,MAAM;AAAA,cACN,sBACE;AAAA,gBACE;AAAA,gBACA;AAAA,cACF;AAAA,cACF,OAAO,CAAA;AAAA,YACT;AAAA,YACA,mBAAmB;AAAA,cACjB,MAAM;AAAA,cACN,sBACE;AAAA,gBACE;AAAA,gBACA;AAAA,cACF;AAAA,cACF,OAAO,CAAA;AAAA,YACT;AAAA,YACA,uBAAuB;AAAA,cACrB,MAAM;AAAA,cACN,sBACE;AAAA,gBACE;AAAA,gBACA;AAAA,cACF;AAAA,cACF,OAAO,CAAA;AAAA,YACT;AAAA,YACA,gBAAgB;AAAA,cACd,MAAM;AAAA,cACN,sBAAsB;AAAA,cACtB,OAAO,CAAA;AAAA,YACT;AAAA,YACA,kBAAkB;AAAA,cAChB,MAAM;AAAA,cACN,sBAAsB;AAAA,cACtB,OAAO,CAAA;AAAA,YACT;AAAA,YACA,YAAY;AAAA,cACV,MAAM;AAAA,cACN,sBAAsB;AAAA,cACtB,OAAO,CAAA;AAAA,YACT;AAAA,YACA,YAAY;AAAA,cACV,MAAM;AAAA,cACN,sBAAsB;AAAA,cACtB,OAAO,CAAA;AAAA,YACT;AAAA,YACA,oBAAoB;AAAA,cAClB,MAAM;A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;AAAA,EAAA,GAEnE;AACM,UAAA,aAAa,mBAAmB,WAAW,qBAAA,IAC7C,mBAAmB,WAAW,KAAK,KACnC;AACI,YAAA;AAAA,MACN;AAAA,MACA;AAAA,MACA;AAAA,MACAA,aAAE,aAAa,UAAU,IAAI,WAAW,OAAO;AAAA,IACjD;AAAA,EAAA;AAGI,QAAA,oBAAoB,oBAAoB,KAAK,GAAG;AAEtD,MAAI,CAAC,mBAAmB;AAEH,uBAAA;AAAA,MACjBA,aAAE,wBAAwB,CAAA,GAAIA,aAAE,eAAe,CAAA,CAAE,CAAC;AAAA,IACpD;AACA;AAAA,EAAA;AAGF,QAAM,uBAAuB,kBAAkB,KAAK,UAAU,CAAC;AAE/D,MAAI,CAACA,aAAE,aAAa,oBAAoB,GAAG;AACzC,UAAM,IAAI;AAAA,MACR,wBAAwB,KAAK,GAAG;AAAA,IAClC;AAAA,EAAA;AAGF,qBAAmB,YAAY,oBAAoB;AACrD;AAEO,SAAS,sBAAsB,MAAwC;AAE5E,MAAI,qBAAuD;AAGpD,SAAA,mBAAmB,WAAW,sBAAsB;AACzD,UAAM,SAAS,mBAAmB;AAC9B,QAAA,OAAO,WAAW,oBAAoB;AACxC,2BAAqB,OAAO;AAAA,IAAA;AAAA,EAC9B;AAGK,SAAA;AACT;AAEA,SAAS,eACP,MACA,KAIA,SACA;AACA,QAAM,QAAQG,UAAA;AAAA,IACZ;AAAA,IACA;AAAA,MACE,OAAO,IAAI;AAAA,MACX,KAAK,IAAI;AAAA,IACX;AAAA,IACA;AAAA,MACE,eAAe;AAAA,MACf;AAAA,IAAA;AAAA,EAEJ;AAEO,SAAA,IAAI,MAAM,KAAK;AACxB;;;;;;;;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"debug.cjs","sources":["../../src/debug.ts"],"sourcesContent":["export const debug =\n process.env.TSR_VITE_DEBUG &&\n ['true', 'start-plugin-core'].includes(process.env.TSR_VITE_DEBUG)\n"],"names":[],"mappings":";;AAAa,MAAA,QACX,QAAQ,IAAI,kBACZ,CAAC,QAAQ,mBAAmB,EAAE,SAAS,QAAQ,IAAI,cAAc;;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const debug: boolean | "" | undefined;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
-
const
|
|
3
|
+
const node_fs = require("node:fs");
|
|
4
4
|
const path = require("node:path");
|
|
5
5
|
const xmlbuilder2 = require("xmlbuilder2");
|
|
6
6
|
const utils = require("../utils.cjs");
|
|
@@ -107,9 +107,9 @@ function buildSitemap({
|
|
|
107
107
|
const pagesOutputPath = path.join(publicDir, "pages.json");
|
|
108
108
|
try {
|
|
109
109
|
logger.info(`Writing sitemap XML at ${xmlOutputPath}`);
|
|
110
|
-
|
|
110
|
+
node_fs.writeFileSync(xmlOutputPath, jsonToXml(sitemapData));
|
|
111
111
|
logger.info(`Writing pages data at ${pagesOutputPath}`);
|
|
112
|
-
|
|
112
|
+
node_fs.writeFileSync(
|
|
113
113
|
pagesOutputPath,
|
|
114
114
|
JSON.stringify(
|
|
115
115
|
{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-sitemap.cjs","sources":["../../../src/nitro-plugin/build-sitemap.ts"],"sourcesContent":["import { writeFileSync } from 'node:fs'\nimport path from 'node:path'\nimport { create } from 'xmlbuilder2'\nimport { createLogger } from '../utils'\nimport type { TanStackStartOutputConfig } from '../plugin'\nimport type { XMLBuilder } from 'xmlbuilder2/lib/interfaces'\n\nexport type SitemapUrl = {\n loc: string\n lastmod: string\n priority?: number\n changefreq?:\n | 'always'\n | 'hourly'\n | 'daily'\n | 'weekly'\n | 'monthly'\n | 'yearly'\n | 'never'\n alternateRefs?: Array<{\n href: string\n hreflang?: string\n }>\n images?: Array<{\n loc: string\n title?: string\n caption?: string\n }>\n news?: {\n publication: {\n name: string\n language: string\n }\n publicationDate: string | Date\n title: string\n }\n}\n\nexport type SitemapData = {\n urls: Array<SitemapUrl>\n}\n\nfunction buildSitemapJson(\n pages: TanStackStartOutputConfig['pages'],\n host: string,\n): SitemapData {\n const slash = checkSlash(host)\n\n const urls: Array<SitemapUrl> = pages\n .filter((page) => {\n return page.sitemap?.exclude !== true\n })\n .map((page) => ({\n loc: `${host}${slash}${page.path.replace(/^\\/+/g, '')}`,\n lastmod: page.sitemap?.lastmod\n ? new Date(page.sitemap.lastmod).toISOString().split('T')[0]!\n : new Date().toISOString().split('T')[0]!,\n priority: page.sitemap?.priority,\n changefreq: page.sitemap?.changefreq,\n alternateRefs: page.sitemap?.alternateRefs,\n images: page.sitemap?.images,\n news: page.sitemap?.news,\n }))\n\n return { urls }\n}\n\nfunction jsonToXml(sitemapData: SitemapData): string {\n const sitemap = createXml('urlset')\n\n for (const item of sitemapData.urls) {\n const page = sitemap.ele('url')\n page.ele('loc').txt(item.loc)\n page.ele('lastmod').txt(item.lastmod)\n\n if (item.priority !== undefined) {\n page.ele('priority').txt(item.priority.toString())\n }\n if (item.changefreq) {\n page.ele('changefreq').txt(item.changefreq)\n }\n\n // Add alternate references\n if (item.alternateRefs?.length) {\n for (const ref of item.alternateRefs) {\n const alternateRef = page.ele('xhtml:link')\n alternateRef.att('rel', 'alternate')\n alternateRef.att('href', ref.href)\n if (ref.hreflang) {\n alternateRef.att('hreflang', ref.hreflang)\n }\n }\n }\n\n // Add images\n if (item.images?.length) {\n for (const image of item.images) {\n const imageElement = page.ele('image:image')\n imageElement.ele('image:loc').txt(image.loc)\n if (image.title) {\n imageElement.ele('image:title').txt(image.title)\n }\n if (image.caption) {\n imageElement.ele('image:caption').txt(image.caption)\n }\n }\n }\n\n // Add news\n if (item.news) {\n const newsElement = page.ele('news:news')\n const publication = newsElement.ele('news:publication')\n publication.ele('news:name').txt(item.news.publication.name)\n publication.ele('news:language').txt(item.news.publication.language)\n newsElement\n .ele('news:publication_date')\n .txt(new Date(item.news.publicationDate).toISOString().split('T')[0]!)\n newsElement.ele('news:title').txt(item.news.title)\n }\n }\n\n return sitemap.end({ prettyPrint: true })\n}\n\nexport function buildSitemap({\n options,\n publicDir,\n}: {\n options: TanStackStartOutputConfig\n publicDir: string\n}) {\n const logger = createLogger('sitemap')\n\n let sitemapOptions = options.sitemap\n\n if (!sitemapOptions && options.pages.length) {\n sitemapOptions = { enabled: true, outputPath: 'sitemap.xml' }\n }\n\n if (!sitemapOptions?.enabled) {\n throw new Error('Sitemap is not enabled')\n }\n\n const { host, outputPath } = sitemapOptions\n\n if (!host) {\n if (!options.sitemap) {\n logger.info(\n 'Hint: Pages found, but no sitemap host has been set. To enable sitemap generation, set the `sitemap.host` option.',\n )\n return\n }\n throw new Error(\n 'Sitemap host is not set and required to build the sitemap.',\n )\n }\n\n if (!outputPath) {\n throw new Error('Sitemap output path is not set')\n }\n\n const { pages } = options\n\n if (!pages.length) {\n logger.info('No pages were found to build the sitemap. Skipping...')\n return\n }\n\n logger.info('Building Sitemap...')\n\n // Build the sitemap data\n const sitemapData = buildSitemapJson(pages, host)\n\n // Generate output paths\n const xmlOutputPath = path.join(publicDir, outputPath)\n const pagesOutputPath = path.join(publicDir, 'pages.json')\n\n try {\n // Write XML sitemap\n logger.info(`Writing sitemap XML at ${xmlOutputPath}`)\n writeFileSync(xmlOutputPath, jsonToXml(sitemapData))\n\n // Write pages data for runtime use\n logger.info(`Writing pages data at ${pagesOutputPath}`)\n writeFileSync(\n pagesOutputPath,\n JSON.stringify(\n {\n pages,\n host,\n lastBuilt: new Date().toISOString(),\n },\n null,\n 2,\n ),\n )\n } catch (e) {\n logger.error(`Unable to write sitemap files`, e)\n }\n}\n\nfunction createXml(elementName: 'urlset' | 'sitemapindex'): XMLBuilder {\n return create({ version: '1.0', encoding: 'UTF-8' })\n .ele(elementName, {\n xmlns: 'https://www.sitemaps.org/schemas/sitemap/0.9',\n })\n .com(`This file was automatically generated by TanStack Start.`)\n}\n\nfunction checkSlash(host: string): string {\n const finalChar = host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EAAE,SAAS,MAAM,YAAY,cAAc;AAAA,EAAA;AAG1D,MAAA,EAAC,iDAAgB,UAAS;AACtB,UAAA,IAAI,MAAM,wBAAwB;AAAA,EAAA;AAGpC,QAAA,EAAE,MAAM,WAAA,IAAe;AAE7B,MAAI,CAAC,MAAM;AACL,QAAA,CAAC,QAAQ,SAAS;AACb,aAAA;AAAA,QACL;AAAA,MACF;AACA;AAAA,IAAA;AAEF,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EAAA;AAGF,MAAI,CAAC,YAAY;AACT,UAAA,IAAI,MAAM,gCAAgC;AAAA,EAAA;AAG5C,QAAA,EAAE,UAAU;AAEd,MAAA,CAAC,MAAM,QAAQ;AACjB,WAAO,KAAK,uDAAuD;AACnE;AAAA,EAAA;AAGF,SAAO,KAAK,qBAAqB;AAG3B,QAAA,cAAc,iBAAiB,OAAO,IAAI;AAGhD,QAAM,gBAAgB,KAAK,KAAK,WAAW,UAAU;AACrD,QAAM,kBAAkB,KAAK,KAAK,WAAW,YAAY;AAErD,MAAA;AAEK,WAAA,KAAK,0BAA0B,aAAa,EAAE;AACvCC,
|
|
1
|
+
{"version":3,"file":"build-sitemap.cjs","sources":["../../../src/nitro-plugin/build-sitemap.ts"],"sourcesContent":["import { writeFileSync } from 'node:fs'\nimport path from 'node:path'\nimport { create } from 'xmlbuilder2'\nimport { createLogger } from '../utils'\nimport type { TanStackStartOutputConfig } from '../plugin'\nimport type { XMLBuilder } from 'xmlbuilder2/lib/interfaces'\n\nexport type SitemapUrl = {\n loc: string\n lastmod: string\n priority?: number\n changefreq?:\n | 'always'\n | 'hourly'\n | 'daily'\n | 'weekly'\n | 'monthly'\n | 'yearly'\n | 'never'\n alternateRefs?: Array<{\n href: string\n hreflang?: string\n }>\n images?: Array<{\n loc: string\n title?: string\n caption?: string\n }>\n news?: {\n publication: {\n name: string\n language: string\n }\n publicationDate: string | Date\n title: string\n }\n}\n\nexport type SitemapData = {\n urls: Array<SitemapUrl>\n}\n\nfunction buildSitemapJson(\n pages: TanStackStartOutputConfig['pages'],\n host: string,\n): SitemapData {\n const slash = checkSlash(host)\n\n const urls: Array<SitemapUrl> = pages\n .filter((page) => {\n return page.sitemap?.exclude !== true\n })\n .map((page) => ({\n loc: `${host}${slash}${page.path.replace(/^\\/+/g, '')}`,\n lastmod: page.sitemap?.lastmod\n ? new Date(page.sitemap.lastmod).toISOString().split('T')[0]!\n : new Date().toISOString().split('T')[0]!,\n priority: page.sitemap?.priority,\n changefreq: page.sitemap?.changefreq,\n alternateRefs: page.sitemap?.alternateRefs,\n images: page.sitemap?.images,\n news: page.sitemap?.news,\n }))\n\n return { urls }\n}\n\nfunction jsonToXml(sitemapData: SitemapData): string {\n const sitemap = createXml('urlset')\n\n for (const item of sitemapData.urls) {\n const page = sitemap.ele('url')\n page.ele('loc').txt(item.loc)\n page.ele('lastmod').txt(item.lastmod)\n\n if (item.priority !== undefined) {\n page.ele('priority').txt(item.priority.toString())\n }\n if (item.changefreq) {\n page.ele('changefreq').txt(item.changefreq)\n }\n\n // Add alternate references\n if (item.alternateRefs?.length) {\n for (const ref of item.alternateRefs) {\n const alternateRef = page.ele('xhtml:link')\n alternateRef.att('rel', 'alternate')\n alternateRef.att('href', ref.href)\n if (ref.hreflang) {\n alternateRef.att('hreflang', ref.hreflang)\n }\n }\n }\n\n // Add images\n if (item.images?.length) {\n for (const image of item.images) {\n const imageElement = page.ele('image:image')\n imageElement.ele('image:loc').txt(image.loc)\n if (image.title) {\n imageElement.ele('image:title').txt(image.title)\n }\n if (image.caption) {\n imageElement.ele('image:caption').txt(image.caption)\n }\n }\n }\n\n // Add news\n if (item.news) {\n const newsElement = page.ele('news:news')\n const publication = newsElement.ele('news:publication')\n publication.ele('news:name').txt(item.news.publication.name)\n publication.ele('news:language').txt(item.news.publication.language)\n newsElement\n .ele('news:publication_date')\n .txt(new Date(item.news.publicationDate).toISOString().split('T')[0]!)\n newsElement.ele('news:title').txt(item.news.title)\n }\n }\n\n return sitemap.end({ prettyPrint: true })\n}\n\nexport function buildSitemap({\n options,\n publicDir,\n}: {\n options: TanStackStartOutputConfig\n publicDir: string\n}) {\n const logger = createLogger('sitemap')\n\n let sitemapOptions = options.sitemap\n\n if (!sitemapOptions && options.pages.length) {\n sitemapOptions = { enabled: true, outputPath: 'sitemap.xml' }\n }\n\n if (!sitemapOptions?.enabled) {\n throw new Error('Sitemap is not enabled')\n }\n\n const { host, outputPath } = sitemapOptions\n\n if (!host) {\n if (!options.sitemap) {\n logger.info(\n 'Hint: Pages found, but no sitemap host has been set. To enable sitemap generation, set the `sitemap.host` option.',\n )\n return\n }\n throw new Error(\n 'Sitemap host is not set and required to build the sitemap.',\n )\n }\n\n if (!outputPath) {\n throw new Error('Sitemap output path is not set')\n }\n\n const { pages } = options\n\n if (!pages.length) {\n logger.info('No pages were found to build the sitemap. Skipping...')\n return\n }\n\n logger.info('Building Sitemap...')\n\n // Build the sitemap data\n const sitemapData = buildSitemapJson(pages, host)\n\n // Generate output paths\n const xmlOutputPath = path.join(publicDir, outputPath)\n const pagesOutputPath = path.join(publicDir, 'pages.json')\n\n try {\n // Write XML sitemap\n logger.info(`Writing sitemap XML at ${xmlOutputPath}`)\n writeFileSync(xmlOutputPath, jsonToXml(sitemapData))\n\n // Write pages data for runtime use\n logger.info(`Writing pages data at ${pagesOutputPath}`)\n writeFileSync(\n pagesOutputPath,\n JSON.stringify(\n {\n pages,\n host,\n lastBuilt: new Date().toISOString(),\n },\n null,\n 2,\n ),\n )\n } catch (e) {\n logger.error(`Unable to write sitemap files`, e)\n }\n}\n\nfunction createXml(elementName: 'urlset' | 'sitemapindex'): XMLBuilder {\n return create({ version: '1.0', encoding: 'UTF-8' })\n .ele(elementName, {\n xmlns: 'https://www.sitemaps.org/schemas/sitemap/0.9',\n })\n .com(`This file was automatically generated by TanStack Start.`)\n}\n\nfunction checkSlash(host: string): string {\n const finalChar = host.slice(-1)\n return finalChar === '/' ? '' : '/'\n}\n"],"names":["createLogger","writeFileSync","create"],"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7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
3
|
const path = require("node:path");
|
|
4
|
-
const
|
|
4
|
+
const node_fs = require("node:fs");
|
|
5
5
|
const nitropack = require("nitropack");
|
|
6
6
|
const pathe = require("pathe");
|
|
7
7
|
const constants = require("../constants.cjs");
|
|
@@ -43,7 +43,7 @@ function nitroPlugin(options, getSsrBundle) {
|
|
|
43
43
|
throw new Error("SSR environment not found");
|
|
44
44
|
}
|
|
45
45
|
const clientOutputDir = pathe.resolve(options.root, constants.CLIENT_DIST_DIR);
|
|
46
|
-
|
|
46
|
+
node_fs.rmSync(clientOutputDir, { recursive: true, force: true });
|
|
47
47
|
await builder.build(client);
|
|
48
48
|
await builder.build(server);
|
|
49
49
|
const nitroConfig = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.cjs","sources":["../../../src/nitro-plugin/plugin.ts"],"sourcesContent":["import path from 'node:path'\nimport { rmSync } from 'node:fs'\nimport { build, copyPublicAssets, createNitro, prepare } from 'nitropack'\nimport { dirname, resolve } from 'pathe'\nimport {\n CLIENT_DIST_DIR,\n SSR_ENTRY_FILE,\n VITE_ENVIRONMENT_NAMES,\n} from '../constants'\nimport { buildSitemap } from './build-sitemap'\nimport { prerender } from './prerender'\nimport type {\n EnvironmentOptions,\n PluginOption,\n Rollup,\n ViteBuilder,\n} from 'vite'\nimport type { Nitro, NitroConfig } from 'nitropack'\nimport type { TanStackStartOutputConfig } from '../plugin'\n\nexport function nitroPlugin(\n options: TanStackStartOutputConfig,\n getSsrBundle: () => Rollup.OutputBundle,\n): Array<PluginOption> {\n const buildPreset =\n process.env['START_TARGET'] ?? (options.target as string | undefined)\n return [\n {\n name: 'tanstack-vite-plugin-nitro',\n configEnvironment(name) {\n if (name === VITE_ENVIRONMENT_NAMES.server) {\n return {\n build: {\n commonjsOptions: {\n include: [],\n },\n ssr: true,\n sourcemap: true,\n rollupOptions: {\n input: '/~start/server-entry',\n },\n },\n } satisfies EnvironmentOptions\n }\n\n return null\n },\n config() {\n return {\n builder: {\n sharedPlugins: true,\n async buildApp(builder) {\n const client = builder.environments[VITE_ENVIRONMENT_NAMES.client]\n const server = builder.environments[VITE_ENVIRONMENT_NAMES.server]\n\n if (!client) {\n throw new Error('Client environment not found')\n }\n\n if (!server) {\n throw new Error('SSR environment not found')\n }\n\n // Build the client bundle\n // i.e client entry file with `hydrateRoot(...)`\n const clientOutputDir = resolve(options.root, CLIENT_DIST_DIR)\n rmSync(clientOutputDir, { recursive: true, force: true })\n await builder.build(client)\n\n // Build the SSR bundle\n await builder.build(server)\n\n const nitroConfig: NitroConfig = {\n dev: false,\n // TODO: do we need this? should this be made configurable?\n compatibilityDate: '2024-11-19',\n logLevel: 3,\n preset: buildPreset,\n baseURL: globalThis.TSS_APP_BASE,\n publicAssets: [\n {\n dir: path.resolve(options.root, CLIENT_DIST_DIR),\n baseURL: '/',\n maxAge: 31536000, // 1 year\n },\n ],\n typescript: {\n generateTsConfig: false,\n },\n prerender: undefined,\n renderer: SSR_ENTRY_FILE,\n plugins: [], // Nitro's plugins\n appConfigFiles: [],\n scanDirs: [],\n imports: false, // unjs/unimport for global/magic imports\n rollupConfig: {\n plugins: [virtualBundlePlugin(getSsrBundle())],\n },\n virtual: {\n // This is Nitro's way of defining virtual modules\n // Should we define the ones for TanStack Start's here as well?\n },\n }\n\n const nitro = await createNitro(nitroConfig)\n\n await buildNitroApp(builder, nitro, options)\n },\n },\n }\n },\n },\n ]\n}\n\n/**\n * Correctly co-ordinates the nitro app build process to make sure that the\n * app is built, while also correctly handling the prerendering and sitemap\n * generation and including their outputs in the final build.\n */\nasync function buildNitroApp(\n builder: ViteBuilder,\n nitro: Nitro,\n options: TanStackStartOutputConfig,\n) {\n // Cleans the public and server directories for a fresh build\n // i.e the `.output/public` and `.output/server` directories\n await prepare(nitro)\n\n // Creates the `.output/public` directory and copies the public assets\n await copyPublicAssets(nitro)\n\n // If the user has not set a prerender option, we need to set it to true\n // if the pages array is not empty and has sub options requiring for prerendering\n if (options.prerender?.enabled !== false) {\n options.prerender = {\n ...options.prerender,\n enabled: options.pages.some((d) =>\n typeof d === 'string' ? false : !!d.prerender?.enabled,\n ),\n }\n }\n\n // Setup the options for prerendering the SPA shell (i.e `src/routes/__root.tsx`)\n if (options.spa?.enabled) {\n options.prerender = {\n ...options.prerender,\n enabled: true,\n }\n\n const maskUrl = new URL(options.spa.maskPath, 'http://localhost')\n\n maskUrl.searchParams.set('__TSS_SHELL', 'true')\n\n options.pages.push({\n path: maskUrl.toString().replace('http://localhost', ''),\n prerender: options.spa.prerender,\n sitemap: {\n exclude: true,\n },\n })\n }\n\n // Run the prerendering process\n if (options.prerender.enabled) {\n await prerender({\n options,\n nitro,\n builder,\n })\n }\n\n // Run the sitemap build process\n if (options.pages.length) {\n buildSitemap({\n options,\n publicDir: nitro.options.output.publicDir,\n })\n }\n\n // Build the nitro app\n // We only build the nitro app, once we've prepared the public assets,\n // prerendered the pages and built the sitemap.\n // If we try to do this earlier, then the public assets may not be available\n // in the production build.\n await build(nitro)\n\n // Close the nitro instance\n await nitro.close()\n nitro.logger.success(\n 'Client and Server bundles for TanStack Start have been successfully built.',\n )\n}\n\ntype NitroRollupPluginOption = NonNullable<\n NitroConfig['rollupConfig']\n>['plugins']\n\nfunction virtualBundlePlugin(\n ssrBundle: Rollup.OutputBundle,\n): NitroRollupPluginOption {\n type VirtualModule = { code: string; map: string | null }\n const _modules = new Map<string, VirtualModule>()\n\n // group chunks and source maps\n for (const [fileName, content] of Object.entries(ssrBundle)) {\n if (content.type === 'chunk') {\n const virtualModule: VirtualModule = {\n code: content.code,\n map: null,\n }\n const maybeMap = ssrBundle[`${fileName}.map`]\n if (maybeMap && maybeMap.type === 'asset') {\n virtualModule.map = maybeMap.source as string\n }\n _modules.set(fileName, virtualModule)\n _modules.set(resolve(fileName), virtualModule)\n }\n }\n\n return {\n name: 'virtual-bundle',\n resolveId(id, importer) {\n if (_modules.has(id)) {\n return resolve(id)\n }\n\n if (importer) {\n const resolved = resolve(dirname(importer), id)\n if (_modules.has(resolved)) {\n return resolved\n }\n }\n return null\n },\n load(id) {\n const m = _modules.get(id)\n if (!m) {\n return null\n }\n return m\n },\n }\n}\n"],"names":["VITE_ENVIRONMENT_NAMES","resolve","CLIENT_DIST_DIR","rmSync","SSR_ENTRY_FILE","createNitro","prepare","copyPublicAssets","_a","prerender","buildSitemap","build","dirname"],"mappings":";;;;;;;;;AAoBgB,SAAA,YACd,SACA,cACqB;AACrB,QAAM,cACJ,QAAQ,IAAI,cAAc,KAAM,QAAQ;AACnC,SAAA;AAAA,IACL;AAAA,MACE,MAAM;AAAA,MACN,kBAAkB,MAAM;AAClB,YAAA,SAASA,iCAAuB,QAAQ;AACnC,iBAAA;AAAA,YACL,OAAO;AAAA,cACL,iBAAiB;AAAA,gBACf,SAAS,CAAA;AAAA,cACX;AAAA,cACA,KAAK;AAAA,cACL,WAAW;AAAA,cACX,eAAe;AAAA,gBACb,OAAO;AAAA,cAAA;AAAA,YACT;AAAA,UAEJ;AAAA,QAAA;AAGK,eAAA;AAAA,MACT;AAAA,MACA,SAAS;AACA,eAAA;AAAA,UACL,SAAS;AAAA,YACP,eAAe;AAAA,YACf,MAAM,SAAS,SAAS;AACtB,oBAAM,SAAS,QAAQ,aAAaA,UAAAA,uBAAuB,MAAM;AACjE,oBAAM,SAAS,QAAQ,aAAaA,UAAAA,uBAAuB,MAAM;AAEjE,kBAAI,CAAC,QAAQ;AACL,sBAAA,IAAI,MAAM,8BAA8B;AAAA,cAAA;AAGhD,kBAAI,CAAC,QAAQ;AACL,sBAAA,IAAI,MAAM,2BAA2B;AAAA,cAAA;AAK7C,oBAAM,kBAAkBC,MAAA,QAAQ,QAAQ,MAAMC,UAAAA,eAAe;AAC7DC,iBAAA,OAAO,iBAAiB,EAAE,WAAW,MAAM,OAAO,MAAM;AAClD,oBAAA,QAAQ,MAAM,MAAM;AAGpB,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;AACpB,eAAOA,MAAAA,QAAQ,EAAE;AAAA,MAAA;AAGnB,UAAI,UAAU;AACZ,cAAM,WAAWA,MAAA,QAAQW,MAAQ,QAAA,QAAQ,GAAG,EAAE;AAC1C,YAAA,SAAS,IAAI,QAAQ,GAAG;AACnB,iBAAA;AAAA,QAAA;AAAA,MACT;AAEK,aAAA;AAAA,IACT;AAAA,IACA,KAAK,IAAI;AACD,YAAA,IAAI,SAAS,IAAI,EAAE;AACzB,UAAI,CAAC,GAAG;AACC,eAAA;AAAA,MAAA;AAEF,aAAA;AAAA,IAAA;AAAA,EAEX;AACF;;"}
|
|
1
|
+
{"version":3,"file":"plugin.cjs","sources":["../../../src/nitro-plugin/plugin.ts"],"sourcesContent":["import path from 'node:path'\nimport { rmSync } from 'node:fs'\nimport { build, copyPublicAssets, createNitro, prepare } from 'nitropack'\nimport { dirname, resolve } from 'pathe'\nimport {\n CLIENT_DIST_DIR,\n SSR_ENTRY_FILE,\n VITE_ENVIRONMENT_NAMES,\n} from '../constants'\nimport { buildSitemap } from './build-sitemap'\nimport { prerender } from './prerender'\nimport type {\n EnvironmentOptions,\n PluginOption,\n Rollup,\n ViteBuilder,\n} from 'vite'\nimport type { Nitro, NitroConfig } from 'nitropack'\nimport type { TanStackStartOutputConfig } from '../plugin'\n\nexport function nitroPlugin(\n options: TanStackStartOutputConfig,\n getSsrBundle: () => Rollup.OutputBundle,\n): Array<PluginOption> {\n const buildPreset =\n process.env['START_TARGET'] ?? (options.target as string | undefined)\n return [\n {\n name: 'tanstack-vite-plugin-nitro',\n configEnvironment(name) {\n if (name === VITE_ENVIRONMENT_NAMES.server) {\n return {\n build: {\n commonjsOptions: {\n include: [],\n },\n ssr: true,\n sourcemap: true,\n rollupOptions: {\n input: '/~start/server-entry',\n },\n },\n } satisfies EnvironmentOptions\n }\n\n return null\n },\n config() {\n return {\n builder: {\n sharedPlugins: true,\n async buildApp(builder) {\n const client = builder.environments[VITE_ENVIRONMENT_NAMES.client]\n const server = builder.environments[VITE_ENVIRONMENT_NAMES.server]\n\n if (!client) {\n throw new Error('Client environment not found')\n }\n\n if (!server) {\n throw new Error('SSR environment not found')\n }\n\n // Build the client bundle\n // i.e client entry file with `hydrateRoot(...)`\n const clientOutputDir = resolve(options.root, CLIENT_DIST_DIR)\n rmSync(clientOutputDir, { recursive: true, force: true })\n await builder.build(client)\n\n // Build the SSR bundle\n await builder.build(server)\n\n const nitroConfig: NitroConfig = {\n dev: false,\n // TODO: do we need this? should this be made configurable?\n compatibilityDate: '2024-11-19',\n logLevel: 3,\n preset: buildPreset,\n baseURL: globalThis.TSS_APP_BASE,\n publicAssets: [\n {\n dir: path.resolve(options.root, CLIENT_DIST_DIR),\n baseURL: '/',\n maxAge: 31536000, // 1 year\n },\n ],\n typescript: {\n generateTsConfig: false,\n },\n prerender: undefined,\n renderer: SSR_ENTRY_FILE,\n plugins: [], // Nitro's plugins\n appConfigFiles: [],\n scanDirs: [],\n imports: false, // unjs/unimport for global/magic imports\n rollupConfig: {\n plugins: [virtualBundlePlugin(getSsrBundle())],\n },\n virtual: {\n // This is Nitro's way of defining virtual modules\n // Should we define the ones for TanStack Start's here as well?\n },\n }\n\n const nitro = await createNitro(nitroConfig)\n\n await buildNitroApp(builder, nitro, options)\n },\n },\n }\n },\n },\n ]\n}\n\n/**\n * Correctly co-ordinates the nitro app build process to make sure that the\n * app is built, while also correctly handling the prerendering and sitemap\n * generation and including their outputs in the final build.\n */\nasync function buildNitroApp(\n builder: ViteBuilder,\n nitro: Nitro,\n options: TanStackStartOutputConfig,\n) {\n // Cleans the public and server directories for a fresh build\n // i.e the `.output/public` and `.output/server` directories\n await prepare(nitro)\n\n // Creates the `.output/public` directory and copies the public assets\n await copyPublicAssets(nitro)\n\n // If the user has not set a prerender option, we need to set it to true\n // if the pages array is not empty and has sub options requiring for prerendering\n if (options.prerender?.enabled !== false) {\n options.prerender = {\n ...options.prerender,\n enabled: options.pages.some((d) =>\n typeof d === 'string' ? false : !!d.prerender?.enabled,\n ),\n }\n }\n\n // Setup the options for prerendering the SPA shell (i.e `src/routes/__root.tsx`)\n if (options.spa?.enabled) {\n options.prerender = {\n ...options.prerender,\n enabled: true,\n }\n\n const maskUrl = new URL(options.spa.maskPath, 'http://localhost')\n\n maskUrl.searchParams.set('__TSS_SHELL', 'true')\n\n options.pages.push({\n path: maskUrl.toString().replace('http://localhost', ''),\n prerender: options.spa.prerender,\n sitemap: {\n exclude: true,\n },\n })\n }\n\n // Run the prerendering process\n if (options.prerender.enabled) {\n await prerender({\n options,\n nitro,\n builder,\n })\n }\n\n // Run the sitemap build process\n if (options.pages.length) {\n buildSitemap({\n options,\n publicDir: nitro.options.output.publicDir,\n })\n }\n\n // Build the nitro app\n // We only build the nitro app, once we've prepared the public assets,\n // prerendered the pages and built the sitemap.\n // If we try to do this earlier, then the public assets may not be available\n // in the production build.\n await build(nitro)\n\n // Close the nitro instance\n await nitro.close()\n nitro.logger.success(\n 'Client and Server bundles for TanStack Start have been successfully built.',\n )\n}\n\ntype NitroRollupPluginOption = NonNullable<\n NitroConfig['rollupConfig']\n>['plugins']\n\nfunction virtualBundlePlugin(\n ssrBundle: Rollup.OutputBundle,\n): NitroRollupPluginOption {\n type VirtualModule = { code: string; map: string | null }\n const _modules = new Map<string, VirtualModule>()\n\n // group chunks and source maps\n for (const [fileName, content] of Object.entries(ssrBundle)) {\n if (content.type === 'chunk') {\n const virtualModule: VirtualModule = {\n code: content.code,\n map: null,\n }\n const maybeMap = ssrBundle[`${fileName}.map`]\n if (maybeMap && maybeMap.type === 'asset') {\n virtualModule.map = maybeMap.source as string\n }\n _modules.set(fileName, virtualModule)\n _modules.set(resolve(fileName), virtualModule)\n }\n }\n\n return {\n name: 'virtual-bundle',\n resolveId(id, importer) {\n if (_modules.has(id)) {\n return resolve(id)\n }\n\n if (importer) {\n const resolved = resolve(dirname(importer), id)\n if (_modules.has(resolved)) {\n return resolved\n }\n }\n return null\n },\n load(id) {\n const m = _modules.get(id)\n if (!m) {\n return null\n }\n return m\n },\n }\n}\n"],"names":["VITE_ENVIRONMENT_NAMES","resolve","CLIENT_DIST_DIR","rmSync","SSR_ENTRY_FILE","createNitro","prepare","copyPublicAssets","_a","prerender","buildSitemap","build","dirname"],"mappings":";;;;;;;;;AAoBgB,SAAA,YACd,SACA,cACqB;AACrB,QAAM,cACJ,QAAQ,IAAI,cAAc,KAAM,QAAQ;AACnC,SAAA;AAAA,IACL;AAAA,MACE,MAAM;AAAA,MACN,kBAAkB,MAAM;AAClB,YAAA,SAASA,iCAAuB,QAAQ;AACnC,iBAAA;AAAA,YACL,OAAO;AAAA,cACL,iBAAiB;AAAA,gBACf,SAAS,CAAA;AAAA,cACX;AAAA,cACA,KAAK;AAAA,cACL,WAAW;AAAA,cACX,eAAe;AAAA,gBACb,OAAO;AAAA,cAAA;AAAA,YACT;AAAA,UAEJ;AAAA,QAAA;AAGK,eAAA;AAAA,MACT;AAAA,MACA,SAAS;AACA,eAAA;AAAA,UACL,SAAS;AAAA,YACP,eAAe;AAAA,YACf,MAAM,SAAS,SAAS;AACtB,oBAAM,SAAS,QAAQ,aAAaA,UAAAA,uBAAuB,MAAM;AACjE,oBAAM,SAAS,QAAQ,aAAaA,UAAAA,uBAAuB,MAAM;AAEjE,kBAAI,CAAC,QAAQ;AACL,sBAAA,IAAI,MAAM,8BAA8B;AAAA,cAAA;AAGhD,kBAAI,CAAC,QAAQ;AACL,sBAAA,IAAI,MAAM,2BAA2B;AAAA,cAAA;AAK7C,oBAAM,kBAAkBC,MAAA,QAAQ,QAAQ,MAAMC,UAAAA,eAAe;AAC7DC,sBAAA,OAAO,iBAAiB,EAAE,WAAW,MAAM,OAAO,MAAM;AAClD,oBAAA,QAAQ,MAAM,MAAM;AAGpB,oBAAA,QAAQ,MAAM,MAAM;AAE1B,oBAAM,cAA2B;AAAA,gBAC/B,KAAK;AAAA;AAAA,gBAEL,mBAAmB;AAAA,gBACnB,UAAU;AAAA,gBACV,QAAQ;AAAA,gBACR,SAAS,WAAW;AAAA,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AAG;AACnB,iBAAA;AAAA,QAAA;AAAA,MACT;AAEK,aAAA;AAAA,IACT;AAAA,IACA,KAAK,IAAI;AACD,YAAA,IAAI,SAAS,IAAI,EAAE;AACzB,UAAI,CAAC,GAAG;AACC,eAAA;AAAA,MAAA;AAEF,aAAA;AAAA,IAAA;AAAA,EAEX;AACF;;"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
-
const
|
|
3
|
+
const node_fs = require("node:fs");
|
|
4
4
|
const os = require("node:os");
|
|
5
5
|
const path = require("node:path");
|
|
6
6
|
const rollup = require("nitropack/rollup");
|
|
@@ -136,10 +136,10 @@ async function prerender({
|
|
|
136
136
|
);
|
|
137
137
|
const html = await res.text();
|
|
138
138
|
const filepath = path.join(nitro.options.output.publicDir, filename);
|
|
139
|
-
await
|
|
139
|
+
await node_fs.promises.mkdir(path.dirname(filepath), {
|
|
140
140
|
recursive: true
|
|
141
141
|
});
|
|
142
|
-
await
|
|
142
|
+
await node_fs.promises.writeFile(filepath, html);
|
|
143
143
|
const newPage = await ((_a4 = prerenderOptions.onSuccess) == null ? void 0 : _a4.call(prerenderOptions, { page, html }));
|
|
144
144
|
if (newPage) {
|
|
145
145
|
Object.assign(page, newPage);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prerender.cjs","sources":["../../../src/nitro-plugin/prerender.ts"],"sourcesContent":["import { promises as fsp } from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport { getRollupConfig } from 'nitropack/rollup'\nimport { build as buildNitro, createNitro } from 'nitropack'\nimport { joinURL, withBase, withoutBase } from 'ufo'\nimport { VITE_ENVIRONMENT_NAMES } from '../constants'\nimport { createLogger } from '../utils'\nimport { Queue } from './queue'\nimport type { ViteBuilder } from 'vite'\nimport type { $Fetch, Nitro } from 'nitropack'\nimport type { TanStackStartOutputConfig } from '../plugin'\nimport type { Page } from '../schema'\n\nexport async function prerender({\n options,\n nitro,\n builder,\n}: {\n options: TanStackStartOutputConfig\n nitro: Nitro\n builder: ViteBuilder\n}) {\n const logger = createLogger('prerender')\n logger.info('Prendering pages...')\n\n // If prerender is enabled but no pages are provided, default to prerendering the root page\n if (options.prerender?.enabled && !options.pages.length) {\n options.pages = [\n {\n path: '/',\n },\n ]\n }\n\n const serverEnv = builder.environments[VITE_ENVIRONMENT_NAMES.server]\n\n if (!serverEnv) {\n throw new Error(\n `Vite's \"${VITE_ENVIRONMENT_NAMES.server}\" environment not found`,\n )\n }\n\n const prerenderOutputDir = path.resolve(\n options.root,\n '.tanstack-start/build/prerenderer',\n )\n\n const nodeNitro = await createNitro({\n ...nitro.options._config,\n preset: 'nitro-prerender',\n logLevel: 0,\n output: {\n dir: prerenderOutputDir,\n serverDir: path.resolve(prerenderOutputDir, 'server'),\n publicDir: path.resolve(prerenderOutputDir, 'public'),\n },\n })\n\n const nodeNitroRollupOptions = getRollupConfig(nodeNitro)\n\n const build = serverEnv.config.build\n\n build.outDir = prerenderOutputDir\n\n build.rollupOptions = {\n ...build.rollupOptions,\n ...nodeNitroRollupOptions,\n output: {\n ...build.rollupOptions.output,\n ...nodeNitroRollupOptions.output,\n sourcemap: undefined,\n },\n }\n\n await buildNitro(nodeNitro)\n\n // Import renderer entry\n const serverFilename =\n typeof nodeNitroRollupOptions.output.entryFileNames === 'string'\n ? nodeNitroRollupOptions.output.entryFileNames\n : 'index.mjs'\n\n const serverEntrypoint = path.resolve(\n path.join(nodeNitro.options.output.serverDir, serverFilename),\n )\n\n const { closePrerenderer, localFetch } = (await import(serverEntrypoint)) as {\n closePrerenderer: () => void\n localFetch: $Fetch\n }\n\n try {\n // Crawl all pages\n const pages = await prerenderPages()\n\n logger.info(`Prerendered ${pages.length} pages:`)\n pages.forEach((page) => {\n logger.info(`- ${page}`)\n })\n\n // TODO: Write the prerendered pages to the output directory\n } catch (error) {\n logger.error(error)\n } finally {\n // Ensure server is always closed\n // server.process.kill()\n closePrerenderer()\n }\n\n function extractLinks(html: string): Array<string> {\n const linkRegex = /<a[^>]+href=[\"']([^\"']+)[\"'][^>]*>/g\n const links: Array<string> = []\n let match\n\n while ((match = linkRegex.exec(html)) !== null) {\n const href = match[1]\n if (href && (href.startsWith('/') || href.startsWith('./'))) {\n links.push(href)\n }\n }\n\n return links\n }\n\n async function prerenderPages() {\n const seen = new Set<string>()\n const retriesByPath = new Map<string, number>()\n const concurrency = options.prerender?.concurrency ?? os.cpus().length\n logger.info(`Concurrency: ${concurrency}`)\n const queue = new Queue({ concurrency })\n\n options.pages.forEach((page) => addCrawlPageTask(page))\n\n await queue.start()\n\n return Array.from(seen)\n\n function addCrawlPageTask(page: Page) {\n // Was the page already seen?\n if (seen.has(page.path)) return\n\n // Add the page to the seen set\n seen.add(page.path)\n\n if (page.fromCrawl) {\n options.pages.push(page)\n }\n\n // If not enabled, skip\n if (!(page.prerender?.enabled ?? true)) return\n\n // If there is a filter link, check if the page should be prerendered\n if (options.prerender?.filter && !options.prerender.filter(page)) return\n\n // Resolve the merged default and page-specific prerender options\n const prerenderOptions = {\n ...options.prerender,\n ...page.prerender,\n }\n\n // Add the task\n queue.add(async () => {\n logger.info(`Crawling: ${page.path}`)\n const retries = retriesByPath.get(page.path) || 0\n try {\n // Fetch the route\n const encodedRoute = encodeURI(page.path)\n\n const res = await localFetch<Response>(\n withBase(encodedRoute, nodeNitro.options.baseURL),\n {\n headers: { 'x-nitro-prerender': encodedRoute },\n },\n )\n\n if (!res.ok) {\n throw new Error(`Failed to fetch ${page.path}: ${res.statusText}`, {\n cause: res,\n })\n }\n\n const cleanPagePath = (\n prerenderOptions.outputPath || page.path\n ).split(/[?#]/)[0]!\n\n // Guess route type and populate fileName\n const contentType = res.headers.get('content-type') || ''\n const isImplicitHTML =\n !cleanPagePath.endsWith('.html') && contentType.includes('html')\n // &&\n // !JsonSigRx.test(dataBuff.subarray(0, 32).toString('utf8'))\n const routeWithIndex = cleanPagePath.endsWith('/')\n ? cleanPagePath + 'index'\n : cleanPagePath\n\n const htmlPath =\n cleanPagePath.endsWith('/') || prerenderOptions.autoSubfolderIndex\n ? joinURL(cleanPagePath, 'index.html')\n : cleanPagePath + '.html'\n\n const filename = withoutBase(\n isImplicitHTML ? htmlPath : routeWithIndex,\n nitro.options.baseURL,\n )\n\n const html = await res.text()\n\n const filepath = path.join(nitro.options.output.publicDir, filename)\n\n await fsp.mkdir(path.dirname(filepath), {\n recursive: true,\n })\n\n await fsp.writeFile(filepath, html)\n\n const newPage = await prerenderOptions.onSuccess?.({ page, html })\n\n if (newPage) {\n Object.assign(page, newPage)\n }\n\n // Find new links\n if (prerenderOptions.crawlLinks ?? true) {\n const links = extractLinks(html)\n for (const link of links) {\n addCrawlPageTask({ path: link, fromCrawl: true })\n }\n }\n } catch (error) {\n if (retries < (prerenderOptions.retryCount ?? 0)) {\n logger.warn(`Encountered error, retrying: ${page.path} in 500ms`)\n await new Promise((resolve) =>\n setTimeout(resolve, prerenderOptions.retryDelay),\n )\n retriesByPath.set(page.path, retries + 1)\n addCrawlPageTask(page)\n } else {\n throw error\n }\n }\n })\n }\n }\n}\n"],"names":["createLogger","VITE_ENVIRONMENT_NAMES","createNitro","getRollupConfig","buildNitro","_a","queue","Queue","withBase","joinURL","withoutBase","fsp"],"mappings":";;;;;;;;;;;AAcA,eAAsB,UAAU;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AACF,GAIG;;AACK,QAAA,SAASA,mBAAa,WAAW;AACvC,SAAO,KAAK,qBAAqB;AAGjC,QAAI,aAAQ,cAAR,mBAAmB,YAAW,CAAC,QAAQ,MAAM,QAAQ;AACvD,YAAQ,QAAQ;AAAA,MACd;AAAA,QACE,MAAM;AAAA,MAAA;AAAA,IAEV;AAAA,EAAA;AAGF,QAAM,YAAY,QAAQ,aAAaC,UAAAA,uBAAuB,MAAM;AAEpE,MAAI,CAAC,WAAW;AACd,UAAM,IAAI;AAAA,MACR,WAAWA,iCAAuB,MAAM;AAAA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,KAAK,gCAAgC,KAAK,IAAI,WAAW;AAChE,kBAAM,IAAI;AAAA,cAAQ,CAAC,YACjB,WAAW,SAAS,iBAAiB,UAAU;AAAA,YACjD;AACA,0BAAc,IAAI,KAAK,MAAM,UAAU,CAAC;AACxC,6BAAiB,IAAI;AAAA,UAAA,OAChB;AACC,kBAAA;AAAA,UAAA;AAAA,QACR;AAAA,MACF,CACD;AAAA,IAAA;AAAA,EACH;AAEJ;;"}
|
|
1
|
+
{"version":3,"file":"prerender.cjs","sources":["../../../src/nitro-plugin/prerender.ts"],"sourcesContent":["import { promises as fsp } from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport { getRollupConfig } from 'nitropack/rollup'\nimport { build as buildNitro, createNitro } from 'nitropack'\nimport { joinURL, withBase, withoutBase } from 'ufo'\nimport { VITE_ENVIRONMENT_NAMES } from '../constants'\nimport { createLogger } from '../utils'\nimport { Queue } from './queue'\nimport type { ViteBuilder } from 'vite'\nimport type { $Fetch, Nitro } from 'nitropack'\nimport type { TanStackStartOutputConfig } from '../plugin'\nimport type { Page } from '../schema'\n\nexport async function prerender({\n options,\n nitro,\n builder,\n}: {\n options: TanStackStartOutputConfig\n nitro: Nitro\n builder: ViteBuilder\n}) {\n const logger = createLogger('prerender')\n logger.info('Prendering pages...')\n\n // If prerender is enabled but no pages are provided, default to prerendering the root page\n if (options.prerender?.enabled && !options.pages.length) {\n options.pages = [\n {\n path: '/',\n },\n ]\n }\n\n const serverEnv = builder.environments[VITE_ENVIRONMENT_NAMES.server]\n\n if (!serverEnv) {\n throw new Error(\n `Vite's \"${VITE_ENVIRONMENT_NAMES.server}\" environment not found`,\n )\n }\n\n const prerenderOutputDir = path.resolve(\n options.root,\n '.tanstack-start/build/prerenderer',\n )\n\n const nodeNitro = await createNitro({\n ...nitro.options._config,\n preset: 'nitro-prerender',\n logLevel: 0,\n output: {\n dir: prerenderOutputDir,\n serverDir: path.resolve(prerenderOutputDir, 'server'),\n publicDir: path.resolve(prerenderOutputDir, 'public'),\n },\n })\n\n const nodeNitroRollupOptions = getRollupConfig(nodeNitro)\n\n const build = serverEnv.config.build\n\n build.outDir = prerenderOutputDir\n\n build.rollupOptions = {\n ...build.rollupOptions,\n ...nodeNitroRollupOptions,\n output: {\n ...build.rollupOptions.output,\n ...nodeNitroRollupOptions.output,\n sourcemap: undefined,\n },\n }\n\n await buildNitro(nodeNitro)\n\n // Import renderer entry\n const serverFilename =\n typeof nodeNitroRollupOptions.output.entryFileNames === 'string'\n ? nodeNitroRollupOptions.output.entryFileNames\n : 'index.mjs'\n\n const serverEntrypoint = path.resolve(\n path.join(nodeNitro.options.output.serverDir, serverFilename),\n )\n\n const { closePrerenderer, localFetch } = (await import(serverEntrypoint)) as {\n closePrerenderer: () => void\n localFetch: $Fetch\n }\n\n try {\n // Crawl all pages\n const pages = await prerenderPages()\n\n logger.info(`Prerendered ${pages.length} pages:`)\n pages.forEach((page) => {\n logger.info(`- ${page}`)\n })\n\n // TODO: Write the prerendered pages to the output directory\n } catch (error) {\n logger.error(error)\n } finally {\n // Ensure server is always closed\n // server.process.kill()\n closePrerenderer()\n }\n\n function extractLinks(html: string): Array<string> {\n const linkRegex = /<a[^>]+href=[\"']([^\"']+)[\"'][^>]*>/g\n const links: Array<string> = []\n let match\n\n while ((match = linkRegex.exec(html)) !== null) {\n const href = match[1]\n if (href && (href.startsWith('/') || href.startsWith('./'))) {\n links.push(href)\n }\n }\n\n return links\n }\n\n async function prerenderPages() {\n const seen = new Set<string>()\n const retriesByPath = new Map<string, number>()\n const concurrency = options.prerender?.concurrency ?? os.cpus().length\n logger.info(`Concurrency: ${concurrency}`)\n const queue = new Queue({ concurrency })\n\n options.pages.forEach((page) => addCrawlPageTask(page))\n\n await queue.start()\n\n return Array.from(seen)\n\n function addCrawlPageTask(page: Page) {\n // Was the page already seen?\n if (seen.has(page.path)) return\n\n // Add the page to the seen set\n seen.add(page.path)\n\n if (page.fromCrawl) {\n options.pages.push(page)\n }\n\n // If not enabled, skip\n if (!(page.prerender?.enabled ?? true)) return\n\n // If there is a filter link, check if the page should be prerendered\n if (options.prerender?.filter && !options.prerender.filter(page)) return\n\n // Resolve the merged default and page-specific prerender options\n const prerenderOptions = {\n ...options.prerender,\n ...page.prerender,\n }\n\n // Add the task\n queue.add(async () => {\n logger.info(`Crawling: ${page.path}`)\n const retries = retriesByPath.get(page.path) || 0\n try {\n // Fetch the route\n const encodedRoute = encodeURI(page.path)\n\n const res = await localFetch<Response>(\n withBase(encodedRoute, nodeNitro.options.baseURL),\n {\n headers: { 'x-nitro-prerender': encodedRoute },\n },\n )\n\n if (!res.ok) {\n throw new Error(`Failed to fetch ${page.path}: ${res.statusText}`, {\n cause: res,\n })\n }\n\n const cleanPagePath = (\n prerenderOptions.outputPath || page.path\n ).split(/[?#]/)[0]!\n\n // Guess route type and populate fileName\n const contentType = res.headers.get('content-type') || ''\n const isImplicitHTML =\n !cleanPagePath.endsWith('.html') && contentType.includes('html')\n // &&\n // !JsonSigRx.test(dataBuff.subarray(0, 32).toString('utf8'))\n const routeWithIndex = cleanPagePath.endsWith('/')\n ? cleanPagePath + 'index'\n : cleanPagePath\n\n const htmlPath =\n cleanPagePath.endsWith('/') || prerenderOptions.autoSubfolderIndex\n ? joinURL(cleanPagePath, 'index.html')\n : cleanPagePath + '.html'\n\n const filename = withoutBase(\n isImplicitHTML ? htmlPath : routeWithIndex,\n nitro.options.baseURL,\n )\n\n const html = await res.text()\n\n const filepath = path.join(nitro.options.output.publicDir, filename)\n\n await fsp.mkdir(path.dirname(filepath), {\n recursive: true,\n })\n\n await fsp.writeFile(filepath, html)\n\n const newPage = await prerenderOptions.onSuccess?.({ page, html })\n\n if (newPage) {\n Object.assign(page, newPage)\n }\n\n // Find new links\n if (prerenderOptions.crawlLinks ?? true) {\n const links = extractLinks(html)\n for (const link of links) {\n addCrawlPageTask({ path: link, fromCrawl: true })\n }\n }\n } catch (error) {\n if (retries < (prerenderOptions.retryCount ?? 0)) {\n logger.warn(`Encountered error, retrying: ${page.path} in 500ms`)\n await new Promise((resolve) =>\n setTimeout(resolve, prerenderOptions.retryDelay),\n )\n retriesByPath.set(page.path, retries + 1)\n addCrawlPageTask(page)\n } else {\n throw error\n }\n }\n })\n }\n }\n}\n"],"names":["createLogger","VITE_ENVIRONMENT_NAMES","createNitro","getRollupConfig","buildNitro","_a","queue","Queue","withBase","joinURL","withoutBase","fsp"],"mappings":";;;;;;;;;;;AAcA,eAAsB,UAAU;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AACF,GAIG;;AACK,QAAA,SAASA,mBAAa,WAAW;AACvC,SAAO,KAAK,qBAAqB;AAGjC,QAAI,aAAQ,cAAR,mBAAmB,YAAW,CAAC,QAAQ,MAAM,QAAQ;AACvD,YAAQ,QAAQ;AAAA,MACd;AAAA,QACE,MAAM;AAAA,MAAA;AAAA,IAEV;AAAA,EAAA;AAGF,QAAM,YAAY,QAAQ,aAAaC,UAAAA,uBAAuB,MAAM;AAEpE,MAAI,CAAC,WAAW;AACd,UAAM,IAAI;AAAA,MACR,WAAWA,iCAAuB,MAAM;AAAA,IAC1C;AAAA,EAAA;AAGF,QAAM,qBAAqB,KAAK;AAAA,IAC9B,QAAQ;AAAA,IACR;AAAA,EACF;AAEM,QAAA,YAAY,MAAMC,sBAAY;AAAA,IAClC,GAAG,MAAM,QAAQ;AAAA,IACjB,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,QAAQ;AAAA,MACN,KAAK;AAAA,MACL,WAAW,KAAK,QAAQ,oBAAoB,QAAQ;AAAA,MACpD,WAAW,KAAK,QAAQ,oBAAoB,QAAQ;AAAA,IAAA;AAAA,EACtD,CACD;AAEK,QAAA,yBAAyBC,uBAAgB,SAAS;AAElD,QAAA,QAAQ,UAAU,OAAO;AAE/B,QAAM,SAAS;AAEf,QAAM,gBAAgB;AAAA,IACpB,GAAG,MAAM;AAAA,IACT,GAAG;AAAA,IACH,QAAQ;AAAA,MACN,GAAG,MAAM,cAAc;AAAA,MACvB,GAAG,uBA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ACf,iBAAiB,WAAW;AAAA,YAC5B,MAAM,QAAQ;AAAA,UAChB;AAEM,gBAAA,OAAO,MAAM,IAAI,KAAK;AAE5B,gBAAM,WAAW,KAAK,KAAK,MAAM,QAAQ,OAAO,WAAW,QAAQ;AAEnE,gBAAMC,QAAI,SAAA,MAAM,KAAK,QAAQ,QAAQ,GAAG;AAAA,YACtC,WAAW;AAAA,UAAA,CACZ;AAEK,gBAAAA,iBAAI,UAAU,UAAU,IAAI;AAElC,gBAAM,UAAU,QAAMN,MAAA,iBAAiB,cAAjB,gBAAAA,IAAA,uBAA6B,EAAE,MAAM;AAE3D,cAAI,SAAS;AACJ,mBAAA,OAAO,MAAM,OAAO;AAAA,UAAA;AAIzB,cAAA,iBAAiB,cAAc,MAAM;AACjC,kBAAA,QAAQ,aAAa,IAAI;AAC/B,uBAAW,QAAQ,OAAO;AACxB,+BAAiB,EAAE,MAAM,MAAM,WAAW,MAAM;AAAA,YAAA;AAAA,UAClD;AAAA,iBAEK,OAAO;AACV,cAAA,WAAW,iBAAiB,cAAc,IAAI;AAChD,mBAAO,KAAK,gCAAgC,KAAK,IAAI,WAAW;AAChE,kBAAM,IAAI;AAAA,cAAQ,CAAC,YACjB,WAAW,SAAS,iBAAiB,UAAU;AAAA,YACjD;AACA,0BAAc,IAAI,KAAK,MAAM,UAAU,CAAC;AACxC,6BAAiB,IAAI;AAAA,UAAA,OAChB;AACC,kBAAA;AAAA,UAAA;AAAA,QACR;AAAA,MACF,CACD;AAAA,IAAA;AAAA,EACH;AAEJ;;"}
|
package/dist/cjs/plugin.cjs
CHANGED
|
@@ -3,18 +3,18 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
3
3
|
const path = require("node:path");
|
|
4
4
|
const nitropack = require("nitropack");
|
|
5
5
|
const routerCore = require("@tanstack/router-core");
|
|
6
|
-
const
|
|
6
|
+
const startServerCore = require("@tanstack/start-server-core");
|
|
7
7
|
const serverFunctionsPlugin = require("@tanstack/server-functions-plugin");
|
|
8
|
-
const vite
|
|
8
|
+
const vite = require("vite");
|
|
9
9
|
const schema = require("./schema.cjs");
|
|
10
|
-
const plugin$
|
|
11
|
-
const plugin$
|
|
10
|
+
const plugin$5 = require("./nitro-plugin/plugin.cjs");
|
|
11
|
+
const plugin$3 = require("./start-manifest-plugin/plugin.cjs");
|
|
12
12
|
const startCompilerPlugin = require("./start-compiler-plugin.cjs");
|
|
13
13
|
const constants = require("./constants.cjs");
|
|
14
|
-
const plugin
|
|
15
|
-
const plugin$
|
|
16
|
-
const plugin$
|
|
17
|
-
const plugin = require("./resolve-virtual-entries-plugin/plugin.cjs");
|
|
14
|
+
const plugin = require("./start-router-plugin/plugin.cjs");
|
|
15
|
+
const plugin$2 = require("./load-env-plugin/plugin.cjs");
|
|
16
|
+
const plugin$4 = require("./dev-server-plugin/plugin.cjs");
|
|
17
|
+
const plugin$1 = require("./resolve-virtual-entries-plugin/plugin.cjs");
|
|
18
18
|
function _interopNamespaceDefault(e) {
|
|
19
19
|
const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
|
|
20
20
|
if (e) {
|
|
@@ -31,19 +31,17 @@ function _interopNamespaceDefault(e) {
|
|
|
31
31
|
n.default = e;
|
|
32
32
|
return Object.freeze(n);
|
|
33
33
|
}
|
|
34
|
-
const vite__namespace = /* @__PURE__ */ _interopNamespaceDefault(vite
|
|
34
|
+
const vite__namespace = /* @__PURE__ */ _interopNamespaceDefault(vite);
|
|
35
35
|
schema.createTanStackConfig();
|
|
36
36
|
let ssrBundle;
|
|
37
37
|
function TanStackStartVitePluginCore(opts, startConfig) {
|
|
38
38
|
return [
|
|
39
|
-
|
|
40
|
-
verboseFileRoutes: false,
|
|
39
|
+
plugin.tanStackStartRouter({
|
|
41
40
|
...startConfig.tsr,
|
|
42
41
|
target: opts.framework,
|
|
43
|
-
enableRouteGeneration: true,
|
|
44
42
|
autoCodeSplitting: true
|
|
45
43
|
}),
|
|
46
|
-
plugin.resolveVirtualEntriesPlugin(opts, startConfig),
|
|
44
|
+
plugin$1.resolveVirtualEntriesPlugin(opts, startConfig),
|
|
47
45
|
{
|
|
48
46
|
name: "tanstack-start-core:config-client",
|
|
49
47
|
async config(viteConfig) {
|
|
@@ -127,18 +125,13 @@ function TanStackStartVitePluginCore(opts, startConfig) {
|
|
|
127
125
|
"@tanstack/start-router-manifest",
|
|
128
126
|
"@tanstack/start-config",
|
|
129
127
|
"@tanstack/server-functions-plugin",
|
|
130
|
-
"tanstack-start-router-manifest:v",
|
|
131
|
-
"tanstack-start-server-fn-manifest:v",
|
|
132
128
|
"nitropack",
|
|
133
|
-
"@tanstack/**start**"
|
|
129
|
+
"@tanstack/**start**",
|
|
130
|
+
...Object.values(startServerCore.VIRTUAL_MODULES)
|
|
134
131
|
]
|
|
135
132
|
},
|
|
136
133
|
optimizeDeps: {
|
|
137
|
-
exclude: [
|
|
138
|
-
"tanstack-start-server-fn-manifest:v",
|
|
139
|
-
"tanstack-start-router-manifest:v",
|
|
140
|
-
"tanstack-start-server-routes-manifest:v"
|
|
141
|
-
]
|
|
134
|
+
exclude: [...Object.values(startServerCore.VIRTUAL_MODULES)]
|
|
142
135
|
},
|
|
143
136
|
/* prettier-ignore */
|
|
144
137
|
define: {
|
|
@@ -162,7 +155,7 @@ function TanStackStartVitePluginCore(opts, startConfig) {
|
|
|
162
155
|
serverFunctionsPlugin.TanStackServerFnPluginEnv({
|
|
163
156
|
// This is the ID that will be available to look up and import
|
|
164
157
|
// our server function manifest and resolve its module
|
|
165
|
-
manifestVirtualImportId:
|
|
158
|
+
manifestVirtualImportId: startServerCore.VIRTUAL_MODULES.serverFnManifest,
|
|
166
159
|
manifestOutputFilename: ".tanstack-start/build/server/server-functions-manifest.json",
|
|
167
160
|
client: {
|
|
168
161
|
getRuntimeCode: () => `import { createClientRpc } from '@tanstack/${opts.framework}-start/server-functions-client'`,
|
|
@@ -182,14 +175,10 @@ function TanStackStartVitePluginCore(opts, startConfig) {
|
|
|
182
175
|
return serverEnv.runner.import(fn.extractedFilename);
|
|
183
176
|
}
|
|
184
177
|
}),
|
|
185
|
-
plugin$
|
|
186
|
-
plugin$
|
|
187
|
-
plugin$
|
|
188
|
-
plugin$
|
|
189
|
-
plugin$5.TanStackStartServerRoutesVite({
|
|
190
|
-
...startConfig.tsr,
|
|
191
|
-
target: opts.framework
|
|
192
|
-
})
|
|
178
|
+
plugin$2.loadEnvPlugin(startConfig),
|
|
179
|
+
plugin$3.startManifestPlugin(startConfig),
|
|
180
|
+
plugin$4.devServerPlugin(),
|
|
181
|
+
plugin$5.nitroPlugin(startConfig, () => ssrBundle)
|
|
193
182
|
];
|
|
194
183
|
}
|
|
195
184
|
function defineReplaceEnv(key, value) {
|