@tanstack/start-plugin-core 1.130.0 → 1.130.2

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.
@@ -110,7 +110,13 @@ async function buildNitroApp(builder, nitro, options) {
110
110
  const maskUrl = new URL(options.spa.maskPath, "http://localhost");
111
111
  options.pages.push({
112
112
  path: maskUrl.toString().replace("http://localhost", ""),
113
- prerender: options.spa.prerender,
113
+ prerender: {
114
+ ...options.spa.prerender,
115
+ env: {
116
+ ...options.spa.prerender.env,
117
+ TSS_SPA_MODE: "true"
118
+ }
119
+ },
114
120
  sitemap: {
115
121
  exclude: true
116
122
  }
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.js","sources":["../../../src/nitro-plugin/plugin.ts"],"sourcesContent":["import path from 'node:path'\nimport { rmSync } from 'node:fs'\nimport { build, copyPublicAssets, createNitro, prepare } from 'nitropack'\nimport { dirname, resolve } from 'pathe'\nimport {\n CLIENT_DIST_DIR,\n SSR_ENTRY_FILE,\n VITE_ENVIRONMENT_NAMES,\n} from '../constants'\nimport { buildSitemap } from './build-sitemap'\nimport { prerender } from './prerender'\nimport type {\n EnvironmentOptions,\n PluginOption,\n Rollup,\n ViteBuilder,\n} from 'vite'\nimport type { Nitro, NitroConfig } from 'nitropack'\nimport type { TanStackStartOutputConfig } from '../plugin'\n\nexport function nitroPlugin(\n options: TanStackStartOutputConfig,\n getSsrBundle: () => Rollup.OutputBundle,\n): Array<PluginOption> {\n const buildPreset =\n process.env['START_TARGET'] ?? (options.target as string | undefined)\n return [\n {\n name: 'tanstack-vite-plugin-nitro',\n configEnvironment(name) {\n if (name === VITE_ENVIRONMENT_NAMES.server) {\n return {\n build: {\n commonjsOptions: {\n include: [],\n },\n ssr: true,\n sourcemap: true,\n rollupOptions: {\n input: '/~start/server-entry',\n },\n },\n } satisfies EnvironmentOptions\n }\n\n return null\n },\n config() {\n return {\n builder: {\n sharedPlugins: true,\n async buildApp(builder) {\n const client = builder.environments[VITE_ENVIRONMENT_NAMES.client]\n const server = builder.environments[VITE_ENVIRONMENT_NAMES.server]\n\n if (!client) {\n throw new Error('Client environment not found')\n }\n\n if (!server) {\n throw new Error('SSR environment not found')\n }\n\n // Build the client bundle\n // i.e client entry file with `hydrateRoot(...)`\n const clientOutputDir = resolve(options.root, CLIENT_DIST_DIR)\n rmSync(clientOutputDir, { recursive: true, force: true })\n await builder.build(client)\n\n // Build the SSR bundle\n await builder.build(server)\n\n const nitroConfig: NitroConfig = {\n dev: false,\n // TODO: do we need this? should this be made configurable?\n compatibilityDate: '2024-11-19',\n logLevel: 3,\n preset: buildPreset,\n baseURL: globalThis.TSS_APP_BASE,\n publicAssets: [\n {\n dir: path.resolve(options.root, CLIENT_DIST_DIR),\n baseURL: '/',\n maxAge: 31536000, // 1 year\n },\n ],\n typescript: {\n generateTsConfig: false,\n },\n prerender: undefined,\n renderer: SSR_ENTRY_FILE,\n plugins: [], // Nitro's plugins\n appConfigFiles: [],\n scanDirs: [],\n imports: false, // unjs/unimport for global/magic imports\n rollupConfig: {\n plugins: [virtualBundlePlugin(getSsrBundle())],\n },\n virtual: {\n // This is Nitro's way of defining virtual modules\n // Should we define the ones for TanStack Start's here as well?\n },\n }\n\n const nitro = await createNitro(nitroConfig)\n\n await buildNitroApp(builder, nitro, options)\n },\n },\n }\n },\n },\n ]\n}\n\n/**\n * Correctly co-ordinates the nitro app build process to make sure that the\n * app is built, while also correctly handling the prerendering and sitemap\n * generation and including their outputs in the final build.\n */\nasync function buildNitroApp(\n builder: ViteBuilder,\n nitro: Nitro,\n options: TanStackStartOutputConfig,\n) {\n // Cleans the public and server directories for a fresh build\n // i.e the `.output/public` and `.output/server` directories\n await prepare(nitro)\n\n // Creates the `.output/public` directory and copies the public assets\n await copyPublicAssets(nitro)\n\n // If the user has not set a prerender option, we need to set it to true\n // if the pages array is not empty and has sub options requiring for prerendering\n // If the user has explicitly set prerender.enabled, this should be respected\n if (options.prerender?.enabled !== false) {\n options.prerender = {\n ...options.prerender,\n enabled:\n options.prerender?.enabled ??\n options.pages.some((d) =>\n typeof d === 'string' ? false : !!d.prerender?.enabled,\n ),\n }\n }\n\n // Setup the options for prerendering the SPA shell (i.e `src/routes/__root.tsx`)\n if (options.spa?.enabled) {\n options.prerender = {\n ...options.prerender,\n enabled: true,\n }\n\n const maskUrl = new URL(options.spa.maskPath, 'http://localhost')\n\n options.pages.push({\n path: maskUrl.toString().replace('http://localhost', ''),\n prerender: options.spa.prerender,\n sitemap: {\n exclude: true,\n },\n })\n }\n\n // Run the prerendering process\n if (options.prerender.enabled) {\n await prerender({\n options,\n nitro,\n builder,\n })\n }\n\n // Run the sitemap build process\n if (options.pages.length) {\n buildSitemap({\n options,\n publicDir: nitro.options.output.publicDir,\n })\n }\n\n // Build the nitro app\n // We only build the nitro app, once we've prepared the public assets,\n // prerendered the pages and built the sitemap.\n // If we try to do this earlier, then the public assets may not be available\n // in the production build.\n await build(nitro)\n\n // Close the nitro instance\n await nitro.close()\n nitro.logger.success(\n 'Client and Server bundles for TanStack Start have been successfully built.',\n )\n}\n\ntype NitroRollupPluginOption = NonNullable<\n NitroConfig['rollupConfig']\n>['plugins']\n\nfunction virtualBundlePlugin(\n ssrBundle: Rollup.OutputBundle,\n): NitroRollupPluginOption {\n type VirtualModule = { code: string; map: string | null }\n const _modules = new Map<string, VirtualModule>()\n\n // group chunks and source maps\n for (const [fileName, content] of Object.entries(ssrBundle)) {\n if (content.type === 'chunk') {\n const virtualModule: VirtualModule = {\n code: content.code,\n map: null,\n }\n const maybeMap = ssrBundle[`${fileName}.map`]\n if (maybeMap && maybeMap.type === 'asset') {\n virtualModule.map = maybeMap.source as string\n }\n _modules.set(fileName, virtualModule)\n _modules.set(resolve(fileName), virtualModule)\n }\n }\n\n return {\n name: 'virtual-bundle',\n resolveId(id, importer) {\n if (_modules.has(id)) {\n return resolve(id)\n }\n\n if (importer) {\n const resolved = resolve(dirname(importer), id)\n if (_modules.has(resolved)) {\n return resolved\n }\n }\n return null\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EAEX;AACF;"}
1
+ {"version":3,"file":"plugin.js","sources":["../../../src/nitro-plugin/plugin.ts"],"sourcesContent":["import path from 'node:path'\nimport { rmSync } from 'node:fs'\nimport { build, copyPublicAssets, createNitro, prepare } from 'nitropack'\nimport { dirname, resolve } from 'pathe'\nimport {\n CLIENT_DIST_DIR,\n SSR_ENTRY_FILE,\n VITE_ENVIRONMENT_NAMES,\n} from '../constants'\nimport { buildSitemap } from './build-sitemap'\nimport { prerender } from './prerender'\nimport type {\n EnvironmentOptions,\n PluginOption,\n Rollup,\n ViteBuilder,\n} from 'vite'\nimport type { Nitro, NitroConfig } from 'nitropack'\nimport type { TanStackStartOutputConfig } from '../plugin'\n\nexport function nitroPlugin(\n options: TanStackStartOutputConfig,\n getSsrBundle: () => Rollup.OutputBundle,\n): Array<PluginOption> {\n const buildPreset =\n process.env['START_TARGET'] ?? (options.target as string | undefined)\n return [\n {\n name: 'tanstack-vite-plugin-nitro',\n configEnvironment(name) {\n if (name === VITE_ENVIRONMENT_NAMES.server) {\n return {\n build: {\n commonjsOptions: {\n include: [],\n },\n ssr: true,\n sourcemap: true,\n rollupOptions: {\n input: '/~start/server-entry',\n },\n },\n } satisfies EnvironmentOptions\n }\n\n return null\n },\n config() {\n return {\n builder: {\n sharedPlugins: true,\n async buildApp(builder) {\n const client = builder.environments[VITE_ENVIRONMENT_NAMES.client]\n const server = builder.environments[VITE_ENVIRONMENT_NAMES.server]\n\n if (!client) {\n throw new Error('Client environment not found')\n }\n\n if (!server) {\n throw new Error('SSR environment not found')\n }\n\n // Build the client bundle\n // i.e client entry file with `hydrateRoot(...)`\n const clientOutputDir = resolve(options.root, CLIENT_DIST_DIR)\n rmSync(clientOutputDir, { recursive: true, force: true })\n await builder.build(client)\n\n // Build the SSR bundle\n await builder.build(server)\n\n const nitroConfig: NitroConfig = {\n dev: false,\n // TODO: do we need this? should this be made configurable?\n compatibilityDate: '2024-11-19',\n logLevel: 3,\n preset: buildPreset,\n baseURL: globalThis.TSS_APP_BASE,\n publicAssets: [\n {\n dir: path.resolve(options.root, CLIENT_DIST_DIR),\n baseURL: '/',\n maxAge: 31536000, // 1 year\n },\n ],\n typescript: {\n generateTsConfig: false,\n },\n prerender: undefined,\n renderer: SSR_ENTRY_FILE,\n plugins: [], // Nitro's plugins\n appConfigFiles: [],\n scanDirs: [],\n imports: false, // unjs/unimport for global/magic imports\n rollupConfig: {\n plugins: [virtualBundlePlugin(getSsrBundle())],\n },\n virtual: {\n // This is Nitro's way of defining virtual modules\n // Should we define the ones for TanStack Start's here as well?\n },\n }\n\n const nitro = await createNitro(nitroConfig)\n\n await buildNitroApp(builder, nitro, options)\n },\n },\n }\n },\n },\n ]\n}\n\n/**\n * Correctly co-ordinates the nitro app build process to make sure that the\n * app is built, while also correctly handling the prerendering and sitemap\n * generation and including their outputs in the final build.\n */\nasync function buildNitroApp(\n builder: ViteBuilder,\n nitro: Nitro,\n options: TanStackStartOutputConfig,\n) {\n // Cleans the public and server directories for a fresh build\n // i.e the `.output/public` and `.output/server` directories\n await prepare(nitro)\n\n // Creates the `.output/public` directory and copies the public assets\n await copyPublicAssets(nitro)\n\n // If the user has not set a prerender option, we need to set it to true\n // if the pages array is not empty and has sub options requiring for prerendering\n // If the user has explicitly set prerender.enabled, this should be respected\n if (options.prerender?.enabled !== false) {\n options.prerender = {\n ...options.prerender,\n enabled:\n options.prerender?.enabled ??\n options.pages.some((d) =>\n typeof d === 'string' ? false : !!d.prerender?.enabled,\n ),\n }\n }\n\n // Setup the options for prerendering the SPA shell (i.e `src/routes/__root.tsx`)\n if (options.spa?.enabled) {\n options.prerender = {\n ...options.prerender,\n enabled: true,\n }\n\n const maskUrl = new URL(options.spa.maskPath, 'http://localhost')\n\n options.pages.push({\n path: maskUrl.toString().replace('http://localhost', ''),\n prerender: {\n ...options.spa.prerender,\n env: {\n ...options.spa.prerender.env,\n TSS_SPA_MODE: 'true',\n },\n },\n sitemap: {\n exclude: true,\n },\n })\n }\n\n // Run the prerendering process\n if (options.prerender.enabled) {\n await prerender({\n options,\n nitro,\n builder,\n })\n }\n\n // Run the sitemap build process\n if (options.pages.length) {\n buildSitemap({\n options,\n publicDir: nitro.options.output.publicDir,\n })\n }\n\n // Build the nitro app\n // We only build the nitro app, once we've prepared the public assets,\n // prerendered the pages and built the sitemap.\n // If we try to do this earlier, then the public assets may not be available\n // in the production build.\n await build(nitro)\n\n // Close the nitro instance\n await nitro.close()\n nitro.logger.success(\n 'Client and Server bundles for TanStack Start have been successfully built.',\n )\n}\n\ntype NitroRollupPluginOption = NonNullable<\n NitroConfig['rollupConfig']\n>['plugins']\n\nfunction virtualBundlePlugin(\n ssrBundle: Rollup.OutputBundle,\n): NitroRollupPluginOption {\n type VirtualModule = { code: string; map: string | null }\n const _modules = new Map<string, VirtualModule>()\n\n // group chunks and source maps\n for (const [fileName, content] of Object.entries(ssrBundle)) {\n if (content.type === 'chunk') {\n const virtualModule: VirtualModule = {\n code: content.code,\n map: null,\n }\n const maybeMap = ssrBundle[`${fileName}.map`]\n if (maybeMap && maybeMap.type === 'asset') {\n virtualModule.map = maybeMap.source as string\n }\n _modules.set(fileName, virtualModule)\n _modules.set(resolve(fileName), virtualModule)\n }\n }\n\n return {\n name: 'virtual-bundle',\n resolveId(id, importer) {\n if (_modules.has(id)) {\n return resolve(id)\n }\n\n if (importer) {\n const resolved = resolve(dirname(importer), id)\n if (_modules.has(resolved)) {\n return resolved\n }\n }\n return null\n },\n load(id) {\n const m = _modules.get(id)\n if (!m) {\n return null\n }\n return m\n },\n }\n}\n"],"names":["_a"],"mappings":";;;;;;;AAoBgB,SAAA,YACd,SACA,cACqB;AACrB,QAAM,cACJ,QAAQ,IAAI,cAAc,KAAM,QAAQ;AACnC,SAAA;AAAA,IACL;AAAA,MACE,MAAM;AAAA,MACN,kBAAkB,MAAM;AAClB,YAAA,SAAS,uBAAuB,QAAQ;AACnC,iBAAA;AAAA,YACL,OAAO;AAAA,cACL,iBAAiB;AAAA,gBACf,SAAS,CAAA;AAAA,cAC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AA,IAAA,CACjC;AAAA,EAAA;AAQH,QAAM,MAAM,KAAK;AAGjB,QAAM,MAAM,MAAM;AAClB,QAAM,OAAO;AAAA,IACX;AAAA,EACF;AACF;AAMA,SAAS,oBACP,WACyB;AAEnB,QAAA,+BAAe,IAA2B;AAGhD,aAAW,CAAC,UAAU,OAAO,KAAK,OAAO,QAAQ,SAAS,GAAG;AACvD,QAAA,QAAQ,SAAS,SAAS;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,IAAI,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,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;"}
@@ -116,12 +116,22 @@ async function prerender({
116
116
  const retries = retriesByPath.get(page.path) || 0;
117
117
  try {
118
118
  const encodedRoute = encodeURI(page.path);
119
+ const originalEnv = { ...process.env };
120
+ process.env = {
121
+ ...originalEnv,
122
+ TSS_PRERENDERING: "true",
123
+ ...prerenderOptions.env || {}
124
+ };
119
125
  const res = await localFetch(
120
126
  withBase(encodedRoute, nodeNitro.options.baseURL),
121
127
  {
122
- headers: { "x-nitro-prerender": encodedRoute }
128
+ headers: {
129
+ ...prerenderOptions.headers,
130
+ "x-nitro-prerender": encodedRoute
131
+ }
123
132
  }
124
133
  );
134
+ process.env = originalEnv;
125
135
  if (!res.ok) {
126
136
  throw new Error(`Failed to fetch ${page.path}: ${res.statusText}`, {
127
137
  cause: res
@@ -1 +1 @@
1
- {"version":3,"file":"prerender.js","sources":["../../../src/nitro-plugin/prerender.ts"],"sourcesContent":["import { promises as fsp } from 'node:fs'\nimport { pathToFileURL } from 'node:url'\nimport os from 'node:os'\nimport path from 'node:path'\nimport { getRollupConfig } from 'nitropack/rollup'\nimport { build as buildNitro, createNitro } from 'nitropack'\nimport { joinURL, withBase, withoutBase } from 'ufo'\nimport { VITE_ENVIRONMENT_NAMES } from '../constants'\nimport { createLogger } from '../utils'\nimport { Queue } from './queue'\nimport type { ViteBuilder } from 'vite'\nimport type { $Fetch, Nitro } from 'nitropack'\nimport type { TanStackStartOutputConfig } from '../plugin'\nimport type { Page } from '../schema'\n\nexport async function prerender({\n options,\n nitro,\n builder,\n}: {\n options: TanStackStartOutputConfig\n nitro: Nitro\n builder: ViteBuilder\n}) {\n const logger = createLogger('prerender')\n logger.info('Prerendering 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',\n 'start',\n 'build',\n 'prerenderer',\n )\n\n const nodeNitro = await createNitro({\n ...nitro.options._config,\n preset: 'nitro-prerender',\n logLevel: 0,\n output: {\n dir: prerenderOutputDir,\n serverDir: path.resolve(prerenderOutputDir, 'server'),\n publicDir: path.resolve(prerenderOutputDir, 'public'),\n },\n })\n\n const nodeNitroRollupOptions = getRollupConfig(nodeNitro)\n\n const build = serverEnv.config.build\n\n build.outDir = prerenderOutputDir\n\n build.rollupOptions = {\n ...build.rollupOptions,\n ...nodeNitroRollupOptions,\n output: {\n ...build.rollupOptions.output,\n ...nodeNitroRollupOptions.output,\n sourcemap: undefined,\n },\n }\n\n await buildNitro(nodeNitro)\n\n // Import renderer entry\n const serverFilename =\n typeof nodeNitroRollupOptions.output.entryFileNames === 'string'\n ? nodeNitroRollupOptions.output.entryFileNames\n : 'index.mjs'\n\n const serverEntrypoint = pathToFileURL(\n path.resolve(path.join(nodeNitro.options.output.serverDir, serverFilename)),\n ).toString()\n\n const { closePrerenderer, localFetch } = (await import(serverEntrypoint)) as {\n closePrerenderer: () => void\n localFetch: $Fetch\n }\n\n try {\n // Crawl all pages\n const pages = await prerenderPages()\n\n logger.info(`Prerendered ${pages.length} pages:`)\n pages.forEach((page) => {\n logger.info(`- ${page}`)\n })\n\n // TODO: Write the prerendered pages to the output directory\n } catch (error) {\n logger.error(error)\n } finally {\n // Ensure server is always closed\n // server.process.kill()\n closePrerenderer()\n }\n\n function extractLinks(html: string): Array<string> {\n const linkRegex = /<a[^>]+href=[\"']([^\"']+)[\"'][^>]*>/g\n const links: Array<string> = []\n let match\n\n while ((match = linkRegex.exec(html)) !== null) {\n const href = match[1]\n if (href && (href.startsWith('/') || href.startsWith('./'))) {\n links.push(href)\n }\n }\n\n return links\n }\n\n async function prerenderPages() {\n const seen = new Set<string>()\n const retriesByPath = new Map<string, number>()\n const concurrency = options.prerender?.concurrency ?? os.cpus().length\n logger.info(`Concurrency: ${concurrency}`)\n const queue = new Queue({ concurrency })\n\n options.pages.forEach((page) => addCrawlPageTask(page))\n\n await queue.start()\n\n return Array.from(seen)\n\n function addCrawlPageTask(page: Page) {\n // Was the page already seen?\n if (seen.has(page.path)) return\n\n // Add the page to the seen set\n seen.add(page.path)\n\n if (page.fromCrawl) {\n options.pages.push(page)\n }\n\n // If not enabled, skip\n if (!(page.prerender?.enabled ?? true)) return\n\n // If there is a filter link, check if the page should be prerendered\n if (options.prerender?.filter && !options.prerender.filter(page)) return\n\n // Resolve the merged default and page-specific prerender options\n const prerenderOptions = {\n ...options.prerender,\n ...page.prerender,\n }\n\n // Add the task\n queue.add(async () => {\n logger.info(`Crawling: ${page.path}`)\n const retries = retriesByPath.get(page.path) || 0\n try {\n // Fetch the route\n const encodedRoute = encodeURI(page.path)\n\n const res = await localFetch<Response>(\n withBase(encodedRoute, nodeNitro.options.baseURL),\n {\n headers: { 'x-nitro-prerender': encodedRoute },\n },\n )\n\n if (!res.ok) {\n throw new Error(`Failed to fetch ${page.path}: ${res.statusText}`, {\n cause: res,\n })\n }\n\n const cleanPagePath = (\n prerenderOptions.outputPath || page.path\n ).split(/[?#]/)[0]!\n\n // Guess route type and populate fileName\n const contentType = res.headers.get('content-type') || ''\n const isImplicitHTML =\n !cleanPagePath.endsWith('.html') && contentType.includes('html')\n // &&\n // !JsonSigRx.test(dataBuff.subarray(0, 32).toString('utf8'))\n const routeWithIndex = cleanPagePath.endsWith('/')\n ? cleanPagePath + 'index'\n : cleanPagePath\n\n const htmlPath =\n cleanPagePath.endsWith('/') || prerenderOptions.autoSubfolderIndex\n ? joinURL(cleanPagePath, 'index.html')\n : cleanPagePath + '.html'\n\n const filename = withoutBase(\n isImplicitHTML ? htmlPath : routeWithIndex,\n nitro.options.baseURL,\n )\n\n const html = await res.text()\n\n const filepath = path.join(nitro.options.output.publicDir, filename)\n\n await fsp.mkdir(path.dirname(filepath), {\n recursive: true,\n })\n\n await fsp.writeFile(filepath, html)\n\n const newPage = await prerenderOptions.onSuccess?.({ page, html })\n\n if (newPage) {\n Object.assign(page, newPage)\n }\n\n // Find new links\n if (prerenderOptions.crawlLinks ?? true) {\n const links = extractLinks(html)\n for (const link of links) {\n addCrawlPageTask({ path: link, fromCrawl: true })\n }\n }\n } catch (error) {\n if (retries < (prerenderOptions.retryCount ?? 0)) {\n logger.warn(`Encountered error, retrying: ${page.path} in 500ms`)\n await new Promise((resolve) =>\n setTimeout(resolve, prerenderOptions.retryDelay),\n )\n retriesByPath.set(page.path, retries + 1)\n addCrawlPageTask(page)\n } else {\n throw error\n }\n }\n })\n }\n }\n}\n"],"names":["build","buildNitro","_a","fsp"],"mappings":";;;;;;;;;;AAeA,eAAsB,UAAU;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AACF,GAIG;;AACK,QAAA,SAAS,aAAa,WAAW;AACvC,SAAO,KAAK,uBAAuB;AAGnC,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,IAC1C;AAAA,EAAA;AAGF,QAAM,qBAAqB,KAAK;AAAA,IAC9B,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEM,QAAA,YAAY,MAAM,YAAY;AAAA,IAClC,GAAG,MAAM,QAAQ;AAAA,IACjB,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,QAAQ;AAAA,MACN,KAAK;AAAA,MACL,WAAW,KAAK,QAAQ,oBAAoB,QAAQ;AAAA,MACpD,WAAW,KAAK,QAAQ,oBAAoB,QAAQ;AAAA,IAAA;AAAA,EACtD,CACD;AAEK,QAAA,yBAAyB,gBAAgB,SAAS;AAElD,QAAAA,UAAQ,UAAU,OAAO;AAE/BA,UAAM,SAAS;AAEfA,UAAM,gBAAgB;AAAA,IACpB,GAAGA,QAAM;AAAA,IACT,GAAG;AAAA,IACH,QAAQ;AAAA,MACN,GAAGA,QAAM,cAAc;AAAA,MACvB,GAAG,uBAAuB;AAAA,MAC1B,W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M,QAAQ;AAAA,UAChB;AAEM,gBAAA,OAAO,MAAM,IAAI,KAAK;AAE5B,gBAAM,WAAW,KAAK,KAAK,MAAM,QAAQ,OAAO,WAAW,QAAQ;AAEnE,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,mBAAO,KAAK,gCAAgC,KAAK,IAAI,WAAW;AAChE,kBAAM,IAAI;AAAA,cAAQ,CAAC,YACjB,WAAW,SAAS,iBAAiB,UAAU;AAAA,YACjD;AACA,0BAAc,IAAI,KAAK,MAAM,UAAU,CAAC;AACxC,6BAAiB,IAAI;AAAA,UAAA,OAChB;AACC,kBAAA;AAAA,UAAA;AAAA,QACR;AAAA,MACF,CACD;AAAA,IAAA;AAAA,EACH;AAEJ;"}
1
+ {"version":3,"file":"prerender.js","sources":["../../../src/nitro-plugin/prerender.ts"],"sourcesContent":["import { promises as fsp } from 'node:fs'\nimport { pathToFileURL } from 'node:url'\nimport os from 'node:os'\nimport path from 'node:path'\nimport { getRollupConfig } from 'nitropack/rollup'\nimport { build as buildNitro, createNitro } from 'nitropack'\nimport { joinURL, withBase, withoutBase } from 'ufo'\nimport { VITE_ENVIRONMENT_NAMES } from '../constants'\nimport { createLogger } from '../utils'\nimport { Queue } from './queue'\nimport type { ViteBuilder } from 'vite'\nimport type { $Fetch, Nitro } from 'nitropack'\nimport type { TanStackStartOutputConfig } from '../plugin'\nimport type { Page } from '../schema'\n\nexport async function prerender({\n options,\n nitro,\n builder,\n}: {\n options: TanStackStartOutputConfig\n nitro: Nitro\n builder: ViteBuilder\n}) {\n const logger = createLogger('prerender')\n logger.info('Prerendering 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',\n 'start',\n 'build',\n 'prerenderer',\n )\n\n const nodeNitro = await createNitro({\n ...nitro.options._config,\n preset: 'nitro-prerender',\n logLevel: 0,\n output: {\n dir: prerenderOutputDir,\n serverDir: path.resolve(prerenderOutputDir, 'server'),\n publicDir: path.resolve(prerenderOutputDir, 'public'),\n },\n })\n\n const nodeNitroRollupOptions = getRollupConfig(nodeNitro)\n\n const build = serverEnv.config.build\n\n build.outDir = prerenderOutputDir\n\n build.rollupOptions = {\n ...build.rollupOptions,\n ...nodeNitroRollupOptions,\n output: {\n ...build.rollupOptions.output,\n ...nodeNitroRollupOptions.output,\n sourcemap: undefined,\n },\n }\n\n await buildNitro(nodeNitro)\n\n // Import renderer entry\n const serverFilename =\n typeof nodeNitroRollupOptions.output.entryFileNames === 'string'\n ? nodeNitroRollupOptions.output.entryFileNames\n : 'index.mjs'\n\n const serverEntrypoint = pathToFileURL(\n path.resolve(path.join(nodeNitro.options.output.serverDir, serverFilename)),\n ).toString()\n\n const { closePrerenderer, localFetch } = (await import(serverEntrypoint)) as {\n closePrerenderer: () => void\n localFetch: $Fetch\n }\n\n try {\n // Crawl all pages\n const pages = await prerenderPages()\n\n logger.info(`Prerendered ${pages.length} pages:`)\n pages.forEach((page) => {\n logger.info(`- ${page}`)\n })\n\n // TODO: Write the prerendered pages to the output directory\n } catch (error) {\n logger.error(error)\n } finally {\n // Ensure server is always closed\n // server.process.kill()\n closePrerenderer()\n }\n\n function extractLinks(html: string): Array<string> {\n const linkRegex = /<a[^>]+href=[\"']([^\"']+)[\"'][^>]*>/g\n const links: Array<string> = []\n let match\n\n while ((match = linkRegex.exec(html)) !== null) {\n const href = match[1]\n if (href && (href.startsWith('/') || href.startsWith('./'))) {\n links.push(href)\n }\n }\n\n return links\n }\n\n async function prerenderPages() {\n const seen = new Set<string>()\n const retriesByPath = new Map<string, number>()\n const concurrency = options.prerender?.concurrency ?? os.cpus().length\n logger.info(`Concurrency: ${concurrency}`)\n const queue = new Queue({ concurrency })\n\n options.pages.forEach((page) => addCrawlPageTask(page))\n\n await queue.start()\n\n return Array.from(seen)\n\n function addCrawlPageTask(page: Page) {\n // Was the page already seen?\n if (seen.has(page.path)) return\n\n // Add the page to the seen set\n seen.add(page.path)\n\n if (page.fromCrawl) {\n options.pages.push(page)\n }\n\n // If not enabled, skip\n if (!(page.prerender?.enabled ?? true)) return\n\n // If there is a filter link, check if the page should be prerendered\n if (options.prerender?.filter && !options.prerender.filter(page)) return\n\n // Resolve the merged default and page-specific prerender options\n const prerenderOptions = {\n ...options.prerender,\n ...page.prerender,\n }\n\n // Add the task\n queue.add(async () => {\n logger.info(`Crawling: ${page.path}`)\n const retries = retriesByPath.get(page.path) || 0\n try {\n // Fetch the route\n const encodedRoute = encodeURI(page.path)\n\n const originalEnv = { ...process.env }\n\n process.env = {\n ...originalEnv,\n TSS_PRERENDERING: 'true',\n ...(prerenderOptions.env || {}),\n }\n const res = await localFetch<Response>(\n withBase(encodedRoute, nodeNitro.options.baseURL),\n {\n headers: {\n ...prerenderOptions.headers,\n 'x-nitro-prerender': encodedRoute,\n },\n },\n )\n process.env = originalEnv\n if (!res.ok) {\n throw new Error(`Failed to fetch ${page.path}: ${res.statusText}`, {\n cause: res,\n })\n }\n\n const cleanPagePath = (\n prerenderOptions.outputPath || page.path\n ).split(/[?#]/)[0]!\n\n // Guess route type and populate fileName\n const contentType = res.headers.get('content-type') || ''\n const isImplicitHTML =\n !cleanPagePath.endsWith('.html') && contentType.includes('html')\n // &&\n // !JsonSigRx.test(dataBuff.subarray(0, 32).toString('utf8'))\n const routeWithIndex = cleanPagePath.endsWith('/')\n ? cleanPagePath + 'index'\n : cleanPagePath\n\n const htmlPath =\n cleanPagePath.endsWith('/') || prerenderOptions.autoSubfolderIndex\n ? joinURL(cleanPagePath, 'index.html')\n : cleanPagePath + '.html'\n\n const filename = withoutBase(\n isImplicitHTML ? htmlPath : routeWithIndex,\n nitro.options.baseURL,\n )\n\n const html = await res.text()\n\n const filepath = path.join(nitro.options.output.publicDir, filename)\n\n await fsp.mkdir(path.dirname(filepath), {\n recursive: true,\n })\n\n await fsp.writeFile(filepath, html)\n\n const newPage = await prerenderOptions.onSuccess?.({ page, html })\n\n if (newPage) {\n Object.assign(page, newPage)\n }\n\n // Find new links\n if (prerenderOptions.crawlLinks ?? true) {\n const links = extractLinks(html)\n for (const link of links) {\n addCrawlPageTask({ path: link, fromCrawl: true })\n }\n }\n } catch (error) {\n if (retries < (prerenderOptions.retryCount ?? 0)) {\n logger.warn(`Encountered error, retrying: ${page.path} in 500ms`)\n await new Promise((resolve) =>\n setTimeout(resolve, prerenderOptions.retryDelay),\n )\n retriesByPath.set(page.path, retries + 1)\n addCrawlPageTask(page)\n } else {\n throw error\n }\n }\n })\n }\n }\n}\n"],"names":["build","buildNitro","_a","fsp"],"mappings":";;;;;;;;;;AAeA,eAAsB,UAAU;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AACF,GAIG;;AACK,QAAA,SAAS,aAAa,WAAW;AACvC,SAAO,KAAK,uBAAuB;AAGnC,QAAI,aAAQ,cAAR,mBAAmB,YAAW,CAAC,QAAQ,MAAM,QAAQ;AACvD,YAAQ,QAAQ;AAAA,MACd;AAAA,QACE,MAAM;AAAA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I;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,mBAAO,KAAK,gCAAgC,KAAK,IAAI,WAAW;AAChE,kBAAM,IAAI;AAAA,cAAQ,CAAC,YACjB,WAAW,SAAS,iBAAiB,UAAU;AAAA,YACjD;AACA,0BAAc,IAAI,KAAK,MAAM,UAAU,CAAC;AACxC,6BAAiB,IAAI;AAAA,UAAA,OAChB;AACC,kBAAA;AAAA,UAAA;AAAA,QACR;AAAA,MACF,CACD;AAAA,IAAA;AAAA,EACH;AAEJ;"}
@@ -92,6 +92,8 @@ export declare function getTanStackStartOptions(opts?: TanStackStartInputConfig)
92
92
  };
93
93
  html: string;
94
94
  }, ...args: unknown[]) => any) | undefined;
95
+ headers?: Record<string, string> | undefined;
96
+ env?: Record<string, string> | undefined;
95
97
  } | undefined;
96
98
  sitemap?: {
97
99
  exclude?: boolean | undefined;
@@ -159,6 +161,8 @@ export declare function getTanStackStartOptions(opts?: TanStackStartInputConfig)
159
161
  };
160
162
  html: string;
161
163
  }, ...args: unknown[]) => any) | undefined;
164
+ headers?: Record<string, string> | undefined;
165
+ env?: Record<string, string> | undefined;
162
166
  } | undefined;
163
167
  sitemap?: {
164
168
  exclude?: boolean | undefined;
@@ -225,6 +229,8 @@ export declare function getTanStackStartOptions(opts?: TanStackStartInputConfig)
225
229
  };
226
230
  html: string;
227
231
  }, ...args: unknown[]) => any) | undefined;
232
+ headers?: Record<string, string> | undefined;
233
+ env?: Record<string, string> | undefined;
228
234
  }) | undefined;
229
235
  sitemap?: {
230
236
  enabled: boolean;
@@ -269,6 +275,8 @@ export declare function getTanStackStartOptions(opts?: TanStackStartInputConfig)
269
275
  };
270
276
  html: string;
271
277
  }, ...args: unknown[]) => any) | undefined;
