@tanstack/start-plugin-core 1.120.4-alpha.15 → 1.120.4-alpha.16

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.
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const VITE_ENVIRONMENT_NAMES = {
4
+ // 'ssr' is chosen as the name for the server environment to ensure backwards compatibility
5
+ // with vite plugins that are not compatible with the new vite environment API (e.g. tailwindcss)
6
+ server: "ssr",
7
+ client: "client"
8
+ };
9
+ exports.VITE_ENVIRONMENT_NAMES = VITE_ENVIRONMENT_NAMES;
10
+ //# sourceMappingURL=constants.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.cjs","sources":["../../src/constants.ts"],"sourcesContent":["export const VITE_ENVIRONMENT_NAMES = {\n // 'ssr' is chosen as the name for the server environment to ensure backwards compatibility\n // with vite plugins that are not compatible with the new vite environment API (e.g. tailwindcss)\n server: 'ssr',\n client: 'client',\n} as const\n"],"names":[],"mappings":";;AAAO,MAAM,yBAAyB;AAAA;AAAA;AAAA,EAGpC,QAAQ;AAAA,EACR,QAAQ;AACV;;"}
@@ -0,0 +1,4 @@
1
+ export declare const VITE_ENVIRONMENT_NAMES: {
2
+ readonly server: "ssr";
3
+ readonly client: "client";
4
+ };
@@ -3,6 +3,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const h3 = require("h3");
4
4
  const vite = require("vite");
5
5
  const extractHtmlScripts = require("../extractHtmlScripts.cjs");
