@tanstack/start-plugin-core 1.134.12 → 1.134.13

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.
@@ -121,9 +121,8 @@ async function prerender({
121
121
  logger.info(`Crawling: ${page.path}`);
122
122
  const retries = retriesByPath.get(page.path) || 0;
123
123
  try {
124
- const encodedRoute = encodeURI(page.path);
125
124
  const res = await localFetch(
126
- withBase(encodedRoute, routerBasePath),
125
+ withBase(page.path, routerBasePath),
127
126
  {
128
127
  headers: {
129
128
  ...prerenderOptions.headers ?? {}
@@ -1 +1 @@
1
- {"version":3,"file":"prerender.js","sources":["../../src/prerender.ts"],"sourcesContent":["import { existsSync, promises as fsp, rmSync } from 'node:fs'\nimport { pathToFileURL } from 'node:url'\nimport os from 'node:os'\nimport path from 'pathe'\nimport { joinURL, withBase, withoutBase } from 'ufo'\nimport { VITE_ENVIRONMENT_NAMES } from './constants'\nimport { createLogger } from './utils'\nimport { Queue } from './queue'\nimport type { Rollup, ViteBuilder } from 'vite'\nimport type { Page, TanStackStartOutputConfig } from './schema'\n\nexport async function prerender({\n startConfig,\n builder,\n serverBundle,\n}: {\n startConfig: TanStackStartOutputConfig\n builder: ViteBuilder\n serverBundle: Rollup.OutputBundle\n}) {\n const logger = createLogger('prerender')\n logger.info('Prerendering pages...')\n\n // If prerender is enabled\n if (startConfig.prerender?.enabled) {\n // default to root page if no pages are defined\n let pages = startConfig.pages.length ? startConfig.pages : [{ path: '/' }]\n\n if (startConfig.prerender.autoStaticPathsDiscovery ?? true) {\n // merge discovered static pages with user-defined pages\n const pagesMap = new Map(pages.map((item) => [item.path, item]))\n const discoveredPages = globalThis.TSS_PRERENDABLE_PATHS || []\n\n for (const page of discoveredPages) {\n if (!pagesMap.has(page.path)) {\n pagesMap.set(page.path, page)\n }\n }\n\n pages = Array.from(pagesMap.values())\n }\n\n startConfig.pages = pages\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 clientEnv = builder.environments[VITE_ENVIRONMENT_NAMES.client]\n if (!clientEnv) {\n throw new Error(\n `Vite's \"${VITE_ENVIRONMENT_NAMES.client}\" environment not found`,\n )\n }\n\n const outputDir = clientEnv.config.build.outDir\n\n const entryFile = findEntryFileInBundle(serverBundle)\n let fullEntryFilePath = path.join(serverEnv.config.build.outDir, entryFile)\n process.env.TSS_PRERENDERING = 'true'\n\n if (!existsSync(fullEntryFilePath)) {\n // if the file does not exist, we need to write the bundle to a temporary directory\n // this can happen e.g. with nitro that postprocesses the bundle and thus does not write SSR build to disk\n const bundleOutputDir = path.resolve(\n serverEnv.config.root,\n '.tanstack',\n 'start',\n 'prerender',\n )\n rmSync(bundleOutputDir, { recursive: true, force: true })\n await writeBundleToDisk({ bundle: serverBundle, outDir: bundleOutputDir })\n fullEntryFilePath = path.join(bundleOutputDir, entryFile)\n }\n\n const { default: serverEntrypoint } = await import(\n pathToFileURL(fullEntryFilePath).toString()\n )\n\n const isRedirectResponse = (res: Response) => {\n return res.status >= 300 && res.status < 400 && res.headers.get('location')\n }\n async function localFetch(\n path: string,\n options?: RequestInit,\n maxRedirects: number = 5,\n ): Promise<Response> {\n const url = new URL(`http://localhost${path}`)\n const response = await serverEntrypoint.fetch(new Request(url, options))\n\n if (isRedirectResponse(response) && maxRedirects > 0) {\n const location = response.headers.get('location')!\n if (location.startsWith('http://localhost') || location.startsWith('/')) {\n const newUrl = location.replace('http://localhost', '')\n return localFetch(newUrl, options, maxRedirects - 1)\n } else {\n logger.warn(`Skipping redirect to external location: ${location}`)\n }\n }\n\n return response\n }\n\n try {\n // Crawl all pages\n const pages = await prerenderPages({ outputDir })\n\n logger.info(`Prerendered ${pages.length} pages:`)\n pages.forEach((page) => {\n logger.info(`- ${page}`)\n })\n } catch (error) {\n logger.error(error)\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({ outputDir }: { outputDir: string }) {\n const seen = new Set<string>()\n const prerendered = new Set<string>()\n const retriesByPath = new Map<string, number>()\n const concurrency = startConfig.prerender?.concurrency ?? os.cpus().length\n logger.info(`Concurrency: ${concurrency}`)\n const queue = new Queue({ concurrency })\n const routerBasePath = joinURL('/', startConfig.router.basepath ?? '')\n\n startConfig.pages.forEach((page) => addCrawlPageTask(page))\n\n await queue.start()\n\n return Array.from(prerendered)\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 startConfig.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 (startConfig.prerender?.filter && !startConfig.prerender.filter(page))\n return\n\n // Resolve the merged default and page-specific prerender options\n const prerenderOptions = {\n ...startConfig.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(\n withBase(encodedRoute, routerBasePath),\n {\n headers: {\n ...(prerenderOptions.headers ?? {}),\n },\n },\n prerenderOptions.maxRedirects,\n )\n\n if (!res.ok) {\n if (isRedirectResponse(res)) {\n logger.warn(`Max redirects reached for ${page.path}`)\n }\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 const routeWithIndex = cleanPagePath.endsWith('/')\n ? cleanPagePath + 'index'\n : cleanPagePath\n\n const isSpaShell =\n startConfig.spa?.prerender.outputPath === cleanPagePath\n\n let htmlPath: string\n if (isSpaShell) {\n // For SPA shell, ignore autoSubfolderIndex option\n htmlPath = cleanPagePath + '.html'\n } else {\n if (\n cleanPagePath.endsWith('/') ||\n (prerenderOptions.autoSubfolderIndex ?? true)\n ) {\n htmlPath = joinURL(cleanPagePath, 'index.html')\n } else {\n htmlPath = cleanPagePath + '.html'\n }\n }\n\n const filename = withoutBase(\n isImplicitHTML ? htmlPath : routeWithIndex,\n routerBasePath,\n )\n\n const html = await res.text()\n\n const filepath = path.join(outputDir, filename)\n\n await fsp.mkdir(path.dirname(filepath), {\n recursive: true,\n })\n\n await fsp.writeFile(filepath, html)\n\n prerendered.add(page.path)\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 if (prerenderOptions.failOnError ?? true) {\n throw error\n }\n }\n }\n })\n }\n }\n}\n\nfunction findEntryFileInBundle(bundle: Rollup.OutputBundle): string {\n let entryFile: string | undefined\n\n for (const [_name, file] of Object.entries(bundle)) {\n if (file.type === 'chunk') {\n if (file.isEntry) {\n if (entryFile !== undefined) {\n throw new Error(\n `Multiple entry points found. Only one entry point is allowed.`,\n )\n }\n entryFile = file.fileName\n }\n }\n }\n if (entryFile === undefined) {\n throw new Error(`No entry point found in the bundle.`)\n }\n return entryFile\n}\n\nexport async function writeBundleToDisk({\n bundle,\n outDir,\n}: {\n bundle: Rollup.OutputBundle\n outDir: string\n}) {\n const createdDirs = new Set<string>()\n\n for (const [fileName, asset] of Object.entries(bundle)) {\n const fullPath = path.join(outDir, fileName)\n const dir = path.dirname(fullPath)\n const content = asset.type === 'asset' ? asset.source : asset.code\n\n if (!createdDirs.has(dir)) {\n await fsp.mkdir(dir, { recursive: true })\n createdDirs.add(dir)\n }\n\n await fsp.writeFile(fullPath, content)\n }\n}\n"],"names":["path","outputDir","fsp"],"mappings":";;;;;;;;AAWA,eAAsB,UAAU;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AACF,GAIG;AACD,QAAM,SAAS,aAAa,WAAW;AACvC,SAAO,KAAK,uBAAuB;AAGnC,MAAI,YAAY,WAAW,SAAS;AAElC,QAAI,QAAQ,YAAY,MAAM,SAAS,YAAY,QAAQ,CAAC,EAAE,MAAM,KAAK;AAEzE,QAAI,YAAY,UAAU,4BAA4B,MAAM;AAE1D,YAAM,WAAW,IAAI,IAAI,MAAM,IAAI,CAAC,SAAS,CAAC,KAAK,MAAM,IAAI,CAAC,CAAC;AAC/D,YAAM,kBAAkB,WAAW,yBAAyB,CAAA;AAE5D,iBAAW,QAAQ,iBAAiB;AAClC,YAAI,CAAC,SAAS,IAAI,KAAK,IAAI,GAAG;AAC5B,mBAAS,IAAI,KAAK,MAAM,IAAI;AAAA,QAC9B;AAAA,MACF;AAEA,cAAQ,MAAM,KAAK,SAAS,OAAA,CAAQ;AAAA,IACtC;AAEA,gBAAY,QAAQ;AAAA,EACtB;AAEA,QAAM,YAAY,QAAQ,aAAa,uBAAuB,MAAM;AAEpE,MAAI,CAAC,WAAW;AACd,UAAM,IAAI;AAAA,MACR,WAAW,uBAAuB,MAAM;AAAA,IAAA;AAAA,EAE5C;AAEA,QAAM,YAAY,QAAQ,aAAa,uBAAuB,MAAM;AACpE,MAAI,CAAC,WAAW;AACd,UAAM,IAAI;AAAA,MACR,WAAW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C3B,UAAM,IAAI,MAAM,qCAAqC;AAAA,EACvD;AACA,SAAO;AACT;AAEA,eAAsB,kBAAkB;AAAA,EACtC;AAAA,EACA;AACF,GAGG;AACD,QAAM,kCAAkB,IAAA;AAExB,aAAW,CAAC,UAAU,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AACtD,UAAM,WAAW,KAAK,KAAK,QAAQ,QAAQ;AAC3C,UAAM,MAAM,KAAK,QAAQ,QAAQ;AACjC,UAAM,UAAU,MAAM,SAAS,UAAU,MAAM,SAAS,MAAM;AAE9D,QAAI,CAAC,YAAY,IAAI,GAAG,GAAG;AACzB,YAAMA,SAAI,MAAM,KAAK,EAAE,WAAW,MAAM;AACxC,kBAAY,IAAI,GAAG;AAAA,IACrB;AAEA,UAAMA,SAAI,UAAU,UAAU,OAAO;AAAA,EACvC;AACF;"}
1
+ {"version":3,"file":"prerender.js","sources":["../../src/prerender.ts"],"sourcesContent":["import { existsSync, promises as fsp, rmSync } from 'node:fs'\nimport { pathToFileURL } from 'node:url'\nimport os from 'node:os'\nimport path from 'pathe'\nimport { joinURL, withBase, withoutBase } from 'ufo'\nimport { VITE_ENVIRONMENT_NAMES } from './constants'\nimport { createLogger } from './utils'\nimport { Queue } from './queue'\nimport type { Rollup, ViteBuilder } from 'vite'\nimport type { Page, TanStackStartOutputConfig } from './schema'\n\nexport async function prerender({\n startConfig,\n builder,\n serverBundle,\n}: {\n startConfig: TanStackStartOutputConfig\n builder: ViteBuilder\n serverBundle: Rollup.OutputBundle\n}) {\n const logger = createLogger('prerender')\n logger.info('Prerendering pages...')\n\n // If prerender is enabled\n if (startConfig.prerender?.enabled) {\n // default to root page if no pages are defined\n let pages = startConfig.pages.length ? startConfig.pages : [{ path: '/' }]\n\n if (startConfig.prerender.autoStaticPathsDiscovery ?? true) {\n // merge discovered static pages with user-defined pages\n const pagesMap = new Map(pages.map((item) => [item.path, item]))\n const discoveredPages = globalThis.TSS_PRERENDABLE_PATHS || []\n\n for (const page of discoveredPages) {\n if (!pagesMap.has(page.path)) {\n pagesMap.set(page.path, page)\n }\n }\n\n pages = Array.from(pagesMap.values())\n }\n\n startConfig.pages = pages\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 clientEnv = builder.environments[VITE_ENVIRONMENT_NAMES.client]\n if (!clientEnv) {\n throw new Error(\n `Vite's \"${VITE_ENVIRONMENT_NAMES.client}\" environment not found`,\n )\n }\n\n const outputDir = clientEnv.config.build.outDir\n\n const entryFile = findEntryFileInBundle(serverBundle)\n let fullEntryFilePath = path.join(serverEnv.config.build.outDir, entryFile)\n process.env.TSS_PRERENDERING = 'true'\n\n if (!existsSync(fullEntryFilePath)) {\n // if the file does not exist, we need to write the bundle to a temporary directory\n // this can happen e.g. with nitro that postprocesses the bundle and thus does not write SSR build to disk\n const bundleOutputDir = path.resolve(\n serverEnv.config.root,\n '.tanstack',\n 'start',\n 'prerender',\n )\n rmSync(bundleOutputDir, { recursive: true, force: true })\n await writeBundleToDisk({ bundle: serverBundle, outDir: bundleOutputDir })\n fullEntryFilePath = path.join(bundleOutputDir, entryFile)\n }\n\n const { default: serverEntrypoint } = await import(\n pathToFileURL(fullEntryFilePath).toString()\n )\n\n const isRedirectResponse = (res: Response) => {\n return res.status >= 300 && res.status < 400 && res.headers.get('location')\n }\n async function localFetch(\n path: string,\n options?: RequestInit,\n maxRedirects: number = 5,\n ): Promise<Response> {\n const url = new URL(`http://localhost${path}`)\n const response = await serverEntrypoint.fetch(new Request(url, options))\n\n if (isRedirectResponse(response) && maxRedirects > 0) {\n const location = response.headers.get('location')!\n if (location.startsWith('http://localhost') || location.startsWith('/')) {\n const newUrl = location.replace('http://localhost', '')\n return localFetch(newUrl, options, maxRedirects - 1)\n } else {\n logger.warn(`Skipping redirect to external location: ${location}`)\n }\n }\n\n return response\n }\n\n try {\n // Crawl all pages\n const pages = await prerenderPages({ outputDir })\n\n logger.info(`Prerendered ${pages.length} pages:`)\n pages.forEach((page) => {\n logger.info(`- ${page}`)\n })\n } catch (error) {\n logger.error(error)\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({ outputDir }: { outputDir: string }) {\n const seen = new Set<string>()\n const prerendered = new Set<string>()\n const retriesByPath = new Map<string, number>()\n const concurrency = startConfig.prerender?.concurrency ?? os.cpus().length\n logger.info(`Concurrency: ${concurrency}`)\n const queue = new Queue({ concurrency })\n const routerBasePath = joinURL('/', startConfig.router.basepath ?? '')\n\n startConfig.pages.forEach((page) => addCrawlPageTask(page))\n\n await queue.start()\n\n return Array.from(prerendered)\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 startConfig.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 (startConfig.prerender?.filter && !startConfig.prerender.filter(page))\n return\n\n // Resolve the merged default and page-specific prerender options\n const prerenderOptions = {\n ...startConfig.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\n const res = await localFetch(\n withBase(page.path, routerBasePath),\n {\n headers: {\n ...(prerenderOptions.headers ?? {}),\n },\n },\n prerenderOptions.maxRedirects,\n )\n\n if (!res.ok) {\n if (isRedirectResponse(res)) {\n logger.warn(`Max redirects reached for ${page.path}`)\n }\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 const routeWithIndex = cleanPagePath.endsWith('/')\n ? cleanPagePath + 'index'\n : cleanPagePath\n\n const isSpaShell =\n startConfig.spa?.prerender.outputPath === cleanPagePath\n\n let htmlPath: string\n if (isSpaShell) {\n // For SPA shell, ignore autoSubfolderIndex option\n htmlPath = cleanPagePath + '.html'\n } else {\n if (\n cleanPagePath.endsWith('/') ||\n (prerenderOptions.autoSubfolderIndex ?? true)\n ) {\n htmlPath = joinURL(cleanPagePath, 'index.html')\n } else {\n htmlPath = cleanPagePath + '.html'\n }\n }\n\n const filename = withoutBase(\n isImplicitHTML ? htmlPath : routeWithIndex,\n routerBasePath,\n )\n\n const html = await res.text()\n\n const filepath = path.join(outputDir, filename)\n\n await fsp.mkdir(path.dirname(filepath), {\n recursive: true,\n })\n\n await fsp.writeFile(filepath, html)\n\n prerendered.add(page.path)\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 if (prerenderOptions.failOnError ?? true) {\n throw error\n }\n }\n }\n })\n }\n }\n}\n\nfunction findEntryFileInBundle(bundle: Rollup.OutputBundle): string {\n let entryFile: string | undefined\n\n for (const [_name, file] of Object.entries(bundle)) {\n if (file.type === 'chunk') {\n if (file.isEntry) {\n if (entryFile !== undefined) {\n throw new Error(\n `Multiple entry points found. Only one entry point is allowed.`,\n )\n }\n entryFile = file.fileName\n }\n }\n }\n if (entryFile === undefined) {\n throw new Error(`No entry point found in the bundle.`)\n }\n return entryFile\n}\n\nexport async function writeBundleToDisk({\n bundle,\n outDir,\n}: {\n bundle: Rollup.OutputBundle\n outDir: string\n}) {\n const createdDirs = new Set<string>()\n\n for (const [fileName, asset] of Object.entries(bundle)) {\n const fullPath = path.join(outDir, fileName)\n const dir = path.dirname(fullPath)\n const content = asset.type === 'asset' ? asset.source : asset.code\n\n if (!createdDirs.has(dir)) {\n await fsp.mkdir(dir, { recursive: true })\n createdDirs.add(dir)\n }\n\n await fsp.writeFile(fullPath, content)\n }\n}\n"],"names":["path","outputDir","fsp"],"mappings":";;;;;;;;AAWA,eAAsB,UAAU;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AACF,GAIG;AACD,QAAM,SAAS,aAAa,WAAW;AACvC,SAAO,KAAK,uBAAuB;AAGnC,MAAI,YAAY,WAAW,SAAS;AAElC,QAAI,QAAQ,YAAY,MAAM,SAAS,YAAY,QAAQ,CAAC,EAAE,MAAM,KAAK;AAEzE,QAAI,YAAY,UAAU,4BAA4B,MAAM;AAE1D,YAAM,WAAW,IAAI,IAAI,MAAM,IAAI,CAAC,SAAS,CAAC,KAAK,MAAM,IAAI,CAAC,CAAC;AAC/D,YAAM,kBAAkB,WAAW,yBAAyB,CAAA;AAE5D,iBAAW,QAAQ,iBAAiB;AAClC,YAAI,CAAC,SAAS,IAAI,KAAK,IAAI,GAAG;AAC5B,mBAAS,IAAI,KAAK,MAAM,IAAI;AAAA,QAC9B;AAAA,MACF;AAEA,cAAQ,MAAM,KAAK,SAAS,OAAA,CAAQ;AAAA,IACtC;AAEA,gBAAY,QAAQ;AAAA,EACtB;AAEA,QAAM,YAAY,QAAQ,aAAa,uBAAuB,MAAM;AAEpE,MAAI,CAAC,WAAW;AACd,UAAM,IAAI;AAAA,MACR,WAAW,uBAAuB,MAAM;A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AAA;AAAA,QAEJ;AACA,oBAAY,KAAK;AAAA,MACnB;AAAA,IACF;AAAA,EACF;AACA,MAAI,cAAc,QAAW;AAC3B,UAAM,IAAI,MAAM,qCAAqC;AAAA,EACvD;AACA,SAAO;AACT;AAEA,eAAsB,kBAAkB;AAAA,EACtC;AAAA,EACA;AACF,GAGG;AACD,QAAM,kCAAkB,IAAA;AAExB,aAAW,CAAC,UAAU,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AACtD,UAAM,WAAW,KAAK,KAAK,QAAQ,QAAQ;AAC3C,UAAM,MAAM,KAAK,QAAQ,QAAQ;AACjC,UAAM,UAAU,MAAM,SAAS,UAAU,MAAM,SAAS,MAAM;AAE9D,QAAI,CAAC,YAAY,IAAI,GAAG,GAAG;AACzB,YAAMA,SAAI,MAAM,KAAK,EAAE,WAAW,MAAM;AACxC,kBAAY,IAAI,GAAG;AAAA,IACrB;AAEA,UAAMA,SAAI,UAAU,UAAU,OAAO;AAAA,EACvC;AACF;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/start-plugin-core",
3
- "version": "1.134.12",
3
+ "version": "1.134.13",
4
4
  "description": "Modern and scalable routing for React applications",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -59,13 +59,13 @@
59
59
  "vitefu": "^1.1.1",
60
60
  "xmlbuilder2": "^3.1.1",
61
61
  "zod": "^3.24.2",
62
- "@tanstack/router-core": "1.134.12",
63
- "@tanstack/router-plugin": "1.134.12",
64
- "@tanstack/server-functions-plugin": "1.134.5",
65
- "@tanstack/start-client-core": "1.134.12",
62
+ "@tanstack/router-core": "1.134.13",
63
+ "@tanstack/router-generator": "1.134.13",
66
64
  "@tanstack/router-utils": "1.133.19",
67
- "@tanstack/start-server-core": "1.134.12",
68
- "@tanstack/router-generator": "1.134.12"
65
+ "@tanstack/router-plugin": "1.134.13",
66
+ "@tanstack/server-functions-plugin": "1.134.5",
67
+ "@tanstack/start-client-core": "1.134.13",
68
+ "@tanstack/start-server-core": "1.134.13"
69
69
  },
70
70
  "devDependencies": {
71
71
  "@types/babel__code-frame": "^7.0.6",
package/src/prerender.ts CHANGED
@@ -178,10 +178,9 @@ export async function prerender({
178
178
  const retries = retriesByPath.get(page.path) || 0
179
179
  try {
180
180
  // Fetch the route
181
- const encodedRoute = encodeURI(page.path)
182
181
 
183
182
  const res = await localFetch(
184
- withBase(encodedRoute, routerBasePath),
183
+ withBase(page.path, routerBasePath),
185
184
  {
186
185
  headers: {
187
186
  ...(prerenderOptions.headers ?? {}),