278
+ headers?: Record<string, string> | undefined;
279
+ env?: Record<string, string> | undefined;
272
280
  };
273
281
  enabled: boolean;
274
282
  maskPath: string;
@@ -25,7 +25,7 @@ function TanStackStartVitePluginCore(opts, startConfig) {
25
25
  resolveVirtualEntriesPlugin(opts, startConfig),
26
26
  {
27
27
  name: "tanstack-start-core:config-client",
28
- async config(viteConfig) {
28
+ async config(viteConfig, { command }) {
29
29
  var _a;
30
30
  const viteAppBase = trimPathRight(viteConfig.base || "/");
31
31
  globalThis.TSS_APP_BASE = viteAppBase;
@@ -106,7 +106,7 @@ function TanStackStartVitePluginCore(opts, startConfig) {
106
106
  ...defineReplaceEnv("TSS_SERVER_FN_BASE", startConfig.serverFns.base),
107
107
  ...defineReplaceEnv("TSS_OUTPUT_PUBLIC_DIR", nitroOutputPublicDir),
108
108
  ...defineReplaceEnv("TSS_APP_BASE", viteAppBase),
109
- ...defineReplaceEnv("TSS_SPA_MODE", ((_a = startConfig.spa) == null ? void 0 : _a.enabled) ? "true" : "false")
109
+ ...command === "serve" ? defineReplaceEnv("TSS_SPA_MODE", ((_a = startConfig.spa) == null ? void 0 : _a.enabled) ? "true" : "false") : {}
110
110
  }
111
111
  };
112
112
  }
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.js","sources":["../../src/plugin.ts"],"sourcesContent":["import path from 'node:path'\nimport { createNitro } from 'nitropack'\nimport { trimPathRight } from '@tanstack/router-core'\nimport { VIRTUAL_MODULES } from '@tanstack/start-server-core'\nimport { TanStackServerFnPluginEnv } from '@tanstack/server-functions-plugin'\nimport * as vite from 'vite'\nimport { createTanStackConfig } from './schema'\nimport { nitroPlugin } from './nitro-plugin/plugin'\nimport { startManifestPlugin } from './start-manifest-plugin/plugin'\nimport { startCompilerPlugin } from './start-compiler-plugin'\nimport {\n CLIENT_DIST_DIR,\n SSR_ENTRY_FILE,\n VITE_ENVIRONMENT_NAMES,\n} from './constants'\nimport { tanStackStartRouter } from './start-router-plugin/plugin'\nimport { loadEnvPlugin } from './load-env-plugin/plugin'\nimport { devServerPlugin } from './dev-server-plugin/plugin'\nimport { resolveVirtualEntriesPlugin } from './resolve-virtual-entries-plugin/plugin'\nimport type { createTanStackStartOptionsSchema } from './schema'\nimport type { PluginOption, Rollup } from 'vite'\nimport type { z } from 'zod'\nimport type { CompileStartFrameworkOptions } from './compilers'\n\nexport type TanStackStartInputConfig = z.input<\n ReturnType<typeof createTanStackStartOptionsSchema>\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 interface TanStackStartVitePluginCoreOptions {\n framework: CompileStartFrameworkOptions\n getVirtualServerRootHandler: (ctx: {\n routerFilepath: string\n serverEntryFilepath: string\n }) => string\n getVirtualServerEntry: (ctx: { routerFilepath: string }) => string\n getVirtualClientEntry: (ctx: { routerFilepath: string }) => string\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 tanStackStartRouter({\n ...startConfig.tsr,\n target: opts.framework,\n autoCodeSplitting: true,\n }),\n resolveVirtualEntriesPlugin(opts, startConfig),\n {\n name: 'tanstack-start-core:config-client',\n async config(viteConfig) {\n const viteAppBase = trimPathRight(viteConfig.base || '/')\n globalThis.TSS_APP_BASE = viteAppBase\n\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 base: viteAppBase,\n environments: {\n [VITE_ENVIRONMENT_NAMES.client]: {\n consumer: 'client',\n build: {\n manifest: true,\n rollupOptions: {\n input: {\n main: getClientEntryPath(startConfig),\n },\n output: {\n dir: path.resolve(startConfig.root, CLIENT_DIST_DIR),\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: SSR_ENTRY_FILE,\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**',\n `@tanstack/${opts.framework}-start**`,\n ...Object.values(VIRTUAL_MODULES),\n ],\n dedupe: [`@tanstack/${opts.framework}-start`],\n },\n optimizeDeps: {\n exclude: [\n ...Object.values(VIRTUAL_MODULES),\n `@tanstack/${opts.framework}-start`,\n ],\n },\n /* prettier-ignore */\n define: {\n // define is an esbuild function that replaces the any instances of given keys with the given values\n // i.e: __FRAMEWORK_NAME__ can be replaced with JSON.stringify(\"TanStack Start\")\n // This is not the same as injecting environment variables.\n\n ...defineReplaceEnv('TSS_SERVER_FN_BASE', startConfig.serverFns.base),\n ...defineReplaceEnv('TSS_OUTPUT_PUBLIC_DIR', nitroOutputPublicDir),\n ...defineReplaceEnv('TSS_APP_BASE', viteAppBase),\n ...defineReplaceEnv('TSS_SPA_MODE', startConfig.spa?.enabled ? 'true' : 'false'),\n },\n }\n },\n },\n // N.B. TanStackStartCompilerPlugin must be before the TanStackServerFnPluginEnv\n startCompilerPlugin(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: VIRTUAL_MODULES.serverFnManifest,\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 }),\n loadEnvPlugin(startConfig),\n startManifestPlugin({ clientEntry: getClientEntryPath(startConfig) }),\n devServerPlugin(),\n nitroPlugin(startConfig, () => ssrBundle),\n {\n name: 'tanstack-start:core:capture-client-bundle',\n applyToEnvironment(e) {\n return e.name === VITE_ENVIRONMENT_NAMES.client\n },\n enforce: 'post',\n generateBundle(_options, bundle) {\n globalThis.TSS_CLIENT_BUNDLE = bundle\n },\n },\n ]\n}\n\nfunction defineReplaceEnv<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\nconst getClientEntryPath = (startConfig: TanStackStartOutputConfig) => {\n // when the user specifies a custom client entry path, we need to resolve it\n // relative to the root of the project, keeping in mind that if not specified\n // it will be /~start/default-client-entry which is a virtual path\n // that is resolved by vite to the actual client entry path\n const entry = startConfig.clientEntryPath.startsWith(\n '/~start/default-client-entry',\n )\n ? startConfig.clientEntryPath\n : vite.normalizePath(\n path.join(\n '/@fs',\n path.resolve(startConfig.root, startConfig.clientEntryPath),\n ),\n )\n\n return entry\n}\n"],"names":["nitroOutputPublicDir"],"mappings":";;;;;;;;;;;;;;;AA4BsB,qBAAqB;AAmB3C,IAAI;AAEY,SAAA,4BACd,MACA,aACqB;AACd,SAAA;AAAA,IACL,oBAAoB;AAAA,MAClB,GAAG,YAAY;AAAA,MACf,QAAQ,KAAK;AAAA,MACb,mBAAmB;AAAA,IAAA,CACpB;AAAA,IACD,4BAA4B,MAAM,WAAW;AAAA,IAC7C;AAAA,MACE,MAAM;AAAA,MACN,MAAM,OAAO,YAAY;;AACvB,cAAM,cAAc,cAAc,WAAW,QAAQ,GAAG;AACxD,mBAAW,eAAe;AAEpB,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,MAAM;AAAA,UACN,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,mBAAmB,WAAW;AAAA,kBACtC;AAAA,kBACA,QAAQ;AAAA,oBACN,KAAK,KAAK,QAAQ,YAAY,MAAM,eAAe;AAAA,kBACrD;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,KA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AgB,MACd,8CAA8C,KAAK,SAAS;AAAA,QAC9D,UAAU,CAAC,MACT,oBAAoB,EAAE,UAAU,OAAO,YAAY,UAAU,IAAI;AAAA,QACnE,SAAS,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,SAAS,uBAAuB;AAAA,MAAA;AAAA,IAClC,CACD;AAAA,IACD,cAAc,WAAW;AAAA,IACzB,oBAAoB,EAAE,aAAa,mBAAmB,WAAW,GAAG;AAAA,IACpE,gBAAgB;AAAA,IAChB,YAAY,aAAa,MAAM,SAAS;AAAA,IACxC;AAAA,MACE,MAAM;AAAA,MACN,mBAAmB,GAAG;AACb,eAAA,EAAE,SAAS,uBAAuB;AAAA,MAC3C;AAAA,MACA,SAAS;AAAA,MACT,eAAe,UAAU,QAAQ;AAC/B,mBAAW,oBAAoB;AAAA,MAAA;AAAA,IACjC;AAAA,EAEJ;AACF;AAEA,SAAS,iBACP,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;AAEA,MAAM,qBAAqB,CAAC,gBAA2C;AAK/D,QAAA,QAAQ,YAAY,gBAAgB;AAAA,IACxC;AAAA,EAAA,IAEE,YAAY,kBACZ,KAAK;AAAA,IACH,KAAK;AAAA,MACH;AAAA,MACA,KAAK,QAAQ,YAAY,MAAM,YAAY,eAAe;AAAA,IAAA;AAAA,EAE9D;AAEG,SAAA;AACT;"}
1
+ {"version":3,"file":"plugin.js","sources":["../../src/plugin.ts"],"sourcesContent":["import path from 'node:path'\nimport { createNitro } from 'nitropack'\nimport { trimPathRight } from '@tanstack/router-core'\nimport { VIRTUAL_MODULES } from '@tanstack/start-server-core'\nimport { TanStackServerFnPluginEnv } from '@tanstack/server-functions-plugin'\nimport * as vite from 'vite'\nimport { createTanStackConfig } from './schema'\nimport { nitroPlugin } from './nitro-plugin/plugin'\nimport { startManifestPlugin } from './start-manifest-plugin/plugin'\nimport { startCompilerPlugin } from './start-compiler-plugin'\nimport {\n CLIENT_DIST_DIR,\n SSR_ENTRY_FILE,\n VITE_ENVIRONMENT_NAMES,\n} from './constants'\nimport { tanStackStartRouter } from './start-router-plugin/plugin'\nimport { loadEnvPlugin } from './load-env-plugin/plugin'\nimport { devServerPlugin } from './dev-server-plugin/plugin'\nimport { resolveVirtualEntriesPlugin } from './resolve-virtual-entries-plugin/plugin'\nimport type { createTanStackStartOptionsSchema } from './schema'\nimport type { PluginOption, Rollup } from 'vite'\nimport type { z } from 'zod'\nimport type { CompileStartFrameworkOptions } from './compilers'\n\nexport type TanStackStartInputConfig = z.input<\n ReturnType<typeof createTanStackStartOptionsSchema>\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 interface TanStackStartVitePluginCoreOptions {\n framework: CompileStartFrameworkOptions\n getVirtualServerRootHandler: (ctx: {\n routerFilepath: string\n serverEntryFilepath: string\n }) => string\n getVirtualServerEntry: (ctx: { routerFilepath: string }) => string\n getVirtualClientEntry: (ctx: { routerFilepath: string }) => string\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 tanStackStartRouter({\n ...startConfig.tsr,\n target: opts.framework,\n autoCodeSplitting: true,\n }),\n resolveVirtualEntriesPlugin(opts, startConfig),\n {\n name: 'tanstack-start-core:config-client',\n async config(viteConfig, { command }) {\n const viteAppBase = trimPathRight(viteConfig.base || '/')\n globalThis.TSS_APP_BASE = viteAppBase\n\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 base: viteAppBase,\n environments: {\n [VITE_ENVIRONMENT_NAMES.client]: {\n consumer: 'client',\n build: {\n manifest: true,\n rollupOptions: {\n input: {\n main: getClientEntryPath(startConfig),\n },\n output: {\n dir: path.resolve(startConfig.root, CLIENT_DIST_DIR),\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: SSR_ENTRY_FILE,\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**',\n `@tanstack/${opts.framework}-start**`,\n ...Object.values(VIRTUAL_MODULES),\n ],\n dedupe: [`@tanstack/${opts.framework}-start`],\n },\n optimizeDeps: {\n exclude: [\n ...Object.values(VIRTUAL_MODULES),\n `@tanstack/${opts.framework}-start`,\n ],\n },\n /* prettier-ignore */\n define: {\n // define is an esbuild function that replaces the any instances of given keys with the given values\n // i.e: __FRAMEWORK_NAME__ can be replaced with JSON.stringify(\"TanStack Start\")\n // This is not the same as injecting environment variables.\n\n ...defineReplaceEnv('TSS_SERVER_FN_BASE', startConfig.serverFns.base),\n ...defineReplaceEnv('TSS_OUTPUT_PUBLIC_DIR', nitroOutputPublicDir),\n ...defineReplaceEnv('TSS_APP_BASE', viteAppBase),\n ...(command === 'serve' ? defineReplaceEnv('TSS_SPA_MODE', startConfig.spa?.enabled ? 'true' : 'false') : {}),\n },\n }\n },\n },\n // N.B. TanStackStartCompilerPlugin must be before the TanStackServerFnPluginEnv\n startCompilerPlugin(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: VIRTUAL_MODULES.serverFnManifest,\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 }),\n loadEnvPlugin(startConfig),\n startManifestPlugin({ clientEntry: getClientEntryPath(startConfig) }),\n devServerPlugin(),\n nitroPlugin(startConfig, () => ssrBundle),\n {\n name: 'tanstack-start:core:capture-client-bundle',\n applyToEnvironment(e) {\n return e.name === VITE_ENVIRONMENT_NAMES.client\n },\n enforce: 'post',\n generateBundle(_options, bundle) {\n globalThis.TSS_CLIENT_BUNDLE = bundle\n },\n },\n ]\n}\n\nfunction defineReplaceEnv<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\nconst getClientEntryPath = (startConfig: TanStackStartOutputConfig) => {\n // when the user specifies a custom client entry path, we need to resolve it\n // relative to the root of the project, keeping in mind that if not specified\n // it will be /~start/default-client-entry which is a virtual path\n // that is resolved by vite to the actual client entry path\n const entry = startConfig.clientEntryPath.startsWith(\n '/~start/default-client-entry',\n )\n ? startConfig.clientEntryPath\n : vite.normalizePath(\n path.join(\n '/@fs',\n path.resolve(startConfig.root, startConfig.clientEntryPath),\n ),\n )\n\n return entry\n}\n"],"names":["nitroOutputPublicDir"],"mappings":";;;;;;;;;;;;;;;AA4BsB,qBAAqB;AAmB3C,IAAI;AAEY,SAAA,4BACd,MACA,aACqB;AACd,SAAA;AAAA,IACL,oBAAoB;AAAA,MAClB,GAAG,YAAY;AAAA,MACf,QAAQ,KAAK;AAAA,MACb,mBAAmB;AAAA,IAAA,CACpB;AAAA,IACD,4BAA4B,MAAM,WAAW;AAAA,IAC7C;AAAA,MACE,MAAM;AAAA,MACN,MAAM,OAAO,YAAY,EAAE,WAAW;;AACpC,cAAM,cAAc,cAAc,WAAW,QAAQ,GAAG;AACxD,mBAAW,eAAe;AAEpB,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,MAAM;AAAA,UACN,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,mBAAmB,WAAW;AAAA,kBACtC;AAAA,kBACA,QAAQ;AAAA,oBACN,KAAK,K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