6
+ const constants = require("../constants.cjs");
6
7
  function devServerPlugin() {
7
8
  let isTest = false;
8
9
  return {
@@ -21,10 +22,17 @@ function devServerPlugin() {
21
22
  viteDevServer.middlewares.use(async (req, res) => {
22
23
  var _a;
23
24
  const event = h3.createEvent(req, res);
24
- const serverEnv = viteDevServer.environments["server"];
25
+ const serverEnv = viteDevServer.environments[constants.VITE_ENVIRONMENT_NAMES.server];
25
26
  try {
26
- if (!serverEnv || !vite.isRunnableDevEnvironment(serverEnv)) {
27
- throw new Error("Server environment not found");
27
+ if (!serverEnv) {
28
+ throw new Error(
29
+ `Server environment ${constants.VITE_ENVIRONMENT_NAMES.server} not found`
30
+ );
31
+ }
32
+ if (!vite.isRunnableDevEnvironment(serverEnv)) {
33
+ throw new Error(
34
+ `Expected server environment ${constants.VITE_ENVIRONMENT_NAMES.server} to be a RunnableDevEnvironment. This can be caused by multiple vite versions being installed in the project.`
35
+ );
28
36
  }
29
37
  if (cachedScripts === void 0) {
30
38
  const templateHtml = `<html><head></head><body></body></html>`;
@@ -1 +1 @@
1
- {"version":3,"file":"dev-server-plugin.cjs","sources":["../../../src/nitro/dev-server-plugin.ts"],"sourcesContent":["import { createEvent, getHeader, sendWebResponse } from 'h3'\nimport { isRunnableDevEnvironment } from 'vite'\nimport { extractHtmlScripts } from '../extractHtmlScripts'\nimport type { Connect, Plugin, ViteDevServer } from 'vite'\n\ndeclare global {\n // eslint-disable-next-line no-var\n var TSS_INJECTED_HEAD_SCRIPTS: string | undefined\n}\n\nexport function devServerPlugin(): Plugin {\n // let config: UserConfig\n let isTest = false\n\n return {\n name: 'start-dev-ssr-plugin',\n config(userConfig, { mode }) {\n // config = userConfig\n isTest = isTest ? isTest : mode === 'test'\n },\n configureServer(viteDevServer) {\n if (isTest) {\n return\n }\n\n ;(globalThis as any).viteDevServer = viteDevServer\n\n return () => {\n remove_html_middlewares(viteDevServer.middlewares)\n let cachedScripts: string | undefined\n viteDevServer.middlewares.use(async (req, res) => {\n const event = createEvent(req, res)\n const serverEnv = viteDevServer.environments['server']\n\n try {\n if (!serverEnv || !isRunnableDevEnvironment(serverEnv)) {\n throw new Error('Server environment not found')\n }\n if (cachedScripts === undefined) {\n const templateHtml = `<html><head></head><body></body></html>`\n const transformedHtml = await viteDevServer.transformIndexHtml(\n req.url || '/',\n templateHtml,\n )\n const scripts = extractHtmlScripts(transformedHtml)\n globalThis.TSS_INJECTED_HEAD_SCRIPTS = scripts\n .map((script) => script.content ?? '')\n .join(';')\n }\n const serverEntry = await serverEnv.runner.import(\n '/~start/server-entry',\n )\n const response = await serverEntry['default'](event)\n\n return sendWebResponse(event, response)\n } catch (e) {\n console.error(e)\n viteDevServer.ssrFixStacktrace(e as Error)\n\n if (\n getHeader(event, 'content-type')?.includes('application/json')\n ) {\n return sendWebResponse(\n event,\n new Response(\n JSON.stringify(\n {\n status: 500,\n error: 'Internal Server Error',\n message:\n 'An unexpected error occurred. Please try again later.',\n timestamp: new Date().toISOString(),\n },\n null,\n 2,\n ),\n {\n status: 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n },\n ),\n )\n }\n\n return sendWebResponse(\n event,\n new Response(\n `\n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <title>Error</title>\n <script type=\"module\">\n import { ErrorOverlay } from '/@vite/client'\n document.body.appendChild(new ErrorOverlay(${JSON.stringify(\n prepareError(req, e),\n ).replace(/</g, '\\\\u003c')}))\n </script>\n </head>\n <body>\n </body>\n </html>\n `,\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n },\n ),\n )\n }\n })\n }\n },\n }\n}\n\n/**\n * Removes Vite internal middleware\n *\n * @param server\n */\nfunction remove_html_middlewares(server: ViteDevServer['middlewares']) {\n const html_middlewares = [\n 'viteIndexHtmlMiddleware',\n 'vite404Middleware',\n 'viteSpaFallbackMiddleware',\n ]\n for (let i = server.stack.length - 1; i > 0; i--) {\n if (\n html_middlewares.includes(\n // @ts-expect-error\n server.stack[i].handle.name,\n )\n ) {\n server.stack.splice(i, 1)\n }\n }\n}\n\n/**\n * Formats error for SSR message in error overlay\n * @param req\n * @param error\n * @returns\n */\nfunction prepareError(req: Connect.IncomingMessage, error: unknown) {\n const e = error as Error\n return {\n message: `An error occured while server rendering ${req.url}:\\n\\n\\t${\n typeof e === 'string' ? e : e.message\n } `,\n stack: typeof e === 'string' ? '' : e.stack,\n }\n}\n"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;;"}
1
+ {"version":3,"file":"dev-server-plugin.cjs","sources":["../../../src/nitro/dev-server-plugin.ts"],"sourcesContent":["import { createEvent, getHeader, sendWebResponse } from 'h3'\nimport { isRunnableDevEnvironment } from 'vite'\nimport { extractHtmlScripts } from '../extractHtmlScripts'\nimport { VITE_ENVIRONMENT_NAMES } from '../constants'\nimport type { Connect, DevEnvironment, Plugin, ViteDevServer } from 'vite'\n\ndeclare global {\n // eslint-disable-next-line no-var\n var TSS_INJECTED_HEAD_SCRIPTS: string | undefined\n}\n\nexport function devServerPlugin(): Plugin {\n // let config: UserConfig\n let isTest = false\n\n return {\n name: 'start-dev-ssr-plugin',\n config(userConfig, { mode }) {\n // config = userConfig\n isTest = isTest ? isTest : mode === 'test'\n },\n configureServer(viteDevServer) {\n if (isTest) {\n return\n }\n\n ;(globalThis as any).viteDevServer = viteDevServer\n\n return () => {\n remove_html_middlewares(viteDevServer.middlewares)\n let cachedScripts: string | undefined\n viteDevServer.middlewares.use(async (req, res) => {\n const event = createEvent(req, res)\n const serverEnv = viteDevServer.environments[\n VITE_ENVIRONMENT_NAMES.server\n ] as DevEnvironment | undefined\n\n try {\n if (!serverEnv) {\n throw new Error(\n `Server environment ${VITE_ENVIRONMENT_NAMES.server} not found`,\n )\n }\n if (!isRunnableDevEnvironment(serverEnv)) {\n throw new Error(\n `Expected server environment ${VITE_ENVIRONMENT_NAMES.server} to be a RunnableDevEnvironment. This can be caused by multiple vite versions being installed in the project.`,\n )\n }\n if (cachedScripts === undefined) {\n const templateHtml = `<html><head></head><body></body></html>`\n const transformedHtml = await viteDevServer.transformIndexHtml(\n req.url || '/',\n templateHtml,\n )\n const scripts = extractHtmlScripts(transformedHtml)\n globalThis.TSS_INJECTED_HEAD_SCRIPTS = scripts\n .map((script) => script.content ?? '')\n .join(';')\n }\n const serverEntry = await serverEnv.runner.import(\n '/~start/server-entry',\n )\n const response = await serverEntry['default'](event)\n\n return sendWebResponse(event, response)\n } catch (e) {\n console.error(e)\n viteDevServer.ssrFixStacktrace(e as Error)\n\n if (\n getHeader(event, 'content-type')?.includes('application/json')\n ) {\n return sendWebResponse(\n event,\n new Response(\n JSON.stringify(\n {\n status: 500,\n error: 'Internal Server Error',\n message:\n 'An unexpected error occurred. Please try again later.',\n timestamp: new Date().toISOString(),\n },\n null,\n 2,\n ),\n {\n status: 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n },\n ),\n )\n }\n\n return sendWebResponse(\n event,\n new Response(\n `\n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <title>Error</title>\n <script type=\"module\">\n import { ErrorOverlay } from '/@vite/client'\n document.body.appendChild(new ErrorOverlay(${JSON.stringify(\n prepareError(req, e),\n ).replace(/</g, '\\\\u003c')}))\n </script>\n </head>\n <body>\n </body>\n </html>\n `,\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n },\n ),\n )\n }\n })\n }\n },\n }\n}\n\n/**\n * Removes Vite internal middleware\n *\n * @param server\n */\nfunction remove_html_middlewares(server: ViteDevServer['middlewares']) {\n const html_middlewares = [\n 'viteIndexHtmlMiddleware',\n 'vite404Middleware',\n 'viteSpaFallbackMiddleware',\n ]\n for (let i = server.stack.length - 1; i > 0; i--) {\n if (\n html_middlewares.includes(\n // @ts-expect-error\n server.stack[i].handle.name,\n )\n ) {\n server.stack.splice(i, 1)\n }\n }\n}\n\n/**\n * Formats error for SSR message in error overlay\n * @param req\n * @param error\n * @returns\n */\nfunction prepareError(req: Connect.IncomingMessage, error: unknown) {\n const e = error as Error\n return {\n message: `An error occured while server rendering ${req.url}:\\n\\n\\t${\n typeof e === 'string' ? e : e.message\n } `,\n stack: typeof e === 'string' ? '' : e.stack,\n }\n}\n"],"names":["createEvent","VITE_ENVIRONMENT_NAMES","isRunnableDevEnvironment","extractHtmlScripts","sendWebResponse","getHeader"],"mappings":";;;;;;AAWO,SAAS,kBAA0B;AAExC,MAAI,SAAS;AAEN,SAAA;AAAA,IACL,MAAM;AA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ACF;;"}
@@ -6,6 +6,7 @@ const nitropack = require("nitropack");
6
6
  const pathe = require("pathe");
7
7
  const plugin = require("../plugin.cjs");
8
8
  const prerender = require("../prerender.cjs");
9
+ const constants = require("../constants.cjs");
9
10
  const devServerPlugin = require("./dev-server-plugin.cjs");
10
11
  const buildNitro = require("./build-nitro.cjs");
11
12
  function nitroPlugin(options, getSsrBundle) {
@@ -15,7 +16,7 @@ function nitroPlugin(options, getSsrBundle) {
15
16
  {
16
17
  name: "tanstack-vite-plugin-nitro",
17
18
  configEnvironment(name) {
18
- if (name === "server") {
19
+ if (name === constants.VITE_ENVIRONMENT_NAMES.server) {
19
20
  return {
20
21
  build: {
21
22
  commonjsOptions: {
@@ -37,8 +38,8 @@ function nitroPlugin(options, getSsrBundle) {
37
38
  sharedPlugins: true,
38
39
  async buildApp(builder) {
39
40
  var _a, _b, _c;
40
- const clientEnv = builder.environments["client"];
41
- const serverEnv = builder.environments["server"];
41
+ const clientEnv = builder.environments[constants.VITE_ENVIRONMENT_NAMES.client];
42
+ const serverEnv = builder.environments[constants.VITE_ENVIRONMENT_NAMES.server];
42
43
  if (!clientEnv) {
43
44
  throw new Error("Client environment not found");
44
45
  }
@@ -1 +1 @@
1
- {"version":3,"file":"nitro-plugin.cjs","sources":["../../../src/nitro/nitro-plugin.ts"],"sourcesContent":["import path from 'node:path'\nimport { rmSync } from 'node:fs'\nimport { build, createNitro } from 'nitropack'\nimport { dirname, resolve } from 'pathe'\nimport { clientDistDir, ssrEntryFile } from '../plugin'\nimport { prerender } from '../prerender'\nimport { devServerPlugin } from './dev-server-plugin'\nimport { buildNitroEnvironment } from './build-nitro'\nimport type { EnvironmentOptions, PluginOption, Rollup } from 'vite'\nimport type { 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\n return [\n devServerPlugin(),\n {\n name: 'tanstack-vite-plugin-nitro',\n configEnvironment(name) {\n if (name === '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 clientEnv = builder.environments['client']\n const serverEnv = builder.environments['server']\n\n if (!clientEnv) {\n throw new Error('Client environment not found')\n }\n\n if (!serverEnv) {\n throw new Error('SSR environment not found')\n }\n\n const clientOutputDir = resolve(options.root, clientDistDir)\n rmSync(clientOutputDir, { recursive: true, force: true })\n await builder.build(clientEnv)\n\n await builder.build(serverEnv)\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 publicAssets: [\n {\n dir: path.resolve(options.root, clientDistDir),\n },\n ],\n typescript: {\n generateTsConfig: false,\n },\n prerender: undefined,\n renderer: ssrEntryFile,\n rollupConfig: {\n plugins: [virtualBundlePlugin(getSsrBundle())],\n },\n routeRules: {\n // TODO: We need to expose *some* kind of routeRules configuration\n // and it needs to translate to this for now. But we should\n // be cognizant of the probability that we will not use Nitro's\n // routeRules configuration in the future.\n ...(options.shell?.enabled && options.shell.autoRedirect\n ? {\n '/**': {\n // @ts-expect-error We are using this as a marker\n __TSS_SHELL: true,\n redirect: {\n to: `${options.shell.prerender.outputPath.replace(/[/]{1,}$/, '')}`,\n statusCode: 200,\n },\n },\n }\n : {}),\n },\n }\n\n const nitro = await createNitro(nitroConfig)\n\n await buildNitroEnvironment(nitro, () => build(nitro))\n\n if (options.shell?.enabled) {\n options.prerender = {\n ...options.prerender,\n enabled: true,\n }\n\n const maskUrl = new URL(\n options.shell.maskPath,\n 'http://localhost',\n )\n\n maskUrl.searchParams.set('__TSS_SHELL', 'true')\n\n options.pages.push({\n path: maskUrl.toString().replace('http://localhost', ''),\n prerender: options.shell.prerender,\n sitemap: {\n exclude: true,\n },\n })\n }\n\n if (options.prerender?.enabled) {\n await prerender({\n options,\n nitro,\n builder,\n })\n }\n\n // if (nitroConfig.prerender?.routes?.length && options.sitemap) {\n // console.log('Building Sitemap...')\n // // sitemap needs to be built after all directories are built\n // await buildSitemap({\n // host: options.sitemap.host,\n // routes: nitroConfig.prerender.routes,\n // outputDir: resolve(options.root, 'dist/public'),\n // })\n // }\n\n // console.log(\n // `\\n\\n✅ Client and server bundles successfully built.`,\n // )\n },\n },\n }\n },\n },\n ]\n}\n\nfunction virtualBundlePlugin(ssrBundle: Rollup.OutputBundle): Rollup.Plugin {\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":["devServerPlugin","resolve","clientDistDir","rmSync","ssrEntryFile","createNitro","buildNitroEnvironment","build","prerender","dirname"],"mappings":";;;;;;;;;;AAYgB,SAAA,YACd,SACA,cACqB;AACrB,QAAM,cACJ,QAAQ,IAAI,cAAc,KAAM,QAAQ;AAEnC,SAAA;AAAA,IACLA,gCAAgB;AAAA,IAChB;AAAA,MACE,MAAM;AAAA,MACN,kBAAkB,MAAM;AACtB,YAAI,SAAS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AU,GAAG,QAAQ,MAAM;AACxC,UAAA,YAAY,SAAS,SAAS,SAAS;AACzC,sBAAc,MAAM,SAAS;AAAA,MAAA;AAEtB,eAAA,IAAI,UAAU,aAAa;AACpC,eAAS,IAAIP,MAAAA,QAAQ,QAAQ,GAAG,aAAa;AAAA,IAAA;AAAA,EAC/C;AAGK,SAAA;AAAA,IACL,MAAM;AAAA,IACN,UAAU,IAAI,UAAU;AAClB,UAAA,SAAS,IAAI,EAAE,GAAG;AACpB,eAAOA,MAAAA,QAAQ,EAAE;AAAA,MAAA;AAGnB,UAAI,UAAU;AACZ,cAAM,WAAWA,MAAA,QAAQQ,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":"nitro-plugin.cjs","sources":["../../../src/nitro/nitro-plugin.ts"],"sourcesContent":["import path from 'node:path'\nimport { rmSync } from 'node:fs'\nimport { build, createNitro } from 'nitropack'\nimport { dirname, resolve } from 'pathe'\nimport { clientDistDir, ssrEntryFile } from '../plugin'\nimport { prerender } from '../prerender'\nimport { VITE_ENVIRONMENT_NAMES } from '../constants'\nimport { devServerPlugin } from './dev-server-plugin'\nimport { buildNitroEnvironment } from './build-nitro'\nimport type { EnvironmentOptions, PluginOption, Rollup } from 'vite'\nimport type { 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\n return [\n devServerPlugin(),\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 clientEnv =\n builder.environments[VITE_ENVIRONMENT_NAMES.client]\n const serverEnv =\n builder.environments[VITE_ENVIRONMENT_NAMES.server]\n\n if (!clientEnv) {\n throw new Error('Client environment not found')\n }\n\n if (!serverEnv) {\n throw new Error('SSR environment not found')\n }\n\n const clientOutputDir = resolve(options.root, clientDistDir)\n rmSync(clientOutputDir, { recursive: true, force: true })\n await builder.build(clientEnv)\n\n await builder.build(serverEnv)\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 publicAssets: [\n {\n dir: path.resolve(options.root, clientDistDir),\n },\n ],\n typescript: {\n generateTsConfig: false,\n },\n prerender: undefined,\n renderer: ssrEntryFile,\n rollupConfig: {\n plugins: [virtualBundlePlugin(getSsrBundle())],\n },\n routeRules: {\n // TODO: We need to expose *some* kind of routeRules configuration\n // and it needs to translate to this for now. But we should\n // be cognizant of the probability that we will not use Nitro's\n // routeRules configuration in the future.\n ...(options.shell?.enabled && options.shell.autoRedirect\n ? {\n '/**': {\n // @ts-expect-error We are using this as a marker\n __TSS_SHELL: true,\n redirect: {\n to: `${options.shell.prerender.outputPath.replace(/[/]{1,}$/, '')}`,\n statusCode: 200,\n },\n },\n }\n : {}),\n },\n }\n\n const nitro = await createNitro(nitroConfig)\n\n await buildNitroEnvironment(nitro, () => build(nitro))\n\n if (options.shell?.enabled) {\n options.prerender = {\n ...options.prerender,\n enabled: true,\n }\n\n const maskUrl = new URL(\n options.shell.maskPath,\n 'http://localhost',\n )\n\n maskUrl.searchParams.set('__TSS_SHELL', 'true')\n\n options.pages.push({\n path: maskUrl.toString().replace('http://localhost', ''),\n prerender: options.shell.prerender,\n sitemap: {\n exclude: true,\n },\n })\n }\n\n if (options.prerender?.enabled) {\n await prerender({\n options,\n nitro,\n builder,\n })\n }\n\n // if (nitroConfig.prerender?.routes?.length && options.sitemap) {\n // console.log('Building Sitemap...')\n // // sitemap needs to be built after all directories are built\n // await buildSitemap({\n // host: options.sitemap.host,\n // routes: nitroConfig.prerender.routes,\n // outputDir: resolve(options.root, 'dist/public'),\n // })\n // }\n\n // console.log(\n // `\\n\\n✅ Client and server bundles successfully built.`,\n // )\n },\n },\n }\n },\n },\n ]\n}\n\nfunction virtualBundlePlugin(ssrBundle: Rollup.OutputBundle): Rollup.Plugin {\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":["devServerPlugin","VITE_ENVIRONMENT_NAMES","resolve","clientDistDir","rmSync","ssrEntryFile","createNitro","buildNitroEnvironment","build","prerender","dirname"],"mappings":";;;;;;;;;;;AAagB,SAAA,YACd,SACA,cACqB;AACrB,QAAM,cACJ,QAAQ,IAAI,cAAc,KAAM,QAAQ;AAEnC,SAAA;AAAA,IACLA,gCAAgB;AAAA,IAChB;AA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AAS;AAC5B,YAAM,gBAA+B;AAAA,QACnC,MAAM,QAAQ;AAAA,QACd,KAAK;AAAA,MACP;AACA,YAAM,WAAW,UAAU,GAAG,QAAQ,MAAM;AACxC,UAAA,YAAY,SAAS,SAAS,SAAS;AACzC,sBAAc,MAAM,SAAS;AAAA,MAAA;AAEtB,eAAA,IAAI,UAAU,aAAa;AACpC,eAAS,IAAIP,MAAAA,QAAQ,QAAQ,GAAG,aAAa;AAAA,IAAA;AAAA,EAC/C;AAGK,SAAA;AAAA,IACL,MAAM;AAAA,IACN,UAAU,IAAI,UAAU;AAClB,UAAA,SAAS,IAAI,EAAE,GAAG;AACpB,eAAOA,MAAAA,QAAQ,EAAE;AAAA,MAAA;AAGnB,UAAI,UAAU;AACZ,cAAM,WAAWA,MAAA,QAAQQ,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;;"}
@@ -2,23 +2,25 @@
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const path = require("node:path");
4
4
  const nitropack = require("nitropack");
5
+ const serverFunctionsPlugin = require("@tanstack/server-functions-plugin");
5
6
  const schema = require("./schema.cjs");
6
7
  const nitroPlugin = require("./nitro/nitro-plugin.cjs");
7
8
  const routesManifestPlugin = require("./routesManifestPlugin.cjs");
8
9
  const startCompilerPlugin = require("./start-compiler-plugin.cjs");
10
+ const constants = require("./constants.cjs");
9
11
  schema.createTanStackStartOptionsSchema();
10
12
  schema.createTanStackConfig();
11
13
  const clientDistDir = ".tanstack-start/build/client-dist";
12
14
  const ssrEntryFile = "ssr.mjs";
13
15
  let ssrBundle;
14
- function TanStackStartVitePluginCore(framework, opts) {
16
+ function TanStackStartVitePluginCore(opts, startConfig) {
15
17
  return [
16
18
  {
17
19
  name: "tanstack-start-core:config-client",
18
20
  async config() {
19
21
  const nitroOutputPublicDir = await (async () => {
20
22
  const dummyNitroApp = await nitropack.createNitro({
21
- preset: opts.target,
23
+ preset: startConfig.target,
22
24
  compatibilityDate: "2024-12-01"
23
25
  });
24
26
  const nitroOutputPublicDir2 = dummyNitroApp.options.output.publicDir;
@@ -27,23 +29,23 @@ function TanStackStartVitePluginCore(framework, opts) {
27
29
  })();
28
30
  return {
29
31
  environments: {
30
- client: {
32
+ [constants.VITE_ENVIRONMENT_NAMES.client]: {
31
33
  consumer: "client",
32
34
  build: {
33
35
  manifest: true,
34
36
  rollupOptions: {
35
37
  input: {
36
- main: opts.clientEntryPath
38
+ main: startConfig.clientEntryPath
37
39
  },
38
40
  output: {
39
- dir: path.resolve(opts.root, clientDistDir)
41
+ dir: path.resolve(startConfig.root, clientDistDir)
40
42
  },
41
43
  // TODO this should be removed
42
44
  external: ["node:fs", "node:path", "node:os", "node:crypto"]
43
45
  }
44
46
  }
45
47
  },
46
- server: {
48
+ [constants.VITE_ENVIRONMENT_NAMES.server]: {
47
49
  consumer: "server",
48
50
  build: {
49
51
  ssr: true,
@@ -90,18 +92,44 @@ function TanStackStartVitePluginCore(framework, opts) {
90
92
  },
91
93
  /* prettier-ignore */
92
94
  define: {
93
- ...injectDefineEnv("TSS_PUBLIC_BASE", opts.public.base),
94
- ...injectDefineEnv("TSS_CLIENT_BASE", opts.client.base),
95
- ...injectDefineEnv("TSS_CLIENT_ENTRY", opts.clientEntryPath),
96
- ...injectDefineEnv("TSS_SERVER_FN_BASE", opts.serverFns.base),
95
+ ...injectDefineEnv("TSS_PUBLIC_BASE", startConfig.public.base),
96
+ ...injectDefineEnv("TSS_CLIENT_BASE", startConfig.client.base),
97
+ ...injectDefineEnv("TSS_CLIENT_ENTRY", startConfig.clientEntryPath),
98
+ ...injectDefineEnv("TSS_SERVER_FN_BASE", startConfig.serverFns.base),
97
99
  ...injectDefineEnv("TSS_OUTPUT_PUBLIC_DIR", nitroOutputPublicDir)
98
100
  }
99
101
  };
100
102
  }
101
103
  },
102
- startCompilerPlugin.TanStackStartCompilerPlugin(framework),
103
- routesManifestPlugin.startManifestPlugin(opts),
104
- nitroPlugin.nitroPlugin(opts, () => ssrBundle)
104
+ // N.B. TanStackStartCompilerPlugin must be before the TanStackServerFnPluginEnv
105
+ startCompilerPlugin.TanStackStartCompilerPlugin(opts.framework, {
106
+ client: { envName: constants.VITE_ENVIRONMENT_NAMES.client },
107
+ server: { envName: constants.VITE_ENVIRONMENT_NAMES.server }
108
+ }),
109
+ serverFunctionsPlugin.TanStackServerFnPluginEnv({
110
+ // This is the ID that will be available to look up and import
111
+ // our server function manifest and resolve its module
112
+ manifestVirtualImportId: "tanstack:server-fn-manifest",
113
+ client: {
114
+ getRuntimeCode: () => `import { createClientRpc } from '@tanstack/${opts.framework}-start/server-functions-client'`,
115
+ replacer: (d) => `createClientRpc('${d.functionId}', '${startConfig.serverFns.base}')`,
116
+ envName: constants.VITE_ENVIRONMENT_NAMES.client
117
+ },
118
+ server: {
119
+ getRuntimeCode: () => `import { createServerRpc } from '@tanstack/${opts.framework}-start/server-functions-server'`,
120
+ replacer: (d) => `createServerRpc('${d.functionId}', '${startConfig.serverFns.base}', ${d.fn})`,
121
+ envName: constants.VITE_ENVIRONMENT_NAMES.server
122
+ },
123
+ importer: (fn) => {
124
+ const serverEnv = globalThis.viteDevServer.environments[constants.VITE_ENVIRONMENT_NAMES.server];
125
+ if (!serverEnv) {
126
+ throw new Error(`'ssr' vite dev environment not found`);
127
+ }
128
+ return serverEnv.runner.import(fn.extractedFilename);
129
+ }
130
+ }),
131
+ routesManifestPlugin.startManifestPlugin(startConfig),
132
+ nitroPlugin.nitroPlugin(startConfig, () => ssrBundle)
105
133
  ];
106
134
  }
107
135
  function injectDefineEnv(key, value) {
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.cjs","sources":["../../src/plugin.ts"],"sourcesContent":["import path from 'node:path'\nimport { createNitro } from 'nitropack'\nimport {\n createTanStackConfig,\n createTanStackStartOptionsSchema,\n} from './schema'\nimport { nitroPlugin } from './nitro/nitro-plugin'\nimport { startManifestPlugin } from './routesManifestPlugin'\nimport { TanStackStartCompilerPlugin } from './start-compiler-plugin'\nimport type { PluginOption, Rollup } from 'vite'\nimport type { z } from 'zod'\nimport type { CompileStartFrameworkOptions } from './compilers'\n\nconst TanStackStartOptionsSchema = createTanStackStartOptionsSchema()\nexport type TanStackStartInputConfig = z.input<\n typeof TanStackStartOptionsSchema\n>\n\nconst defaultConfig = createTanStackConfig()\nexport function getTanStackStartOptions(opts?: TanStackStartInputConfig) {\n return defaultConfig.parse(opts)\n}\n\nexport type TanStackStartOutputConfig = ReturnType<\n typeof getTanStackStartOptions\n>\n\nexport const clientDistDir = '.tanstack-start/build/client-dist'\nexport const ssrEntryFile = 'ssr.mjs'\n\n// this needs to live outside of the TanStackStartVitePluginCore since it will be invoked multiple times by vite\nlet ssrBundle: Rollup.OutputBundle\n\nexport function TanStackStartVitePluginCore(\n framework: CompileStartFrameworkOptions,\n opts: TanStackStartOutputConfig,\n): Array<PluginOption> {\n return [\n {\n name: 'tanstack-start-core:config-client',\n async config() {\n const nitroOutputPublicDir = await (async () => {\n // Create a dummy nitro app to get the resolved public output path\n const dummyNitroApp = await createNitro({\n preset: opts.target,\n compatibilityDate: '2024-12-01',\n })\n\n const nitroOutputPublicDir = dummyNitroApp.options.output.publicDir\n await dummyNitroApp.close()\n\n return nitroOutputPublicDir\n })()\n\n return {\n environments: {\n client: {\n consumer: 'client',\n build: {\n manifest: true,\n rollupOptions: {\n input: {\n main: opts.clientEntryPath,\n },\n output: {\n dir: path.resolve(opts.root, clientDistDir),\n },\n // TODO this should be removed\n external: ['node:fs', 'node:path', 'node:os', 'node:crypto'],\n },\n },\n },\n server: {\n consumer: 'server',\n build: {\n ssr: true,\n // we don't write to the file system as the below 'capture-output' plugin will\n // capture the output and write it to the virtual file system\n write: false,\n copyPublicDir: false,\n rollupOptions: {\n output: {\n entryFileNames: ssrEntryFile,\n },\n plugins: [\n {\n name: 'capture-output',\n generateBundle(options, bundle) {\n // TODO can this hook be called more than once?\n ssrBundle = bundle\n },\n },\n ],\n },\n commonjsOptions: {\n include: [/node_modules/],\n },\n },\n },\n },\n resolve: {\n noExternal: [\n '@tanstack/start-client',\n '@tanstack/start-client-core',\n '@tanstack/start-server',\n '@tanstack/start-server-core',\n '@tanstack/start-server-functions-fetcher',\n '@tanstack/start-server-functions-client',\n '@tanstack/start-server-functions-server',\n '@tanstack/start-router-manifest',\n '@tanstack/start-config',\n '@tanstack/server-functions-plugin',\n 'tanstack:start-manifest',\n 'tanstack:server-fn-manifest',\n 'nitropack',\n '@tanstack/**',\n ],\n },\n /* prettier-ignore */\n define: {\n ...injectDefineEnv('TSS_PUBLIC_BASE', opts.public.base),\n ...injectDefineEnv('TSS_CLIENT_BASE', opts.client.base),\n ...injectDefineEnv('TSS_CLIENT_ENTRY', opts.clientEntryPath),\n ...injectDefineEnv('TSS_SERVER_FN_BASE', opts.serverFns.base),\n ...injectDefineEnv('TSS_OUTPUT_PUBLIC_DIR', nitroOutputPublicDir),\n },\n }\n },\n },\n TanStackStartCompilerPlugin(framework),\n startManifestPlugin(opts),\n nitroPlugin(opts, () => ssrBundle),\n ]\n}\n\nfunction injectDefineEnv<TKey extends string, TValue extends string>(\n key: TKey,\n value: TValue,\n): { [P in `process.env.${TKey}` | `import.meta.env.${TKey}`]: TValue } {\n return {\n [`process.env.${key}`]: JSON.stringify(value),\n [`import.meta.env.${key}`]: JSON.stringify(value),\n } as { [P in `process.env.${TKey}` | `import.meta.env.${TKey}`]: TValue }\n}\n"],"names":["createTanStackStartOptionsSchema","createTanStackConfig","createNitro","nitroOutputPublicDir","TanStackStartCompilerPlugin","startManifestPlugin","nitroPlugin"],"mappings":";;;;;;;;AAamCA,OAAiC,iCAAA;AAK9CC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A;AAAA,cACA;AAAA,cACA;AAAA,cACA;AAAA,cACA;AAAA,cACA;AAAA,cACA;AAAA,cACA;AAAA,cACA;AAAA,cACA;AAAA,cACA;AAAA,cACA;AAAA,cACA;AAAA,YAAA;AAAA,UAEJ;AAAA;AAAA,UAEA,QAAQ;AAAA,YACN,GAAG,gBAAgB,mBAAmB,KAAK,OAAO,IAAI;AAAA,YACtD,GAAG,gBAAgB,mBAAmB,KAAK,OAAO,IAAI;AAAA,YACtD,GAAG,gBAAgB,oBAAoB,KAAK,eAAe;AAAA,YAC3D,GAAG,gBAAgB,sBAAsB,KAAK,UAAU,IAAI;AAAA,YAC5D,GAAG,gBAAgB,yBAAyB,oBAAoB;AAAA,UAAA;AAAA,QAEpE;AAAA,MAAA;AAAA,IAEJ;AAAA,IACAC,oBAAAA,4BAA4B,SAAS;AAAA,IACrCC,qBAAAA,oBAAoB,IAAI;AAAA,IACxBC,YAAA,YAAY,MAAM,MAAM,SAAS;AAAA,EACnC;AACF;AAEA,SAAS,gBACP,KACA,OACsE;AAC/D,SAAA;AAAA,IACL,CAAC,eAAe,GAAG,EAAE,GAAG,KAAK,UAAU,KAAK;AAAA,IAC5C,CAAC,mBAAmB,GAAG,EAAE,GAAG,KAAK,UAAU,KAAK;AAAA,EAClD;AACF;;;;"}
1
+ {"version":3,"file":"plugin.cjs","sources":["../../src/plugin.ts"],"sourcesContent":["import path from 'node:path'\nimport { createNitro } from 'nitropack'\nimport { TanStackServerFnPluginEnv } from '@tanstack/server-functions-plugin'\nimport {\n createTanStackConfig,\n createTanStackStartOptionsSchema,\n} from './schema'\nimport { nitroPlugin } from './nitro/nitro-plugin'\nimport { startManifestPlugin } from './routesManifestPlugin'\nimport { TanStackStartCompilerPlugin } from './start-compiler-plugin'\nimport { VITE_ENVIRONMENT_NAMES } from './constants'\nimport type { PluginOption, Rollup } from 'vite'\nimport type { z } from 'zod'\nimport type { CompileStartFrameworkOptions } from './compilers'\n\nconst TanStackStartOptionsSchema = createTanStackStartOptionsSchema()\nexport type TanStackStartInputConfig = z.input<\n typeof TanStackStartOptionsSchema\n>\n\nconst defaultConfig = createTanStackConfig()\nexport function getTanStackStartOptions(opts?: TanStackStartInputConfig) {\n return defaultConfig.parse(opts)\n}\n\nexport type TanStackStartOutputConfig = ReturnType<\n typeof getTanStackStartOptions\n>\n\nexport const clientDistDir = '.tanstack-start/build/client-dist'\nexport const ssrEntryFile = 'ssr.mjs'\n\nexport interface TanStackStartVitePluginCoreOptions {\n framework: CompileStartFrameworkOptions\n}\n// this needs to live outside of the TanStackStartVitePluginCore since it will be invoked multiple times by vite\nlet ssrBundle: Rollup.OutputBundle\n\nexport function TanStackStartVitePluginCore(\n opts: TanStackStartVitePluginCoreOptions,\n startConfig: TanStackStartOutputConfig,\n): Array<PluginOption> {\n return [\n {\n name: 'tanstack-start-core:config-client',\n async config() {\n const nitroOutputPublicDir = await (async () => {\n // Create a dummy nitro app to get the resolved public output path\n const dummyNitroApp = await createNitro({\n preset: startConfig.target,\n compatibilityDate: '2024-12-01',\n })\n\n const nitroOutputPublicDir = dummyNitroApp.options.output.publicDir\n await dummyNitroApp.close()\n\n return nitroOutputPublicDir\n })()\n\n return {\n environments: {\n [VITE_ENVIRONMENT_NAMES.client]: {\n consumer: 'client',\n build: {\n manifest: true,\n rollupOptions: {\n input: {\n main: startConfig.clientEntryPath,\n },\n output: {\n dir: path.resolve(startConfig.root, clientDistDir),\n },\n // TODO this should be removed\n external: ['node:fs', 'node:path', 'node:os', 'node:crypto'],\n },\n },\n },\n [VITE_ENVIRONMENT_NAMES.server]: {\n consumer: 'server',\n build: {\n ssr: true,\n // we don't write to the file system as the below 'capture-output' plugin will\n // capture the output and write it to the virtual file system\n write: false,\n copyPublicDir: false,\n rollupOptions: {\n output: {\n entryFileNames: ssrEntryFile,\n },\n plugins: [\n {\n name: 'capture-output',\n generateBundle(options, bundle) {\n // TODO can this hook be called more than once?\n ssrBundle = bundle\n },\n },\n ],\n },\n commonjsOptions: {\n include: [/node_modules/],\n },\n },\n },\n },\n resolve: {\n noExternal: [\n '@tanstack/start-client',\n '@tanstack/start-client-core',\n '@tanstack/start-server',\n '@tanstack/start-server-core',\n '@tanstack/start-server-functions-fetcher',\n '@tanstack/start-server-functions-client',\n '@tanstack/start-server-functions-server',\n '@tanstack/start-router-manifest',\n '@tanstack/start-config',\n '@tanstack/server-functions-plugin',\n 'tanstack:start-manifest',\n 'tanstack:server-fn-manifest',\n 'nitropack',\n '@tanstack/**',\n ],\n },\n /* prettier-ignore */\n define: {\n ...injectDefineEnv('TSS_PUBLIC_BASE', startConfig.public.base),\n ...injectDefineEnv('TSS_CLIENT_BASE', startConfig.client.base),\n ...injectDefineEnv('TSS_CLIENT_ENTRY', startConfig.clientEntryPath),\n ...injectDefineEnv('TSS_SERVER_FN_BASE', startConfig.serverFns.base),\n ...injectDefineEnv('TSS_OUTPUT_PUBLIC_DIR', nitroOutputPublicDir),\n },\n }\n },\n },\n // N.B. TanStackStartCompilerPlugin must be before the TanStackServerFnPluginEnv\n TanStackStartCompilerPlugin(opts.framework, {\n client: { envName: VITE_ENVIRONMENT_NAMES.client },\n server: { envName: VITE_ENVIRONMENT_NAMES.server },\n }),\n TanStackServerFnPluginEnv({\n // This is the ID that will be available to look up and import\n // our server function manifest and resolve its module\n manifestVirtualImportId: 'tanstack:server-fn-manifest',\n client: {\n getRuntimeCode: () =>\n `import { createClientRpc } from '@tanstack/${opts.framework}-start/server-functions-client'`,\n replacer: (d) =>\n `createClientRpc('${d.functionId}', '${startConfig.serverFns.base}')`,\n envName: VITE_ENVIRONMENT_NAMES.client,\n },\n server: {\n getRuntimeCode: () =>\n `import { createServerRpc } from '@tanstack/${opts.framework}-start/server-functions-server'`,\n replacer: (d) =>\n `createServerRpc('${d.functionId}', '${startConfig.serverFns.base}', ${d.fn})`,\n envName: VITE_ENVIRONMENT_NAMES.server,\n },\n importer: (fn) => {\n const serverEnv = (globalThis as any).viteDevServer.environments[\n VITE_ENVIRONMENT_NAMES.server\n ]\n if (!serverEnv) {\n throw new Error(`'ssr' vite dev environment not found`)\n }\n return serverEnv.runner.import(fn.extractedFilename)\n },\n }),\n startManifestPlugin(startConfig),\n nitroPlugin(startConfig, () => ssrBundle),\n ]\n}\n\nfunction injectDefineEnv<TKey extends string, TValue extends string>(\n key: TKey,\n value: TValue,\n): { [P in `process.env.${TKey}` | `import.meta.env.${TKey}`]: TValue } {\n return {\n [`process.env.${key}`]: JSON.stringify(value),\n [`import.meta.env.${key}`]: JSON.stringify(value),\n } as { [P in `process.env.${TKey}` | `import.meta.env.${TKey}`]: TValue }\n}\n"],"names":["createTanStackStartOptionsSchema","createTanStackConfig","createNitro","nitroOutputPublicDir","VITE_ENVIRONMENT_NAMES","TanStackStartCompilerPlugin","TanStackServerFnPluginEnv","startManifestPlugin","nitroPlugin"],"mappings":";;;;;;;;;;AAemCA,OAAiC,iCAAA;AAK9CC,OAAqB,qBAAA;AASpC,MAAM,gBAAgB;AACtB,MAAM,eAAe;AAM5B,IAAI;AAEY,SAAA,4BACd,MACA,aACqB;AACd,SAAA;AAAA,IACL;AAAA,MACE,MAAM;AAAA,MACN,MAAM,SAAS;AACP,cAAA,uBAAuB,OAAO,YAAY;AAExC,gBAAA,gBAAgB,MAAMC,sBAAY;AAAA,YACtC,QAAQ,YAAY;AAAA,YACpB,mBAAmB;AAAA,UAAA,CACpB;AAEKC,gBAAAA,wBAAuB,cAAc,QAAQ,OAAO;AAC1D,gBAAM,cAAc,MAAM;AAEnBA,iBAAAA;AAAAA,QAAAA,GACN;AAEI,eAAA;AAAA,UACL,cAAc;AAAA,YACZ,CAACC,UAAAA,uBAAuB,MAAM,GAAG;AAAA,cAC/B,UAAU;AAAA,cACV,OAAO;AAAA,gBACL,UAAU;AAAA,gBACV,eAAe;AAAA,kBACb,OAAO;AAAA,oBACL,MAAM,YAAY;AAAA,kBACpB;AAAA,kBACA,QAAQ;AAAA,oBACN,KAAK,KAAK,QAAQ,YAAY,MAAM,aAAa;AAAA,kBACnD;AAAA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AAuB,OAAO;AAAA,IAAA,CAClD;AAAA,IACDE,gDAA0B;AAAA;AAAA;AAAA,MAGxB,yBAAyB;AAAA,MACzB,QAAQ;AAAA,QACN,gBAAgB,MACd,8CAA8C,KAAK,SAAS;AAAA,QAC9D,UAAU,CAAC,MACT,oBAAoB,EAAE,UAAU,OAAO,YAAY,UAAU,IAAI;AAAA,QACnE,SAASF,UAAAA,uBAAuB;AAAA,MAClC;AAAA,MACA,QAAQ;AAAA,QACN,gBAAgB,MACd,8CAA8C,KAAK,SAAS;AAAA,QAC9D,UAAU,CAAC,MACT,oBAAoB,EAAE,UAAU,OAAO,YAAY,UAAU,IAAI,MAAM,EAAE,EAAE;AAAA,QAC7E,SAASA,UAAAA,uBAAuB;AAAA,MAClC;AAAA,MACA,UAAU,CAAC,OAAO;AAChB,cAAM,YAAa,WAAmB,cAAc,aAClDA,UAAAA,uBAAuB,MACzB;AACA,YAAI,CAAC,WAAW;AACR,gBAAA,IAAI,MAAM,sCAAsC;AAAA,QAAA;AAExD,eAAO,UAAU,OAAO,OAAO,GAAG,iBAAiB;AAAA,MAAA;AAAA,IACrD,CACD;AAAA,IACDG,qBAAAA,oBAAoB,WAAW;AAAA,IAC/BC,YAAA,YAAY,aAAa,MAAM,SAAS;AAAA,EAC1C;AACF;AAEA,SAAS,gBACP,KACA,OACsE;AAC/D,SAAA;AAAA,IACL,CAAC,eAAe,GAAG,EAAE,GAAG,KAAK,UAAU,KAAK;AAAA,IAC5C,CAAC,mBAAmB,GAAG,EAAE,GAAG,KAAK,UAAU,KAAK;AAAA,EAClD;AACF;;;;"}
@@ -3331,5 +3331,8 @@ export declare function getTanStackStartOptions(opts?: TanStackStartInputConfig)
3331
3331
  export type TanStackStartOutputConfig = ReturnType<typeof getTanStackStartOptions>;
3332
3332
  export declare const clientDistDir = ".tanstack-start/build/client-dist";
3333
3333
  export declare const ssrEntryFile = "ssr.mjs";
3334
- export declare function TanStackStartVitePluginCore(framework: CompileStartFrameworkOptions, opts: TanStackStartOutputConfig): Array<PluginOption>;
3334
+ export interface TanStackStartVitePluginCoreOptions {
3335
+ framework: CompileStartFrameworkOptions;
3336
+ }
3337
+ export declare function TanStackStartVitePluginCore(opts: TanStackStartVitePluginCoreOptions, startConfig: TanStackStartOutputConfig): Array<PluginOption>;
3335
3338
  export {};
@@ -8,6 +8,7 @@ const nitropack = require("nitropack");
8
8
  const ufo = require("ufo");
9
9
  const queue = require("./queue.cjs");
10
10
  const buildNitro = require("./nitro/build-nitro.cjs");
11
+ const constants = require("./constants.cjs");
11
12
  async function prerender({
12
13
  options,
13
14
  nitro,
@@ -22,9 +23,11 @@ async function prerender({
22
23
  }
23
24
  ];
24
25
  }
25
- const serverEnv = builder.environments["server"];
26
+ const serverEnv = builder.environments[constants.VITE_ENVIRONMENT_NAMES.server];
26
27
  if (!serverEnv) {
27
- throw new Error(`Vite's "server" environment not found`);
28
+ throw new Error(
29
+ `Vite's "${constants.VITE_ENVIRONMENT_NAMES.server}" environment not found`
30
+ );
28
31
  }
29
32
  const prerenderOutputDir = path.resolve(
30
33
  options.root,
@@ -1 +1 @@
1
- {"version":3,"file":"prerender.cjs","sources":["../../src/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 { Queue } from './queue'\nimport { buildNitroEnvironment } from './nitro/build-nitro'\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 console.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['server']\n\n if (!serverEnv) {\n throw new Error(`Vite's \"server\" environment not found`)\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 routeRules: {\n // Filter out our shell redirect rule if it exists\n ...Object.fromEntries(\n Object.entries(nitro.options._config.routeRules ?? {}).filter(\n ([_, value]) => !(value as any).__TSS_SHELL,\n ),\n ),\n },\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 buildNitroEnvironment(nodeNitro, () => 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 console.info(`Prerendered ${pages.length} pages:`)\n pages.forEach((page) => {\n console.info(`- ${page}`)\n })\n\n // TODO: Write the prerendered pages to the output directory\n } catch (error) {\n console.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 console.info(`Concurrency: ${concurrency}`)\n const queue = new Queue({ concurrency })\n\n options.pages.forEach((_page) => {\n let page = _page as Page\n\n if (typeof _page === 'string') {\n page = { path: _page }\n }\n\n addCrawlPageTask(page)\n })\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 console.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 console.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":["createNitro","getRollupConfig","buildNitroEnvironment","buildNitro","_a","queue","Queue","withBase","joinURL","withoutBase","fsp"],"mappings":";;;;;;;;;;AAaA,eAAsB,UAAU;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AACF,GAIG;;AACD,UAAQ,KAAK,qBAAqB;AAGlC,QAAI,aAAQ,cAAR,mBAAmB,YAAW,CAAC,QAAQ,MAAM,QAAQ;AACvD,YAAQ,QAAQ;AAAA,MACd;AAAA,QACE,MAAM;AAAA,MAAA;AAAA,IAEV;AAAA,EAAA;AAGI,QAAA,YAAY,QAAQ,aAAa,QAAQ;AAE/C,MAAI,CAAC,WAAW;AACR,UAAA,IAAI,MAAM,uCAAuC;AAAA,EAAA;AAGzD,QAAM,qBAAqB,KAAK;AAAA,IAC9B,QAAQ;AAAA,IACR;AAAA,EACF;AAEM,QAAA,YAAY,MAAMA,sBAAY;AAAA,IAClC,GAAG,MAAM,QAAQ;AAAA,IACjB,YAAY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AAQ,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,oBAAQ,KAAK,gCAAgC,KAAK,IAAI,WAAW;AACjE,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/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 { Queue } from './queue'\nimport { buildNitroEnvironment } from './nitro/build-nitro'\nimport { VITE_ENVIRONMENT_NAMES } from './constants'\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 console.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 routeRules: {\n // Filter out our shell redirect rule if it exists\n ...Object.fromEntries(\n Object.entries(nitro.options._config.routeRules ?? {}).filter(\n ([_, value]) => !(value as any).__TSS_SHELL,\n ),\n ),\n },\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 buildNitroEnvironment(nodeNitro, () => 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 console.info(`Prerendered ${pages.length} pages:`)\n pages.forEach((page) => {\n console.info(`- ${page}`)\n })\n\n // TODO: Write the prerendered pages to the output directory\n } catch (error) {\n console.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 console.info(`Concurrency: ${concurrency}`)\n const queue = new Queue({ concurrency })\n\n options.pages.forEach((_page) => {\n let page = _page as Page\n\n if (typeof _page === 'string') {\n page = { path: _page }\n }\n\n addCrawlPageTask(page)\n })\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 console.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 console.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":["VITE_ENVIRONMENT_NAMES","createNitro","getRollupConfig","buildNitroEnvironment","buildNitro","_a","queue","Queue","withBase","joinURL","withoutBase","fsp"],"mappings":";;;;;;;;;;;AAcA,eAAsB,UAAU;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AACF,GAIG;;AACD,UAAQ,KAAK,qBAAqB;AAGlC,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,aAAaA,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,YAAY;AAAA;AAAA,MAEV,GAAG,OAAO;AAAA,QACR,OAAO,QAAQ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AAiB,EAAE,MAAM,MAAM,WAAW,MAAM;AAAA,YAAA;AAAA,UAClD;AAAA,iBAEK,OAAO;AACV,cAAA,WAAW,iBAAiB,cAAc,IAAI;AAChD,oBAAQ,KAAK,gCAAgC,KAAK,IAAI,WAAW;AACjE,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;;"}
@@ -0,0 +1,4 @@
1
+ export declare const VITE_ENVIRONMENT_NAMES: {
2
+ readonly server: "ssr";
3
+ readonly client: "client";
4
+ };
@@ -0,0 +1,10 @@
1
+ const VITE_ENVIRONMENT_NAMES = {
2
+ // 'ssr' is chosen as the name for the server environment to ensure backwards compatibility
3
+ // with vite plugins that are not compatible with the new vite environment API (e.g. tailwindcss)
4
+ server: "ssr",
5
+ client: "client"
6
+ };
7
+ export {
8
+ VITE_ENVIRONMENT_NAMES
9
+ };
10
+ //# sourceMappingURL=constants.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.js","sources":["../../src/constants.ts"],"sourcesContent":["export const VITE_ENVIRONMENT_NAMES = {\n // 'ssr' is chosen as the name for the server environment to ensure backwards compatibility\n // with vite plugins that are not compatible with the new vite environment API (e.g. tailwindcss)\n server: 'ssr',\n client: 'client',\n} as const\n"],"names":[],"mappings":"AAAO,MAAM,yBAAyB;AAAA;AAAA;AAAA,EAGpC,QAAQ;AAAA,EACR,QAAQ;AACV;"}
@@ -1,6 +1,7 @@
1
1
  import { createEvent, sendWebResponse, getHeader } from "h3";
2
2
  import { isRunnableDevEnvironment } from "vite";
3
3
  import { extractHtmlScripts } from "../extractHtmlScripts.js";
4
+ import { VITE_ENVIRONMENT_NAMES } from "../constants.js";
4
5
  function devServerPlugin() {
5
6
  let isTest = false;
6
7
  return {
@@ -19,10 +20,17 @@ function devServerPlugin() {
19
20
  viteDevServer.middlewares.use(async (req, res) => {
20
21
  var _a;
21
22
  const event = createEvent(req, res);
22
- const serverEnv = viteDevServer.environments["server"];
23
+ const serverEnv = viteDevServer.environments[VITE_ENVIRONMENT_NAMES.server];
23
24
  try {
24
- if (!serverEnv || !isRunnableDevEnvironment(serverEnv)) {
25
- throw new Error("Server environment not found");
25
+ if (!serverEnv) {
26
+ throw new Error(
27
+ `Server environment ${VITE_ENVIRONMENT_NAMES.server} not found`
28
+ );
29
+ }
30
+ if (!isRunnableDevEnvironment(serverEnv)) {
31
+ throw new Error(
32
+ `Expected server environment ${VITE_ENVIRONMENT_NAMES.server} to be a RunnableDevEnvironment. This can be caused by multiple vite versions being installed in the project.`
33
+ );
26
34
  }
27
35
  if (cachedScripts === void 0) {
28
36
  const templateHtml = `<html><head></head><body></body></html>`;
@@ -1 +1 @@
1
- {"version":3,"file":"dev-server-plugin.js","sources":["../../../src/nitro/dev-server-plugin.ts"],"sourcesContent":["import { createEvent, getHeader, sendWebResponse } from 'h3'\nimport { isRunnableDevEnvironment } from 'vite'\nimport { extractHtmlScripts } from '../extractHtmlScripts'\nimport type { Connect, Plugin, ViteDevServer } from 'vite'\n\ndeclare global {\n // eslint-disable-next-line no-var\n var TSS_INJECTED_HEAD_SCRIPTS: string | undefined\n}\n\nexport function devServerPlugin(): Plugin {\n // let config: UserConfig\n let isTest = false\n\n return {\n name: 'start-dev-ssr-plugin',\n config(userConfig, { mode }) {\n // config = userConfig\n isTest = isTest ? isTest : mode === 'test'\n },\n configureServer(viteDevServer) {\n if (isTest) {\n return\n }\n\n ;(globalThis as any).viteDevServer = viteDevServer\n\n return () => {\n remove_html_middlewares(viteDevServer.middlewares)\n let cachedScripts: string | undefined\n viteDevServer.middlewares.use(async (req, res) => {\n const event = createEvent(req, res)\n const serverEnv = viteDevServer.environments['server']\n\n try {\n if (!serverEnv || !isRunnableDevEnvironment(serverEnv)) {\n throw new Error('Server environment not found')\n }\n if (cachedScripts === undefined) {\n const templateHtml = `<html><head></head><body></body></html>`\n const transformedHtml = await viteDevServer.transformIndexHtml(\n req.url || '/',\n templateHtml,\n )\n const scripts = extractHtmlScripts(transformedHtml)\n globalThis.TSS_INJECTED_HEAD_SCRIPTS = scripts\n .map((script) => script.content ?? '')\n .join(';')\n }\n const serverEntry = await serverEnv.runner.import(\n '/~start/server-entry',\n )\n const response = await serverEntry['default'](event)\n\n return sendWebResponse(event, response)\n } catch (e) {\n console.error(e)\n viteDevServer.ssrFixStacktrace(e as Error)\n\n if (\n getHeader(event, 'content-type')?.includes('application/json')\n ) {\n return sendWebResponse(\n event,\n new Response(\n JSON.stringify(\n {\n status: 500,\n error: 'Internal Server Error',\n message:\n 'An unexpected error occurred. Please try again later.',\n timestamp: new Date().toISOString(),\n },\n null,\n 2,\n ),\n {\n status: 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n },\n ),\n )\n }\n\n return sendWebResponse(\n event,\n new Response(\n `\n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <title>Error</title>\n <script type=\"module\">\n import { ErrorOverlay } from '/@vite/client'\n document.body.appendChild(new ErrorOverlay(${JSON.stringify(\n prepareError(req, e),\n ).replace(/</g, '\\\\u003c')}))\n </script>\n </head>\n <body>\n </body>\n </html>\n `,\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n },\n ),\n )\n }\n })\n }\n },\n }\n}\n\n/**\n * Removes Vite internal middleware\n *\n * @param server\n */\nfunction remove_html_middlewares(server: ViteDevServer['middlewares']) {\n const html_middlewares = [\n 'viteIndexHtmlMiddleware',\n 'vite404Middleware',\n 'viteSpaFallbackMiddleware',\n ]\n for (let i = server.stack.length - 1; i > 0; i--) {\n if (\n html_middlewares.includes(\n // @ts-expect-error\n server.stack[i].handle.name,\n )\n ) {\n server.stack.splice(i, 1)\n }\n }\n}\n\n/**\n * Formats error for SSR message in error overlay\n * @param req\n * @param error\n * @returns\n */\nfunction prepareError(req: Connect.IncomingMessage, error: unknown) {\n const e = error as Error\n return {\n message: `An error occured while server rendering ${req.url}:\\n\\n\\t${\n typeof e === 'string' ? e : e.message\n } `,\n stack: typeof e === 'string' ? '' : e.stack,\n }\n}\n"],"names":[],"mappings":";;;AAUO,SAAS,kBAA0B;AAExC,MAAI,SAAS;AAEN,SAAA;AAAA,IACL,MAAM;AAAA,IACN,OAAO,YAAY,EAAE,QAAQ;AAElB,eAAA,SAAS,SAAS,SAAS;AAAA,IACtC;AAAA,IACA,gBAAgB,eAAe;AAC7B,UAAI,QAAQ;AACV;AAAA,MAAA;AAGA,iBAAmB,gBAAgB;AAErC,aAAO,MAAM;AACX,gCAAwB,cAAc,WAAW;AAC7C,YAAA;AACJ,sBAAc,YAAY,IAAI,OAAO,KAAK,QAAQ;;AAC1C,gBAAA,QAAQ,YAAY,KAAK,GAAG;AAC5B,gBAAA,YAAY,cAAc,aAAa,QAAQ;AAEjD,cAAA;AACF,gBAAI,CAAC,aAAa,CAAC,yBAAyB,SAAS,GAAG;AAChD,oBAAA,IAAI,MAAM,8BAA8B;AAAA,YAAA;AAEhD,gBAAI,kBAAkB,QAAW;AAC/B,oBAAM,eAAe;AACf,oBAAA,kBAAkB,MAAM,cAAc;AAAA,gBAC1C,IAAI,OAAO;AAAA,gBACX;AAAA,cACF;AACM,oBAAA,UAAU,mBAAmB,eAAe;AACvC,yBAAA,4BAA4B,QACpC,IAAI,CAAC,WAAW,OAAO,WAAW,EAAE,EACpC,KAAK,GAAG;AAAA,YAAA;AAEP,kBAAA,cAAc,MAAM,UAAU,OAAO;AAAA,cACzC;AAAA,YACF;AACA,kBAAM,WAAW,MAAM,YAAY,SAAS,EAAE,KAAK;AAE5C,mBAAA,gBAAgB,OAAO,QAAQ;AAAA,mBAC/B,GAAG;AACV,oBAAQ,MAAM,CAAC;AACf,0BAAc,iBAAiB,CAAU;AAEzC,iBACE,eAAU,OAAO,c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O,MAAM,WAAW,IAAI,EAAE,OAChC;AAAA,IACA,OAAO,OAAO,MAAM,WAAW,KAAK,EAAE;AAAA,EACxC;AACF;"}
1
+ {"version":3,"file":"dev-server-plugin.js","sources":["../../../src/nitro/dev-server-plugin.ts"],"sourcesContent":["import { createEvent, getHeader, sendWebResponse } from 'h3'\nimport { isRunnableDevEnvironment } from 'vite'\nimport { extractHtmlScripts } from '../extractHtmlScripts'\nimport { VITE_ENVIRONMENT_NAMES } from '../constants'\nimport type { Connect, DevEnvironment, Plugin, ViteDevServer } from 'vite'\n\ndeclare global {\n // eslint-disable-next-line no-var\n var TSS_INJECTED_HEAD_SCRIPTS: string | undefined\n}\n\nexport function devServerPlugin(): Plugin {\n // let config: UserConfig\n let isTest = false\n\n return {\n name: 'start-dev-ssr-plugin',\n config(userConfig, { mode }) {\n // config = userConfig\n isTest = isTest ? isTest : mode === 'test'\n },\n configureServer(viteDevServer) {\n if (isTest) {\n return\n }\n\n ;(globalThis as any).viteDevServer = viteDevServer\n\n return () => {\n remove_html_middlewares(viteDevServer.middlewares)\n let cachedScripts: string | undefined\n viteDevServer.middlewares.use(async (req, res) => {\n const event = createEvent(req, res)\n const serverEnv = viteDevServer.environments[\n VITE_ENVIRONMENT_NAMES.server\n ] as DevEnvironment | undefined\n\n try {\n if (!serverEnv) {\n throw new Error(\n `Server environment ${VITE_ENVIRONMENT_NAMES.server} not found`,\n )\n }\n if (!isRunnableDevEnvironment(serverEnv)) {\n throw new Error(\n `Expected server environment ${VITE_ENVIRONMENT_NAMES.server} to be a RunnableDevEnvironment. This can be caused by multiple vite versions being installed in the project.`,\n )\n }\n if (cachedScripts === undefined) {\n const templateHtml = `<html><head></head><body></body></html>`\n const transformedHtml = await viteDevServer.transformIndexHtml(\n req.url || '/',\n templateHtml,\n )\n const scripts = extractHtmlScripts(transformedHtml)\n globalThis.TSS_INJECTED_HEAD_SCRIPTS = scripts\n .map((script) => script.content ?? '')\n .join(';')\n }\n const serverEntry = await serverEnv.runner.import(\n '/~start/server-entry',\n )\n const response = await serverEntry['default'](event)\n\n return sendWebResponse(event, response)\n } catch (e) {\n console.error(e)\n viteDevServer.ssrFixStacktrace(e as Error)\n\n if (\n getHeader(event, 'content-type')?.includes('application/json')\n ) {\n return sendWebResponse(\n event,\n new Response(\n JSON.stringify(\n {\n status: 500,\n error: 'Internal Server Error',\n message:\n 'An unexpected error occurred. Please try again later.',\n timestamp: new Date().toISOString(),\n },\n null,\n 2,\n ),\n {\n status: 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n },\n ),\n )\n }\n\n return sendWebResponse(\n event,\n new Response(\n `\n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <title>Error</title>\n <script type=\"module\">\n import { ErrorOverlay } from '/@vite/client'\n document.body.appendChild(new ErrorOverlay(${JSON.stringify(\n prepareError(req, e),\n ).replace(/</g, '\\\\u003c')}))\n </script>\n </head>\n <body>\n </body>\n </html>\n `,\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n },\n ),\n )\n }\n })\n }\n },\n }\n}\n\n/**\n * Removes Vite internal middleware\n *\n * @param server\n */\nfunction remove_html_middlewares(server: ViteDevServer['middlewares']) {\n const html_middlewares = [\n 'viteIndexHtmlMiddleware',\n 'vite404Middleware',\n 'viteSpaFallbackMiddleware',\n ]\n for (let i = server.stack.length - 1; i > 0; i--) {\n if (\n html_middlewares.includes(\n // @ts-expect-error\n server.stack[i].handle.name,\n )\n ) {\n server.stack.splice(i, 1)\n }\n }\n}\n\n/**\n * Formats error for SSR message in error overlay\n * @param req\n * @param error\n * @returns\n */\nfunction prepareError(req: Connect.IncomingMessage, error: unknown) {\n const e = error as Error\n return {\n message: `An error occured while server rendering ${req.url}:\\n\\n\\t${\n typeof e === 'string' ? e : e.message\n } `,\n stack: typeof e === 'string' ? '' : e.stack,\n }\n}\n"],"names":[],"mappings":";;;;AAWO,SAAS,kBAA0B;AAExC,MAAI,SAAS;AAEN,SAAA;AA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itropack";
4
4
  import { resolve, dirname } from "pathe";
5
5
  import { clientDistDir, ssrEntryFile } from "../plugin.js";
6
6
  import { prerender } from "../prerender.js";
7
+ import { VITE_ENVIRONMENT_NAMES } from "../constants.js";
7
8
  import { devServerPlugin } from "./dev-server-plugin.js";
8
9
  import { buildNitroEnvironment } from "./build-nitro.js";
9
10
  function nitroPlugin(options, getSsrBundle) {
@@ -13,7 +14,7 @@ function nitroPlugin(options, getSsrBundle) {
13
14
  {
14
15
  name: "tanstack-vite-plugin-nitro",
15
16
  configEnvironment(name) {
16
- if (name === "server") {
17
+ if (name === VITE_ENVIRONMENT_NAMES.server) {
17
18
  return {
18
19
  build: {
19
20
  commonjsOptions: {
@@ -35,8 +36,8 @@ function nitroPlugin(options, getSsrBundle) {
35
36
  sharedPlugins: true,
36
37
  async buildApp(builder) {
37
38
  var _a, _b, _c;
38
- const clientEnv = builder.environments["client"];
39
- const serverEnv = builder.environments["server"];
39
+ const clientEnv = builder.environments[VITE_ENVIRONMENT_NAMES.client];
40
+ const serverEnv = builder.environments[VITE_ENVIRONMENT_NAMES.server];
40
41
  if (!clientEnv) {
41
42
  throw new Error("Client environment not found");
42
43
  }
@@ -1 +1 @@
1
- {"version":3,"file":"nitro-plugin.js","sources":["../../../src/nitro/nitro-plugin.ts"],"sourcesContent":["import path from 'node:path'\nimport { rmSync } from 'node:fs'\nimport { build, createNitro } from 'nitropack'\nimport { dirname, resolve } from 'pathe'\nimport { clientDistDir, ssrEntryFile } from '../plugin'\nimport { prerender } from '../prerender'\nimport { devServerPlugin } from './dev-server-plugin'\nimport { buildNitroEnvironment } from './build-nitro'\nimport type { EnvironmentOptions, PluginOption, Rollup } from 'vite'\nimport type { 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\n return [\n devServerPlugin(),\n {\n name: 'tanstack-vite-plugin-nitro',\n configEnvironment(name) {\n if (name === '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 clientEnv = builder.environments['client']\n const serverEnv = builder.environments['server']\n\n if (!clientEnv) {\n throw new Error('Client environment not found')\n }\n\n if (!serverEnv) {\n throw new Error('SSR environment not found')\n }\n\n const clientOutputDir = resolve(options.root, clientDistDir)\n rmSync(clientOutputDir, { recursive: true, force: true })\n await builder.build(clientEnv)\n\n await builder.build(serverEnv)\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 publicAssets: [\n {\n dir: path.resolve(options.root, clientDistDir),\n },\n ],\n typescript: {\n generateTsConfig: false,\n },\n prerender: undefined,\n renderer: ssrEntryFile,\n rollupConfig: {\n plugins: [virtualBundlePlugin(getSsrBundle())],\n },\n routeRules: {\n // TODO: We need to expose *some* kind of routeRules configuration\n // and it needs to translate to this for now. But we should\n // be cognizant of the probability that we will not use Nitro's\n // routeRules configuration in the future.\n ...(options.shell?.enabled && options.shell.autoRedirect\n ? {\n '/**': {\n // @ts-expect-error We are using this as a marker\n __TSS_SHELL: true,\n redirect: {\n to: `${options.shell.prerender.outputPath.replace(/[/]{1,}$/, '')}`,\n statusCode: 200,\n },\n },\n }\n : {}),\n },\n }\n\n const nitro = await createNitro(nitroConfig)\n\n await buildNitroEnvironment(nitro, () => build(nitro))\n\n if (options.shell?.enabled) {\n options.prerender = {\n ...options.prerender,\n enabled: true,\n }\n\n const maskUrl = new URL(\n options.shell.maskPath,\n 'http://localhost',\n )\n\n maskUrl.searchParams.set('__TSS_SHELL', 'true')\n\n options.pages.push({\n path: maskUrl.toString().replace('http://localhost', ''),\n prerender: options.shell.prerender,\n sitemap: {\n exclude: true,\n },\n })\n }\n\n if (options.prerender?.enabled) {\n await prerender({\n options,\n nitro,\n builder,\n })\n }\n\n // if (nitroConfig.prerender?.routes?.length && options.sitemap) {\n // console.log('Building Sitemap...')\n // // sitemap needs to be built after all directories are built\n // await buildSitemap({\n // host: options.sitemap.host,\n // routes: nitroConfig.prerender.routes,\n // outputDir: resolve(options.root, 'dist/public'),\n // })\n // }\n\n // console.log(\n // `\\n\\n✅ Client and server bundles successfully built.`,\n // )\n },\n },\n }\n },\n },\n ]\n}\n\nfunction virtualBundlePlugin(ssrBundle: Rollup.OutputBundle): Rollup.Plugin {\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":[],"mappings":";;;;;;;;AAYgB,SAAA,YACd,SACA,cACqB;AACrB,QAAM,cACJ,QAAQ,IAAI,cAAc,KAAM,QAAQ;AAEnC,SAAA;AAAA,IACL,gBAAgB;AAAA,IAChB;AAAA,MACE,MAAM;AAAA,MACN,kBAAkB,MAAM;AACtB,YAAI,SAAS,UAAU;AACd,iBAAA;AAAA,YACL,OAAO;AAAA,cACL,iBAAiB;AAAA,gBACf,SAAS,CAAA;AAAA,c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AQ,QAAQ,GAAG,aAAa;AAAA,IAAA;AAAA,EAC/C;AAGK,SAAA;AAAA,IACL,MAAM;AAAA,IACN,UAAU,IAAI,UAAU;AAClB,UAAA,SAAS,IAAI,EAAE,GAAG;AACpB,eAAO,QAAQ,EAAE;AAAA,MAAA;AAGnB,UAAI,UAAU;AACZ,cAAM,WAAW,QAAQ,QAAQ,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":"nitro-plugin.js","sources":["../../../src/nitro/nitro-plugin.ts"],"sourcesContent":["import path from 'node:path'\nimport { rmSync } from 'node:fs'\nimport { build, createNitro } from 'nitropack'\nimport { dirname, resolve } from 'pathe'\nimport { clientDistDir, ssrEntryFile } from '../plugin'\nimport { prerender } from '../prerender'\nimport { VITE_ENVIRONMENT_NAMES } from '../constants'\nimport { devServerPlugin } from './dev-server-plugin'\nimport { buildNitroEnvironment } from './build-nitro'\nimport type { EnvironmentOptions, PluginOption, Rollup } from 'vite'\nimport type { 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\n return [\n devServerPlugin(),\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 clientEnv =\n builder.environments[VITE_ENVIRONMENT_NAMES.client]\n const serverEnv =\n builder.environments[VITE_ENVIRONMENT_NAMES.server]\n\n if (!clientEnv) {\n throw new Error('Client environment not found')\n }\n\n if (!serverEnv) {\n throw new Error('SSR environment not found')\n }\n\n const clientOutputDir = resolve(options.root, clientDistDir)\n rmSync(clientOutputDir, { recursive: true, force: true })\n await builder.build(clientEnv)\n\n await builder.build(serverEnv)\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 publicAssets: [\n {\n dir: path.resolve(options.root, clientDistDir),\n },\n ],\n typescript: {\n generateTsConfig: false,\n },\n prerender: undefined,\n renderer: ssrEntryFile,\n rollupConfig: {\n plugins: [virtualBundlePlugin(getSsrBundle())],\n },\n routeRules: {\n // TODO: We need to expose *some* kind of routeRules configuration\n // and it needs to translate to this for now. But we should\n // be cognizant of the probability that we will not use Nitro's\n // routeRules configuration in the future.\n ...(options.shell?.enabled && options.shell.autoRedirect\n ? {\n '/**': {\n // @ts-expect-error We are using this as a marker\n __TSS_SHELL: true,\n redirect: {\n to: `${options.shell.prerender.outputPath.replace(/[/]{1,}$/, '')}`,\n statusCode: 200,\n },\n },\n }\n : {}),\n },\n }\n\n const nitro = await createNitro(nitroConfig)\n\n await buildNitroEnvironment(nitro, () => build(nitro))\n\n if (options.shell?.enabled) {\n options.prerender = {\n ...options.prerender,\n enabled: true,\n }\n\n const maskUrl = new URL(\n options.shell.maskPath,\n 'http://localhost',\n )\n\n maskUrl.searchParams.set('__TSS_SHELL', 'true')\n\n options.pages.push({\n path: maskUrl.toString().replace('http://localhost', ''),\n prerender: options.shell.prerender,\n sitemap: {\n exclude: true,\n },\n })\n }\n\n if (options.prerender?.enabled) {\n await prerender({\n options,\n nitro,\n builder,\n })\n }\n\n // if (nitroConfig.prerender?.routes?.length && options.sitemap) {\n // console.log('Building Sitemap...')\n // // sitemap needs to be built after all directories are built\n // await buildSitemap({\n // host: options.sitemap.host,\n // routes: nitroConfig.prerender.routes,\n // outputDir: resolve(options.root, 'dist/public'),\n // })\n // }\n\n // console.log(\n // `\\n\\n✅ Client and server bundles successfully built.`,\n // )\n },\n },\n }\n },\n },\n ]\n}\n\nfunction virtualBundlePlugin(ssrBundle: Rollup.OutputBundle): Rollup.Plugin {\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":[],"mappings":";;;;;;;;;AAagB,SAAA,YACd,SACA,cACqB;AACrB,QAAM,cACJ,QAAQ,IAAI,cAAc,KAAM,QAAQ;AAEnC,SAAA;AAAA,IACL,gBAAgB;AAAA,IAChB;AAAA,MACE,MAAM;AAAA,MACN,kBAAkB,MAAM;AAClB,YAAA,SAAS,uBAAuB,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,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,UAAA,SAAS,IAAI,EAAE,GAAG;AACpB,eAAO,QAAQ,EAAE;AAAA,MAAA;AAGnB,UAAI,UAAU;AACZ,cAAM,WAAW,QAAQ,QAAQ,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;"}
@@ -3331,5 +3331,8 @@ export declare function getTanStackStartOptions(opts?: TanStackStartInputConfig)
3331
3331
  export type TanStackStartOutputConfig = ReturnType<typeof getTanStackStartOptions>;
3332
3332
  export declare const clientDistDir = ".tanstack-start/build/client-dist";
3333
3333
  export declare const ssrEntryFile = "ssr.mjs";
3334
- export declare function TanStackStartVitePluginCore(framework: CompileStartFrameworkOptions, opts: TanStackStartOutputConfig): Array<PluginOption>;
3334
+ export interface TanStackStartVitePluginCoreOptions {
3335
+ framework: CompileStartFrameworkOptions;
3336
+ }
3337
+ export declare function TanStackStartVitePluginCore(opts: TanStackStartVitePluginCoreOptions, startConfig: TanStackStartOutputConfig): Array<PluginOption>;
3335
3338
  export {};
@@ -1,22 +1,24 @@
1
1
  import path from "node:path";
2
2
  import { createNitro } from "nitropack";
3
+ import { TanStackServerFnPluginEnv } from "@tanstack/server-functions-plugin";
3
4
  import { createTanStackStartOptionsSchema, createTanStackConfig } from "./schema.js";
4
5
  import { nitroPlugin } from "./nitro/nitro-plugin.js";
5
6
  import { startManifestPlugin } from "./routesManifestPlugin.js";
6
7
  import { TanStackStartCompilerPlugin } from "./start-compiler-plugin.js";
8
+ import { VITE_ENVIRONMENT_NAMES } from "./constants.js";
7
9
  createTanStackStartOptionsSchema();
8
10
  createTanStackConfig();
9
11
  const clientDistDir = ".tanstack-start/build/client-dist";
10
12
  const ssrEntryFile = "ssr.mjs";
11
13
  let ssrBundle;
12
- function TanStackStartVitePluginCore(framework, opts) {
14
+ function TanStackStartVitePluginCore(opts, startConfig) {
13
15
  return [
14
16
  {
15
17
  name: "tanstack-start-core:config-client",
16
18
  async config() {
17
19
  const nitroOutputPublicDir = await (async () => {
18
20
  const dummyNitroApp = await createNitro({
19
- preset: opts.target,
21
+ preset: startConfig.target,
20
22
  compatibilityDate: "2024-12-01"
21
23
  });
22
24
  const nitroOutputPublicDir2 = dummyNitroApp.options.output.publicDir;
@@ -25,23 +27,23 @@ function TanStackStartVitePluginCore(framework, opts) {
25
27
  })();
26
28
  return {
27
29
  environments: {
28
- client: {
30
+ [VITE_ENVIRONMENT_NAMES.client]: {
29
31
  consumer: "client",
30
32
  build: {
31
33
  manifest: true,
32
34
  rollupOptions: {
33
35
  input: {
34
- main: opts.clientEntryPath
36
+ main: startConfig.clientEntryPath
35
37
  },
36
38
  output: {
37
- dir: path.resolve(opts.root, clientDistDir)
39
+ dir: path.resolve(startConfig.root, clientDistDir)
38
40
  },
39
41
  // TODO this should be removed
40
42
  external: ["node:fs", "node:path", "node:os", "node:crypto"]
41
43
  }
42
44
  }
43
45
  },
44
- server: {
46
+ [VITE_ENVIRONMENT_NAMES.server]: {
45
47
  consumer: "server",
46
48
  build: {
47
49
  ssr: true,
@@ -88,18 +90,44 @@ function TanStackStartVitePluginCore(framework, opts) {
88
90
  },
89
91
  /* prettier-ignore */
90
92
  define: {
91
- ...injectDefineEnv("TSS_PUBLIC_BASE", opts.public.base),
92
- ...injectDefineEnv("TSS_CLIENT_BASE", opts.client.base),
93
- ...injectDefineEnv("TSS_CLIENT_ENTRY", opts.clientEntryPath),
94
- ...injectDefineEnv("TSS_SERVER_FN_BASE", opts.serverFns.base),
93
+ ...injectDefineEnv("TSS_PUBLIC_BASE", startConfig.public.base),
94
+ ...injectDefineEnv("TSS_CLIENT_BASE", startConfig.client.base),
95
+ ...injectDefineEnv("TSS_CLIENT_ENTRY", startConfig.clientEntryPath),
96
+ ...injectDefineEnv("TSS_SERVER_FN_BASE", startConfig.serverFns.base),
95
97
  ...injectDefineEnv("TSS_OUTPUT_PUBLIC_DIR", nitroOutputPublicDir)
96
98
  }
97
99
  };
98
100
  }
99
101
  },
100
- TanStackStartCompilerPlugin(framework),
101
- startManifestPlugin(opts),
102
- nitroPlugin(opts, () => ssrBundle)
102
+ // N.B. TanStackStartCompilerPlugin must be before the TanStackServerFnPluginEnv
103
+ TanStackStartCompilerPlugin(opts.framework, {
104
+ client: { envName: VITE_ENVIRONMENT_NAMES.client },
105
+ server: { envName: VITE_ENVIRONMENT_NAMES.server }
106
+ }),
107
+ TanStackServerFnPluginEnv({
108
+ // This is the ID that will be available to look up and import
109
+ // our server function manifest and resolve its module
110
+ manifestVirtualImportId: "tanstack:server-fn-manifest",
111
+ client: {
112
+ getRuntimeCode: () => `import { createClientRpc } from '@tanstack/${opts.framework}-start/server-functions-client'`,
113
+ replacer: (d) => `createClientRpc('${d.functionId}', '${startConfig.serverFns.base}')`,
114
+ envName: VITE_ENVIRONMENT_NAMES.client
115
+ },
116
+ server: {
117
+ getRuntimeCode: () => `import { createServerRpc } from '@tanstack/${opts.framework}-start/server-functions-server'`,
118
+ replacer: (d) => `createServerRpc('${d.functionId}', '${startConfig.serverFns.base}', ${d.fn})`,
119
+ envName: VITE_ENVIRONMENT_NAMES.server
120
+ },
121
+ importer: (fn) => {
122
+ const serverEnv = globalThis.viteDevServer.environments[VITE_ENVIRONMENT_NAMES.server];
123
+ if (!serverEnv) {
124
+ throw new Error(`'ssr' vite dev environment not found`);
125
+ }
126
+ return serverEnv.runner.import(fn.extractedFilename);
127
+ }
128
+ }),
129
+ startManifestPlugin(startConfig),
130
+ nitroPlugin(startConfig, () => ssrBundle)
103
131
  ];
104
132
  }
105
133
  function injectDefineEnv(key, value) {
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.js","sources":["../../src/plugin.ts"],"sourcesContent":["import path from 'node:path'\nimport { createNitro } from 'nitropack'\nimport {\n createTanStackConfig,\n createTanStackStartOptionsSchema,\n} from './schema'\nimport { nitroPlugin } from './nitro/nitro-plugin'\nimport { startManifestPlugin } from './routesManifestPlugin'\nimport { TanStackStartCompilerPlugin } from './start-compiler-plugin'\nimport type { PluginOption, Rollup } from 'vite'\nimport type { z } from 'zod'\nimport type { CompileStartFrameworkOptions } from './compilers'\n\nconst TanStackStartOptionsSchema = createTanStackStartOptionsSchema()\nexport type TanStackStartInputConfig = z.input<\n typeof TanStackStartOptionsSchema\n>\n\nconst defaultConfig = createTanStackConfig()\nexport function getTanStackStartOptions(opts?: TanStackStartInputConfig) {\n return defaultConfig.parse(opts)\n}\n\nexport type TanStackStartOutputConfig = ReturnType<\n typeof getTanStackStartOptions\n>\n\nexport const clientDistDir = '.tanstack-start/build/client-dist'\nexport const ssrEntryFile = 'ssr.mjs'\n\n// this needs to live outside of the TanStackStartVitePluginCore since it will be invoked multiple times by vite\nlet ssrBundle: Rollup.OutputBundle\n\nexport function TanStackStartVitePluginCore(\n framework: CompileStartFrameworkOptions,\n opts: TanStackStartOutputConfig,\n): Array<PluginOption> {\n return [\n {\n name: 'tanstack-start-core:config-client',\n async config() {\n const nitroOutputPublicDir = await (async () => {\n // Create a dummy nitro app to get the resolved public output path\n const dummyNitroApp = await createNitro({\n preset: opts.target,\n compatibilityDate: '2024-12-01',\n })\n\n const nitroOutputPublicDir = dummyNitroApp.options.output.publicDir\n await dummyNitroApp.close()\n\n return nitroOutputPublicDir\n })()\n\n return {\n environments: {\n client: {\n consumer: 'client',\n build: {\n manifest: true,\n rollupOptions: {\n input: {\n main: opts.clientEntryPath,\n },\n output: {\n dir: path.resolve(opts.root, clientDistDir),\n },\n // TODO this should be removed\n external: ['node:fs', 'node:path', 'node:os', 'node:crypto'],\n },\n },\n },\n server: {\n consumer: 'server',\n build: {\n ssr: true,\n // we don't write to the file system as the below 'capture-output' plugin will\n // capture the output and write it to the virtual file system\n write: false,\n copyPublicDir: false,\n rollupOptions: {\n output: {\n entryFileNames: ssrEntryFile,\n },\n plugins: [\n {\n name: 'capture-output',\n generateBundle(options, bundle) {\n // TODO can this hook be called more than once?\n ssrBundle = bundle\n },\n },\n ],\n },\n commonjsOptions: {\n include: [/node_modules/],\n },\n },\n },\n },\n resolve: {\n noExternal: [\n '@tanstack/start-client',\n '@tanstack/start-client-core',\n '@tanstack/start-server',\n '@tanstack/start-server-core',\n '@tanstack/start-server-functions-fetcher',\n '@tanstack/start-server-functions-client',\n '@tanstack/start-server-functions-server',\n '@tanstack/start-router-manifest',\n '@tanstack/start-config',\n '@tanstack/server-functions-plugin',\n 'tanstack:start-manifest',\n 'tanstack:server-fn-manifest',\n 'nitropack',\n '@tanstack/**',\n ],\n },\n /* prettier-ignore */\n define: {\n ...injectDefineEnv('TSS_PUBLIC_BASE', opts.public.base),\n ...injectDefineEnv('TSS_CLIENT_BASE', opts.client.base),\n ...injectDefineEnv('TSS_CLIENT_ENTRY', opts.clientEntryPath),\n ...injectDefineEnv('TSS_SERVER_FN_BASE', opts.serverFns.base),\n ...injectDefineEnv('TSS_OUTPUT_PUBLIC_DIR', nitroOutputPublicDir),\n },\n }\n },\n },\n TanStackStartCompilerPlugin(framework),\n startManifestPlugin(opts),\n nitroPlugin(opts, () => ssrBundle),\n ]\n}\n\nfunction injectDefineEnv<TKey extends string, TValue extends string>(\n key: TKey,\n value: TValue,\n): { [P in `process.env.${TKey}` | `import.meta.env.${TKey}`]: TValue } {\n return {\n [`process.env.${key}`]: JSON.stringify(value),\n [`import.meta.env.${key}`]: JSON.stringify(value),\n } as { [P in `process.env.${TKey}` | `import.meta.env.${TKey}`]: TValue }\n}\n"],"names":["nitroOutputPublicDir"],"mappings":";;;;;;AAamC,iCAAiC;AAK9C,qBAAqB;AASpC,MAAM,gBAAgB;AACtB,MAAM,eAAe;AAG5B,IAAI;AAEY,SAAA,4BACd,WACA,MACqB;AACd,SAAA;AAAA,IACL;AAAA,MACE,MAAM;AAAA,MACN,MAAM,SAAS;AAC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;AAAA,UAEA,QAAQ;AAAA,YACN,GAAG,gBAAgB,mBAAmB,KAAK,OAAO,IAAI;AAAA,YACtD,GAAG,gBAAgB,mBAAmB,KAAK,OAAO,IAAI;AAAA,YACtD,GAAG,gBAAgB,oBAAoB,KAAK,eAAe;AAAA,YAC3D,GAAG,gBAAgB,sBAAsB,KAAK,UAAU,IAAI;AAAA,YAC5D,GAAG,gBAAgB,yBAAyB,oBAAoB;AAAA,UAAA;AAAA,QAEpE;AAAA,MAAA;AAAA,IAEJ;AAAA,IACA,4BAA4B,SAAS;AAAA,IACrC,oBAAoB,IAAI;AAAA,IACxB,YAAY,MAAM,MAAM,SAAS;AAAA,EACnC;AACF;AAEA,SAAS,gBACP,KACA,OACsE;AAC/D,SAAA;AAAA,IACL,CAAC,eAAe,GAAG,EAAE,GAAG,KAAK,UAAU,KAAK;AAAA,IAC5C,CAAC,mBAAmB,GAAG,EAAE,GAAG,KAAK,UAAU,KAAK;AAAA,EAClD;AACF;"}
1
+ {"version":3,"file":"plugin.js","sources":["../../src/plugin.ts"],"sourcesContent":["import path from 'node:path'\nimport { createNitro } from 'nitropack'\nimport { TanStackServerFnPluginEnv } from '@tanstack/server-functions-plugin'\nimport {\n createTanStackConfig,\n createTanStackStartOptionsSchema,\n} from './schema'\nimport { nitroPlugin } from './nitro/nitro-plugin'\nimport { startManifestPlugin } from './routesManifestPlugin'\nimport { TanStackStartCompilerPlugin } from './start-compiler-plugin'\nimport { VITE_ENVIRONMENT_NAMES } from './constants'\nimport type { PluginOption, Rollup } from 'vite'\nimport type { z } from 'zod'\nimport type { CompileStartFrameworkOptions } from './compilers'\n\nconst TanStackStartOptionsSchema = createTanStackStartOptionsSchema()\nexport type TanStackStartInputConfig = z.input<\n typeof TanStackStartOptionsSchema\n>\n\nconst defaultConfig = createTanStackConfig()\nexport function getTanStackStartOptions(opts?: TanStackStartInputConfig) {\n return defaultConfig.parse(opts)\n}\n\nexport type TanStackStartOutputConfig = ReturnType<\n typeof getTanStackStartOptions\n>\n\nexport const clientDistDir = '.tanstack-start/build/client-dist'\nexport const ssrEntryFile = 'ssr.mjs'\n\nexport interface TanStackStartVitePluginCoreOptions {\n framework: CompileStartFrameworkOptions\n}\n// this needs to live outside of the TanStackStartVitePluginCore since it will be invoked multiple times by vite\nlet ssrBundle: Rollup.OutputBundle\n\nexport function TanStackStartVitePluginCore(\n opts: TanStackStartVitePluginCoreOptions,\n startConfig: TanStackStartOutputConfig,\n): Array<PluginOption> {\n return [\n {\n name: 'tanstack-start-core:config-client',\n async config() {\n const nitroOutputPublicDir = await (async () => {\n // Create a dummy nitro app to get the resolved public output path\n const dummyNitroApp = await createNitro({\n preset: startConfig.target,\n compatibilityDate: '2024-12-01',\n })\n\n const nitroOutputPublicDir = dummyNitroApp.options.output.publicDir\n await dummyNitroApp.close()\n\n return nitroOutputPublicDir\n })()\n\n return {\n environments: {\n [VITE_ENVIRONMENT_NAMES.client]: {\n consumer: 'client',\n build: {\n manifest: true,\n rollupOptions: {\n input: {\n main: startConfig.clientEntryPath,\n },\n output: {\n dir: path.resolve(startConfig.root, clientDistDir),\n },\n // TODO this should be removed\n external: ['node:fs', 'node:path', 'node:os', 'node:crypto'],\n },\n },\n },\n [VITE_ENVIRONMENT_NAMES.server]: {\n consumer: 'server',\n build: {\n ssr: true,\n // we don't write to the file system as the below 'capture-output' plugin will\n // capture the output and write it to the virtual file system\n write: false,\n copyPublicDir: false,\n rollupOptions: {\n output: {\n entryFileNames: ssrEntryFile,\n },\n plugins: [\n {\n name: 'capture-output',\n generateBundle(options, bundle) {\n // TODO can this hook be called more than once?\n ssrBundle = bundle\n },\n },\n ],\n },\n commonjsOptions: {\n include: [/node_modules/],\n },\n },\n },\n },\n resolve: {\n noExternal: [\n '@tanstack/start-client',\n '@tanstack/start-client-core',\n '@tanstack/start-server',\n '@tanstack/start-server-core',\n '@tanstack/start-server-functions-fetcher',\n '@tanstack/start-server-functions-client',\n '@tanstack/start-server-functions-server',\n '@tanstack/start-router-manifest',\n '@tanstack/start-config',\n '@tanstack/server-functions-plugin',\n 'tanstack:start-manifest',\n 'tanstack:server-fn-manifest',\n 'nitropack',\n '@tanstack/**',\n ],\n },\n /* prettier-ignore */\n define: {\n ...injectDefineEnv('TSS_PUBLIC_BASE', startConfig.public.base),\n ...injectDefineEnv('TSS_CLIENT_BASE', startConfig.client.base),\n ...injectDefineEnv('TSS_CLIENT_ENTRY', startConfig.clientEntryPath),\n ...injectDefineEnv('TSS_SERVER_FN_BASE', startConfig.serverFns.base),\n ...injectDefineEnv('TSS_OUTPUT_PUBLIC_DIR', nitroOutputPublicDir),\n },\n }\n },\n },\n // N.B. TanStackStartCompilerPlugin must be before the TanStackServerFnPluginEnv\n TanStackStartCompilerPlugin(opts.framework, {\n client: { envName: VITE_ENVIRONMENT_NAMES.client },\n server: { envName: VITE_ENVIRONMENT_NAMES.server },\n }),\n TanStackServerFnPluginEnv({\n // This is the ID that will be available to look up and import\n // our server function manifest and resolve its module\n manifestVirtualImportId: 'tanstack:server-fn-manifest',\n client: {\n getRuntimeCode: () =>\n `import { createClientRpc } from '@tanstack/${opts.framework}-start/server-functions-client'`,\n replacer: (d) =>\n `createClientRpc('${d.functionId}', '${startConfig.serverFns.base}')`,\n envName: VITE_ENVIRONMENT_NAMES.client,\n },\n server: {\n getRuntimeCode: () =>\n `import { createServerRpc } from '@tanstack/${opts.framework}-start/server-functions-server'`,\n replacer: (d) =>\n `createServerRpc('${d.functionId}', '${startConfig.serverFns.base}', ${d.fn})`,\n envName: VITE_ENVIRONMENT_NAMES.server,\n },\n importer: (fn) => {\n const serverEnv = (globalThis as any).viteDevServer.environments[\n VITE_ENVIRONMENT_NAMES.server\n ]\n if (!serverEnv) {\n throw new Error(`'ssr' vite dev environment not found`)\n }\n return serverEnv.runner.import(fn.extractedFilename)\n },\n }),\n startManifestPlugin(startConfig),\n nitroPlugin(startConfig, () => ssrBundle),\n ]\n}\n\nfunction injectDefineEnv<TKey extends string, TValue extends string>(\n key: TKey,\n value: TValue,\n): { [P in `process.env.${TKey}` | `import.meta.env.${TKey}`]: TValue } {\n return {\n [`process.env.${key}`]: JSON.stringify(value),\n [`import.meta.env.${key}`]: JSON.stringify(value),\n } as { [P in `process.env.${TKey}` | `import.meta.env.${TKey}`]: TValue }\n}\n"],"names":["nitroOutputPublicDir"],"mappings":";;;;;;;;AAemC,iCAAiC;AAK9C,qBAAqB;AASpC,MAAM,gBAAgB;AACtB,MAAM,eAAe;AAM5B,IAAI;AAEY,SAAA,4BACd,MACA,aACqB;AACd,SAAA;AAAA,IACL;AAAA,MACE,MAAM;AAAA,MACN,MAAM,SAAS;AACP,cAAA,uBAAuB,OAAO,YAAY;AAExC,gBAAA,gBAAgB,MAAM,YAAY;AAAA,YACtC,QAAQ,YAAY;AAAA,YACpB,mBAAmB;AAAA,UAAA,CACpB;AAEKA,gBAAAA,wBAAuB,cAAc,QAAQ,OAAO;AAC1D,gBAAM,cAAc,MAAM;AAEnBA,iBAAAA;AAAAA,QAAAA,GACN;AAEI,eAAA;AAAA,UACL,cAAc;AAAA,YACZ,CAAC,uBAAuB,MAAM,GAAG;AAAA,cAC/B,UAAU;AAAA,cACV,OAAO;AAAA,gBACL,UAAU;AAAA,gBACV,eAAe;AAAA,kBACb,OAAO;AAAA,oBACL,MAAM,YAAY;AAAA,kBACpB;AAAA,kBACA,QAAQ;AAAA,oBACN,KAAK,KAAK,QAAQ,YAAY,MAAM,aAAa;AAAA,kBACnD;AAAA;AAAA,kBAEA,UAAU,CAAC,WAAW,aAAa,WAAW,aAAa;AAAA,gBAAA;AAAA,cAC7D;AAAA,YAEJ;AAAA,YACA,CAAC,uBAAuB,MAAM,GAAG;AAAA,cAC/B,UAAU;AAAA,cACV,OAAO;AAAA,gBACL,KAAK;AAAA;AAAA;AAAA,gBAGL,OAAO;AAAA,gBACP,eAAe;AAAA,gBACf,eAAe;AAAA,kBACb,QAAQ;AAAA,oBACN,gBAAgB;AAAA,kBAClB;AAAA,kBACA,SAAS;AAAA,oBACP;AAA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E,UAAU,OAAO,YAAY,UAAU,IAAI,MAAM,EAAE,EAAE;AAAA,QAC7E,SAAS,uBAAuB;AAAA,MAClC;AAAA,MACA,UAAU,CAAC,OAAO;AAChB,cAAM,YAAa,WAAmB,cAAc,aAClD,uBAAuB,MACzB;AACA,YAAI,CAAC,WAAW;AACR,gBAAA,IAAI,MAAM,sCAAsC;AAAA,QAAA;AAExD,eAAO,UAAU,OAAO,OAAO,GAAG,iBAAiB;AAAA,MAAA;AAAA,IACrD,CACD;AAAA,IACD,oBAAoB,WAAW;AAAA,IAC/B,YAAY,aAAa,MAAM,SAAS;AAAA,EAC1C;AACF;AAEA,SAAS,gBACP,KACA,OACsE;AAC/D,SAAA;AAAA,IACL,CAAC,eAAe,GAAG,EAAE,GAAG,KAAK,UAAU,KAAK;AAAA,IAC5C,CAAC,mBAAmB,GAAG,EAAE,GAAG,KAAK,UAAU,KAAK;AAAA,EAClD;AACF;"}
@@ -6,6 +6,7 @@ import { createNitro, build } from "nitropack";
6
6
  import { withBase, joinURL, withoutBase } from "ufo";
7
7
  import { Queue } from "./queue.js";
8
8
  import { buildNitroEnvironment } from "./nitro/build-nitro.js";
9
+ import { VITE_ENVIRONMENT_NAMES } from "./constants.js";
9
10
  async function prerender({
10
11
  options,
11
12
  nitro,
@@ -20,9 +21,11 @@ async function prerender({
20
21
  }
21
22
  ];
22
23
  }
23
- const serverEnv = builder.environments["server"];
24
+ const serverEnv = builder.environments[VITE_ENVIRONMENT_NAMES.server];
24
25
  if (!serverEnv) {
25
- throw new Error(`Vite's "server" environment not found`);
26
+ throw new Error(
27
+ `Vite's "${VITE_ENVIRONMENT_NAMES.server}" environment not found`
28
+ );
26
29
  }
27
30
  const prerenderOutputDir = path.resolve(
28
31
  options.root,
@@ -1 +1 @@
1
- {"version":3,"file":"prerender.js","sources":["../../src/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 { Queue } from './queue'\nimport { buildNitroEnvironment } from './nitro/build-nitro'\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 console.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['server']\n\n if (!serverEnv) {\n throw new Error(`Vite's \"server\" environment not found`)\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 routeRules: {\n // Filter out our shell redirect rule if it exists\n ...Object.fromEntries(\n Object.entries(nitro.options._config.routeRules ?? {}).filter(\n ([_, value]) => !(value as any).__TSS_SHELL,\n ),\n ),\n },\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 buildNitroEnvironment(nodeNitro, () => 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 console.info(`Prerendered ${pages.length} pages:`)\n pages.forEach((page) => {\n console.info(`- ${page}`)\n })\n\n // TODO: Write the prerendered pages to the output directory\n } catch (error) {\n console.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 console.info(`Concurrency: ${concurrency}`)\n const queue = new Queue({ concurrency })\n\n options.pages.forEach((_page) => {\n let page = _page as Page\n\n if (typeof _page === 'string') {\n page = { path: _page }\n }\n\n addCrawlPageTask(page)\n })\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 console.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 console.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":["build","buildNitro","_a","fsp"],"mappings":";;;;;;;;AAaA,eAAsB,UAAU;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AACF,GAIG;;AACD,UAAQ,KAAK,qBAAqB;AAGlC,QAAI,aAAQ,cAAR,mBAAmB,YAAW,CAAC,QAA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gBAAMC,SAAI,MAAM,KAAK,QAAQ,QAAQ,GAAG;AAAA,YACtC,WAAW;AAAA,UAAA,CACZ;AAEK,gBAAAA,SAAI,UAAU,UAAU,IAAI;AAElC,gBAAM,UAAU,QAAMD,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,oBAAQ,KAAK,gCAAgC,KAAK,IAAI,WAAW;AACjE,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.js","sources":["../../src/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 { Queue } from './queue'\nimport { buildNitroEnvironment } from './nitro/build-nitro'\nimport { VITE_ENVIRONMENT_NAMES } from './constants'\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 console.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 routeRules: {\n // Filter out our shell redirect rule if it exists\n ...Object.fromEntries(\n Object.entries(nitro.options._config.routeRules ?? {}).filter(\n ([_, value]) => !(value as any).__TSS_SHELL,\n ),\n ),\n },\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 buildNitroEnvironment(nodeNitro, () => 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 console.info(`Prerendered ${pages.length} pages:`)\n pages.forEach((page) => {\n console.info(`- ${page}`)\n })\n\n // TODO: Write the prerendered pages to the output directory\n } catch (error) {\n console.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 console.info(`Concurrency: ${concurrency}`)\n const queue = new Queue({ concurrency })\n\n options.pages.forEach((_page) => {\n let page = _page as Page\n\n if (typeof _page === 'string') {\n page = { path: _page }\n }\n\n addCrawlPageTask(page)\n })\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 console.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 console.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":["build","buildNitro","_a","fsp"],"mappings":";;;;;;;;;AAcA,eAAsB,UAAU;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AACF,GAIG;;AACD,UAAQ,KAAK,qBAAqB;AAGlC,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,aAAa,uBAAuB,MAAM;AAEpE,MAAI,CAAC,WAAW;AACd,UAAM,IAAI;AAAA,MACR,WAAW,uBAAuB,MAAM;AAAA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6B,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,oBAAQ,KAAK,gCAAgC,KAAK,IAAI,WAAW;AACjE,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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/start-plugin-core",
3
- "version": "1.120.4-alpha.15",
3
+ "version": "1.120.4-alpha.16",
4
4
  "description": "Modern and scalable routing for React applications",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -64,8 +64,9 @@
64
64
  "xmlbuilder2": "^3.1.1",
65
65
  "zod": "^3.24.2",
66
66
  "@tanstack/router-core": "^1.120.4-alpha.15",
67
+ "@tanstack/router-generator": "^1.120.4-alpha.15",
67
68
  "@tanstack/router-utils": "^1.120.4-alpha.1",
68
- "@tanstack/router-generator": "^1.120.4-alpha.15"
69
+ "@tanstack/server-functions-plugin": "^1.120.4-alpha.16"
69
70
  },
70
71
  "devDependencies": {
71
72
  "vite": "^6.0.0"
@@ -0,0 +1,6 @@
1
+ export const VITE_ENVIRONMENT_NAMES = {
2
+ // 'ssr' is chosen as the name for the server environment to ensure backwards compatibility
3
+ // with vite plugins that are not compatible with the new vite environment API (e.g. tailwindcss)
4
+ server: 'ssr',
5
+ client: 'client',
6
+ } as const
@@ -1,7 +1,8 @@
1
1
  import { createEvent, getHeader, sendWebResponse } from 'h3'
2
2
  import { isRunnableDevEnvironment } from 'vite'
3
3
  import { extractHtmlScripts } from '../extractHtmlScripts'
4
- import type { Connect, Plugin, ViteDevServer } from 'vite'
4
+ import { VITE_ENVIRONMENT_NAMES } from '../constants'
5
+ import type { Connect, DevEnvironment, Plugin, ViteDevServer } from 'vite'
5
6
 
6
7
  declare global {
7
8
  // eslint-disable-next-line no-var
@@ -30,11 +31,20 @@ export function devServerPlugin(): Plugin {
30
31
  let cachedScripts: string | undefined
31
32
  viteDevServer.middlewares.use(async (req, res) => {
32
33
  const event = createEvent(req, res)
33
- const serverEnv = viteDevServer.environments['server']
34
+ const serverEnv = viteDevServer.environments[
35
+ VITE_ENVIRONMENT_NAMES.server
36
+ ] as DevEnvironment | undefined
34
37
 
35
38
  try {
36
- if (!serverEnv || !isRunnableDevEnvironment(serverEnv)) {
37
- throw new Error('Server environment not found')
39
+ if (!serverEnv) {
40
+ throw new Error(
41
+ `Server environment ${VITE_ENVIRONMENT_NAMES.server} not found`,
42
+ )
43
+ }
44
+ if (!isRunnableDevEnvironment(serverEnv)) {
45
+ throw new Error(
46
+ `Expected server environment ${VITE_ENVIRONMENT_NAMES.server} to be a RunnableDevEnvironment. This can be caused by multiple vite versions being installed in the project.`,
47
+ )
38
48
  }
39
49
  if (cachedScripts === undefined) {
40
50
  const templateHtml = `<html><head></head><body></body></html>`
@@ -4,6 +4,7 @@ import { build, createNitro } from 'nitropack'
4
4
  import { dirname, resolve } from 'pathe'
5
5
  import { clientDistDir, ssrEntryFile } from '../plugin'
6
6
  import { prerender } from '../prerender'
7
+ import { VITE_ENVIRONMENT_NAMES } from '../constants'
7
8
  import { devServerPlugin } from './dev-server-plugin'
8
9
  import { buildNitroEnvironment } from './build-nitro'
9
10
  import type { EnvironmentOptions, PluginOption, Rollup } from 'vite'
@@ -22,7 +23,7 @@ export function nitroPlugin(
22
23
  {
23
24
  name: 'tanstack-vite-plugin-nitro',
24
25
  configEnvironment(name) {
25
- if (name === 'server') {
26
+ if (name === VITE_ENVIRONMENT_NAMES.server) {
26
27
  return {
27
28
  build: {
28
29
  commonjsOptions: {
@@ -44,8 +45,10 @@ export function nitroPlugin(
44
45
  builder: {
45
46
  sharedPlugins: true,
46
47
  async buildApp(builder) {
47
- const clientEnv = builder.environments['client']
48
- const serverEnv = builder.environments['server']
48
+ const clientEnv =
49
+ builder.environments[VITE_ENVIRONMENT_NAMES.client]
50
+ const serverEnv =
51
+ builder.environments[VITE_ENVIRONMENT_NAMES.server]
49
52
 
50
53
  if (!clientEnv) {
51
54
  throw new Error('Client environment not found')
package/src/plugin.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import path from 'node:path'
2
2
  import { createNitro } from 'nitropack'
3
+ import { TanStackServerFnPluginEnv } from '@tanstack/server-functions-plugin'
3
4
  import {
4
5
  createTanStackConfig,
5
6
  createTanStackStartOptionsSchema,
@@ -7,6 +8,7 @@ import {
7
8
  import { nitroPlugin } from './nitro/nitro-plugin'
8
9
  import { startManifestPlugin } from './routesManifestPlugin'
9
10
  import { TanStackStartCompilerPlugin } from './start-compiler-plugin'
11
+ import { VITE_ENVIRONMENT_NAMES } from './constants'
10
12
  import type { PluginOption, Rollup } from 'vite'
11
13
  import type { z } from 'zod'
12
14
  import type { CompileStartFrameworkOptions } from './compilers'
@@ -28,12 +30,15 @@ export type TanStackStartOutputConfig = ReturnType<
28
30
  export const clientDistDir = '.tanstack-start/build/client-dist'
29
31
  export const ssrEntryFile = 'ssr.mjs'
30
32
 
33
+ export interface TanStackStartVitePluginCoreOptions {
34
+ framework: CompileStartFrameworkOptions
35
+ }
31
36
  // this needs to live outside of the TanStackStartVitePluginCore since it will be invoked multiple times by vite
32
37
  let ssrBundle: Rollup.OutputBundle
33
38
 
34
39
  export function TanStackStartVitePluginCore(
35
- framework: CompileStartFrameworkOptions,
36
- opts: TanStackStartOutputConfig,
40
+ opts: TanStackStartVitePluginCoreOptions,
41
+ startConfig: TanStackStartOutputConfig,
37
42
  ): Array<PluginOption> {
38
43
  return [
39
44
  {
@@ -42,7 +47,7 @@ export function TanStackStartVitePluginCore(
42
47
  const nitroOutputPublicDir = await (async () => {
43
48
  // Create a dummy nitro app to get the resolved public output path
44
49
  const dummyNitroApp = await createNitro({
45
- preset: opts.target,
50
+ preset: startConfig.target,
46
51
  compatibilityDate: '2024-12-01',
47
52
  })
48
53
 
@@ -54,23 +59,23 @@ export function TanStackStartVitePluginCore(
54
59
 
55
60
  return {
56
61
  environments: {
57
- client: {
62
+ [VITE_ENVIRONMENT_NAMES.client]: {
58
63
  consumer: 'client',
59
64
  build: {
60
65
  manifest: true,
61
66
  rollupOptions: {
62
67
  input: {
63
- main: opts.clientEntryPath,
68
+ main: startConfig.clientEntryPath,
64
69
  },
65
70
  output: {
66
- dir: path.resolve(opts.root, clientDistDir),
71
+ dir: path.resolve(startConfig.root, clientDistDir),
67
72
  },
68
73
  // TODO this should be removed
69
74
  external: ['node:fs', 'node:path', 'node:os', 'node:crypto'],
70
75
  },
71
76
  },
72
77
  },
73
- server: {
78
+ [VITE_ENVIRONMENT_NAMES.server]: {
74
79
  consumer: 'server',
75
80
  build: {
76
81
  ssr: true,
@@ -118,18 +123,50 @@ export function TanStackStartVitePluginCore(
118
123
  },
119
124
  /* prettier-ignore */
120
125
  define: {
121
- ...injectDefineEnv('TSS_PUBLIC_BASE', opts.public.base),
122
- ...injectDefineEnv('TSS_CLIENT_BASE', opts.client.base),
123
- ...injectDefineEnv('TSS_CLIENT_ENTRY', opts.clientEntryPath),
124
- ...injectDefineEnv('TSS_SERVER_FN_BASE', opts.serverFns.base),
126
+ ...injectDefineEnv('TSS_PUBLIC_BASE', startConfig.public.base),
127
+ ...injectDefineEnv('TSS_CLIENT_BASE', startConfig.client.base),
128
+ ...injectDefineEnv('TSS_CLIENT_ENTRY', startConfig.clientEntryPath),
129
+ ...injectDefineEnv('TSS_SERVER_FN_BASE', startConfig.serverFns.base),
125
130
  ...injectDefineEnv('TSS_OUTPUT_PUBLIC_DIR', nitroOutputPublicDir),
126
131
  },
127
132
  }
128
133
  },
129
134
  },
130
- TanStackStartCompilerPlugin(framework),
131
- startManifestPlugin(opts),
132
- nitroPlugin(opts, () => ssrBundle),
135
+ // N.B. TanStackStartCompilerPlugin must be before the TanStackServerFnPluginEnv
136
+ TanStackStartCompilerPlugin(opts.framework, {
137
+ client: { envName: VITE_ENVIRONMENT_NAMES.client },
138
+ server: { envName: VITE_ENVIRONMENT_NAMES.server },
139
+ }),
140
+ TanStackServerFnPluginEnv({
141
+ // This is the ID that will be available to look up and import
142
+ // our server function manifest and resolve its module
143
+ manifestVirtualImportId: 'tanstack:server-fn-manifest',
144
+ client: {
145
+ getRuntimeCode: () =>
146
+ `import { createClientRpc } from '@tanstack/${opts.framework}-start/server-functions-client'`,
147
+ replacer: (d) =>
148
+ `createClientRpc('${d.functionId}', '${startConfig.serverFns.base}')`,
149
+ envName: VITE_ENVIRONMENT_NAMES.client,
150
+ },
151
+ server: {
152
+ getRuntimeCode: () =>
153
+ `import { createServerRpc } from '@tanstack/${opts.framework}-start/server-functions-server'`,
154
+ replacer: (d) =>
155
+ `createServerRpc('${d.functionId}', '${startConfig.serverFns.base}', ${d.fn})`,
156
+ envName: VITE_ENVIRONMENT_NAMES.server,
157
+ },
158
+ importer: (fn) => {
159
+ const serverEnv = (globalThis as any).viteDevServer.environments[
160
+ VITE_ENVIRONMENT_NAMES.server
161
+ ]
162
+ if (!serverEnv) {
163
+ throw new Error(`'ssr' vite dev environment not found`)
164
+ }
165
+ return serverEnv.runner.import(fn.extractedFilename)
166
+ },
167
+ }),
168
+ startManifestPlugin(startConfig),
169
+ nitroPlugin(startConfig, () => ssrBundle),
133
170
  ]
134
171
  }
135
172
 
package/src/prerender.ts CHANGED
@@ -6,6 +6,7 @@ import { build as buildNitro, createNitro } from 'nitropack'
6
6
  import { joinURL, withBase, withoutBase } from 'ufo'
7
7
  import { Queue } from './queue'
8
8
  import { buildNitroEnvironment } from './nitro/build-nitro'
9
+ import { VITE_ENVIRONMENT_NAMES } from './constants'
9
10
  import type { ViteBuilder } from 'vite'
10
11
  import type { $Fetch, Nitro } from 'nitropack'
11
12
  import type { TanStackStartOutputConfig } from './plugin'
@@ -31,10 +32,12 @@ export async function prerender({
31
32
  ]
32
33
  }
33
34
 
34
- const serverEnv = builder.environments['server']
35
+ const serverEnv = builder.environments[VITE_ENVIRONMENT_NAMES.server]
35
36
 
36
37
  if (!serverEnv) {
37
- throw new Error(`Vite's "server" environment not found`)
38
+ throw new Error(
39
+ `Vite's "${VITE_ENVIRONMENT_NAMES.server}" environment not found`,
40
+ )
38
41
  }
39
42
 
40
43
  const prerenderOutputDir = path.resolve(