@tanstack/start-plugin-core 1.121.10 → 1.121.11
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.
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
3
|
const node_fs = require("node:fs");
|
|
4
|
+
const node_url = require("node:url");
|
|
4
5
|
const os = require("node:os");
|
|
5
6
|
const path = require("node:path");
|
|
6
7
|
const rollup = require("nitropack/rollup");
|
|
@@ -16,7 +17,7 @@ async function prerender({
|
|
|
16
17
|
}) {
|
|
17
18
|
var _a;
|
|
18
19
|
const logger = utils.createLogger("prerender");
|
|
19
|
-
logger.info("
|
|
20
|
+
logger.info("Prerendering pages...");
|
|
20
21
|
if (((_a = options.prerender) == null ? void 0 : _a.enabled) && !options.pages.length) {
|
|
21
22
|
options.pages = [
|
|
22
23
|
{
|
|
@@ -61,9 +62,9 @@ async function prerender({
|
|
|
61
62
|
};
|
|
62
63
|
await nitropack.build(nodeNitro);
|
|
63
64
|
const serverFilename = typeof nodeNitroRollupOptions.output.entryFileNames === "string" ? nodeNitroRollupOptions.output.entryFileNames : "index.mjs";
|
|
64
|
-
const serverEntrypoint =
|
|
65
|
-
path.join(nodeNitro.options.output.serverDir, serverFilename)
|
|
66
|
-
);
|
|
65
|
+
const serverEntrypoint = node_url.pathToFileURL(
|
|
66
|
+
path.resolve(path.join(nodeNitro.options.output.serverDir, serverFilename))
|
|
67
|
+
).toString();
|
|
67
68
|
const { closePrerenderer, localFetch } = await import(serverEntrypoint);
|
|
68
69
|
try {
|
|
69
70
|
const pages = await prerenderPages();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prerender.cjs","sources":["../../../src/nitro-plugin/prerender.ts"],"sourcesContent":["import { promises as fsp } from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport { getRollupConfig } from 'nitropack/rollup'\nimport { build as buildNitro, createNitro } from 'nitropack'\nimport { joinURL, withBase, withoutBase } from 'ufo'\nimport { VITE_ENVIRONMENT_NAMES } from '../constants'\nimport { createLogger } from '../utils'\nimport { Queue } from './queue'\nimport type { ViteBuilder } from 'vite'\nimport type { $Fetch, Nitro } from 'nitropack'\nimport type { TanStackStartOutputConfig } from '../plugin'\nimport type { Page } from '../schema'\n\nexport async function prerender({\n options,\n nitro,\n builder,\n}: {\n options: TanStackStartOutputConfig\n nitro: Nitro\n builder: ViteBuilder\n}) {\n const logger = createLogger('prerender')\n logger.info('Prendering pages...')\n\n // If prerender is enabled but no pages are provided, default to prerendering the root page\n if (options.prerender?.enabled && !options.pages.length) {\n options.pages = [\n {\n path: '/',\n },\n ]\n }\n\n const serverEnv = builder.environments[VITE_ENVIRONMENT_NAMES.server]\n\n if (!serverEnv) {\n throw new Error(\n `Vite's \"${VITE_ENVIRONMENT_NAMES.server}\" environment not found`,\n )\n }\n\n const prerenderOutputDir = path.resolve(\n options.root,\n '.tanstack',\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 = path.resolve(\n path.join(nodeNitro.options.output.serverDir, serverFilename),\n )\n\n const { closePrerenderer, localFetch } = (await import(serverEntrypoint)) as {\n closePrerenderer: () => void\n localFetch: $Fetch\n }\n\n try {\n // Crawl all pages\n const pages = await prerenderPages()\n\n logger.info(`Prerendered ${pages.length} pages:`)\n pages.forEach((page) => {\n logger.info(`- ${page}`)\n })\n\n // TODO: Write the prerendered pages to the output directory\n } catch (error) {\n logger.error(error)\n } finally {\n // Ensure server is always closed\n // server.process.kill()\n closePrerenderer()\n }\n\n function extractLinks(html: string): Array<string> {\n const linkRegex = /<a[^>]+href=[\"']([^\"']+)[\"'][^>]*>/g\n const links: Array<string> = []\n let match\n\n while ((match = linkRegex.exec(html)) !== null) {\n const href = match[1]\n if (href && (href.startsWith('/') || href.startsWith('./'))) {\n links.push(href)\n }\n }\n\n return links\n }\n\n async function prerenderPages() {\n const seen = new Set<string>()\n const retriesByPath = new Map<string, number>()\n const concurrency = options.prerender?.concurrency ?? os.cpus().length\n logger.info(`Concurrency: ${concurrency}`)\n const queue = new Queue({ concurrency })\n\n options.pages.forEach((page) => addCrawlPageTask(page))\n\n await queue.start()\n\n return Array.from(seen)\n\n function addCrawlPageTask(page: Page) {\n // Was the page already seen?\n if (seen.has(page.path)) return\n\n // Add the page to the seen set\n seen.add(page.path)\n\n if (page.fromCrawl) {\n options.pages.push(page)\n }\n\n // If not enabled, skip\n if (!(page.prerender?.enabled ?? true)) return\n\n // If there is a filter link, check if the page should be prerendered\n if (options.prerender?.filter && !options.prerender.filter(page)) return\n\n // Resolve the merged default and page-specific prerender options\n const prerenderOptions = {\n ...options.prerender,\n ...page.prerender,\n }\n\n // Add the task\n queue.add(async () => {\n logger.info(`Crawling: ${page.path}`)\n const retries = retriesByPath.get(page.path) || 0\n try {\n // Fetch the route\n const encodedRoute = encodeURI(page.path)\n\n const res = await localFetch<Response>(\n withBase(encodedRoute, nodeNitro.options.baseURL),\n {\n headers: { 'x-nitro-prerender': encodedRoute },\n },\n )\n\n if (!res.ok) {\n throw new Error(`Failed to fetch ${page.path}: ${res.statusText}`, {\n cause: res,\n })\n }\n\n const cleanPagePath = (\n prerenderOptions.outputPath || page.path\n ).split(/[?#]/)[0]!\n\n // Guess route type and populate fileName\n const contentType = res.headers.get('content-type') || ''\n const isImplicitHTML =\n !cleanPagePath.endsWith('.html') && contentType.includes('html')\n // &&\n // !JsonSigRx.test(dataBuff.subarray(0, 32).toString('utf8'))\n const routeWithIndex = cleanPagePath.endsWith('/')\n ? cleanPagePath + 'index'\n : cleanPagePath\n\n const htmlPath =\n cleanPagePath.endsWith('/') || prerenderOptions.autoSubfolderIndex\n ? joinURL(cleanPagePath, 'index.html')\n : cleanPagePath + '.html'\n\n const filename = withoutBase(\n isImplicitHTML ? htmlPath : routeWithIndex,\n nitro.options.baseURL,\n )\n\n const html = await res.text()\n\n const filepath = path.join(nitro.options.output.publicDir, filename)\n\n await fsp.mkdir(path.dirname(filepath), {\n recursive: true,\n })\n\n await fsp.writeFile(filepath, html)\n\n const newPage = await prerenderOptions.onSuccess?.({ page, html })\n\n if (newPage) {\n Object.assign(page, newPage)\n }\n\n // Find new links\n if (prerenderOptions.crawlLinks ?? true) {\n const links = extractLinks(html)\n for (const link of links) {\n addCrawlPageTask({ path: link, fromCrawl: true })\n }\n }\n } catch (error) {\n if (retries < (prerenderOptions.retryCount ?? 0)) {\n logger.warn(`Encountered error, retrying: ${page.path} in 500ms`)\n await new Promise((resolve) =>\n setTimeout(resolve, prerenderOptions.retryDelay),\n )\n retriesByPath.set(page.path, retries + 1)\n addCrawlPageTask(page)\n } else {\n throw error\n }\n }\n })\n }\n }\n}\n"],"names":["createLogger","VITE_ENVIRONMENT_NAMES","createNitro","getRollupConfig","buildNitro","_a","queue","Queue","withBase","joinURL","withoutBase","fsp"],"mappings":";;;;;;;;;;;AAcA,eAAsB,UAAU;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AACF,GAIG;;AACK,QAAA,SAASA,mBAAa,WAAW;AACvC,SAAO,KAAK,qBAAqB;AAGjC,QAAI,aAAQ,cAAR,mBAAmB,YAAW,CAA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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.cjs","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":["createLogger","VITE_ENVIRONMENT_NAMES","createNitro","getRollupConfig","buildNitro","pathToFileURL","_a","queue","Queue","withBase","joinURL","withoutBase","fsp"],"mappings":";;;;;;;;;;;;AAeA,eAAsB,UAAU;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AACF,GAIG;;AACK,QAAA,SAASA,mBAAa,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,aAAaC,UAAAA,uBAAuB,MAAM;AAEpE,MAAI,CAAC,WAAW;AACd,UAAM,IAAI;AAAA,MACR,WAAWA,iCAAuB,MAAM;AAAA,IAC1C;AAAA,EAAA;AAGF,QAAM,qBAAqB,KAAK;AAAA,IAC9B,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEM,QAAA,YAAY,MAAMC,sBAAY;AAAA,IAClC,GAAG,MAAM,QAAQ;AAAA,IACjB,QAAQ;AAAA,IACR,UAAU;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C,6BAAiB,IAAI;AAAA,UAAA,OAChB;AACC,kBAAA;AAAA,UAAA;AAAA,QACR;AAAA,MACF,CACD;AAAA,IAAA;AAAA,EACH;AAEJ;;"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { promises } from "node:fs";
|
|
2
|
+
import { pathToFileURL } from "node:url";
|
|
2
3
|
import os from "node:os";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import { getRollupConfig } from "nitropack/rollup";
|
|
@@ -14,7 +15,7 @@ async function prerender({
|
|
|
14
15
|
}) {
|
|
15
16
|
var _a;
|
|
16
17
|
const logger = createLogger("prerender");
|
|
17
|
-
logger.info("
|
|
18
|
+
logger.info("Prerendering pages...");
|
|
18
19
|
if (((_a = options.prerender) == null ? void 0 : _a.enabled) && !options.pages.length) {
|
|
19
20
|
options.pages = [
|
|
20
21
|
{
|
|
@@ -59,9 +60,9 @@ async function prerender({
|
|
|
59
60
|
};
|
|
60
61
|
await build(nodeNitro);
|
|
61
62
|
const serverFilename = typeof nodeNitroRollupOptions.output.entryFileNames === "string" ? nodeNitroRollupOptions.output.entryFileNames : "index.mjs";
|
|
62
|
-
const serverEntrypoint =
|
|
63
|
-
path.join(nodeNitro.options.output.serverDir, serverFilename)
|
|
64
|
-
);
|
|
63
|
+
const serverEntrypoint = pathToFileURL(
|
|
64
|
+
path.resolve(path.join(nodeNitro.options.output.serverDir, serverFilename))
|
|
65
|
+
).toString();
|
|
65
66
|
const { closePrerenderer, localFetch } = await import(serverEntrypoint);
|
|
66
67
|
try {
|
|
67
68
|
const pages = await prerenderPages();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prerender.js","sources":["../../../src/nitro-plugin/prerender.ts"],"sourcesContent":["import { promises as fsp } from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport { getRollupConfig } from 'nitropack/rollup'\nimport { build as buildNitro, createNitro } from 'nitropack'\nimport { joinURL, withBase, withoutBase } from 'ufo'\nimport { VITE_ENVIRONMENT_NAMES } from '../constants'\nimport { createLogger } from '../utils'\nimport { Queue } from './queue'\nimport type { ViteBuilder } from 'vite'\nimport type { $Fetch, Nitro } from 'nitropack'\nimport type { TanStackStartOutputConfig } from '../plugin'\nimport type { Page } from '../schema'\n\nexport async function prerender({\n options,\n nitro,\n builder,\n}: {\n options: TanStackStartOutputConfig\n nitro: Nitro\n builder: ViteBuilder\n}) {\n const logger = createLogger('prerender')\n logger.info('Prendering pages...')\n\n // If prerender is enabled but no pages are provided, default to prerendering the root page\n if (options.prerender?.enabled && !options.pages.length) {\n options.pages = [\n {\n path: '/',\n },\n ]\n }\n\n const serverEnv = builder.environments[VITE_ENVIRONMENT_NAMES.server]\n\n if (!serverEnv) {\n throw new Error(\n `Vite's \"${VITE_ENVIRONMENT_NAMES.server}\" environment not found`,\n )\n }\n\n const prerenderOutputDir = path.resolve(\n options.root,\n '.tanstack',\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 = path.resolve(\n path.join(nodeNitro.options.output.serverDir, serverFilename),\n )\n\n const { closePrerenderer, localFetch } = (await import(serverEntrypoint)) as {\n closePrerenderer: () => void\n localFetch: $Fetch\n }\n\n try {\n // Crawl all pages\n const pages = await prerenderPages()\n\n logger.info(`Prerendered ${pages.length} pages:`)\n pages.forEach((page) => {\n logger.info(`- ${page}`)\n })\n\n // TODO: Write the prerendered pages to the output directory\n } catch (error) {\n logger.error(error)\n } finally {\n // Ensure server is always closed\n // server.process.kill()\n closePrerenderer()\n }\n\n function extractLinks(html: string): Array<string> {\n const linkRegex = /<a[^>]+href=[\"']([^\"']+)[\"'][^>]*>/g\n const links: Array<string> = []\n let match\n\n while ((match = linkRegex.exec(html)) !== null) {\n const href = match[1]\n if (href && (href.startsWith('/') || href.startsWith('./'))) {\n links.push(href)\n }\n }\n\n return links\n }\n\n async function prerenderPages() {\n const seen = new Set<string>()\n const retriesByPath = new Map<string, number>()\n const concurrency = options.prerender?.concurrency ?? os.cpus().length\n logger.info(`Concurrency: ${concurrency}`)\n const queue = new Queue({ concurrency })\n\n options.pages.forEach((page) => addCrawlPageTask(page))\n\n await queue.start()\n\n return Array.from(seen)\n\n function addCrawlPageTask(page: Page) {\n // Was the page already seen?\n if (seen.has(page.path)) return\n\n // Add the page to the seen set\n seen.add(page.path)\n\n if (page.fromCrawl) {\n options.pages.push(page)\n }\n\n // If not enabled, skip\n if (!(page.prerender?.enabled ?? true)) return\n\n // If there is a filter link, check if the page should be prerendered\n if (options.prerender?.filter && !options.prerender.filter(page)) return\n\n // Resolve the merged default and page-specific prerender options\n const prerenderOptions = {\n ...options.prerender,\n ...page.prerender,\n }\n\n // Add the task\n queue.add(async () => {\n logger.info(`Crawling: ${page.path}`)\n const retries = retriesByPath.get(page.path) || 0\n try {\n // Fetch the route\n const encodedRoute = encodeURI(page.path)\n\n const res = await localFetch<Response>(\n withBase(encodedRoute, nodeNitro.options.baseURL),\n {\n headers: { 'x-nitro-prerender': encodedRoute },\n },\n )\n\n if (!res.ok) {\n throw new Error(`Failed to fetch ${page.path}: ${res.statusText}`, {\n cause: res,\n })\n }\n\n const cleanPagePath = (\n prerenderOptions.outputPath || page.path\n ).split(/[?#]/)[0]!\n\n // Guess route type and populate fileName\n const contentType = res.headers.get('content-type') || ''\n const isImplicitHTML =\n !cleanPagePath.endsWith('.html') && contentType.includes('html')\n // &&\n // !JsonSigRx.test(dataBuff.subarray(0, 32).toString('utf8'))\n const routeWithIndex = cleanPagePath.endsWith('/')\n ? cleanPagePath + 'index'\n : cleanPagePath\n\n const htmlPath =\n cleanPagePath.endsWith('/') || prerenderOptions.autoSubfolderIndex\n ? joinURL(cleanPagePath, 'index.html')\n : cleanPagePath + '.html'\n\n const filename = withoutBase(\n isImplicitHTML ? htmlPath : routeWithIndex,\n nitro.options.baseURL,\n )\n\n const html = await res.text()\n\n const filepath = path.join(nitro.options.output.publicDir, filename)\n\n await fsp.mkdir(path.dirname(filepath), {\n recursive: true,\n })\n\n await fsp.writeFile(filepath, html)\n\n const newPage = await prerenderOptions.onSuccess?.({ page, html })\n\n if (newPage) {\n Object.assign(page, newPage)\n }\n\n // Find new links\n if (prerenderOptions.crawlLinks ?? true) {\n const links = extractLinks(html)\n for (const link of links) {\n addCrawlPageTask({ path: link, fromCrawl: true })\n }\n }\n } catch (error) {\n if (retries < (prerenderOptions.retryCount ?? 0)) {\n logger.warn(`Encountered error, retrying: ${page.path} in 500ms`)\n await new Promise((resolve) =>\n setTimeout(resolve, prerenderOptions.retryDelay),\n )\n retriesByPath.set(page.path, retries + 1)\n addCrawlPageTask(page)\n } else {\n throw error\n }\n }\n })\n }\n }\n}\n"],"names":["build","buildNitro","_a","fsp"],"mappings":";;;;;;;;;AAcA,eAAsB,UAAU;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AACF,GAIG;;AACK,QAAA,SAAS,aAAa,WAAW;AACvC,SAAO,KAAK,qBAAqB;AAGjC,QAAI,aAAQ,cAAR,mBAAmB,YAAW,CAAC,QAAQ,MAAM,QAAQ;AACvD,YAAQ,QAAQ;AAAA,MACd;AAAA,QACE,MAAM;AAAA,MAAA;AAAA,IAEV;AAAA,EAAA;AAGF,QAAM,YAAY,QAAQ,aAAa,uBAAu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;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 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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B,qBAC5C,QAAQ,eAAe,YAAY,IACnC,gBAAgB;AAEtB,gBAAM,WAAW;AAAA,YACf,iBAAiB,WAAW;AAAA,YAC5B,MAAM,QAAQ;AAAA,UAChB;AAEM,gBAAA,OAAO,MAAM,IAAI,KAAK;AAE5B,gBAAM,WAAW,KAAK,KAAK,MAAM,QAAQ,OAAO,WAAW,QAAQ;AAEnE,gBAAMC,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;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/start-plugin-core",
|
|
3
|
-
"version": "1.121.
|
|
3
|
+
"version": "1.121.11",
|
|
4
4
|
"description": "Modern and scalable routing for React applications",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -65,10 +65,10 @@
|
|
|
65
65
|
"zod": "^3.24.2",
|
|
66
66
|
"@tanstack/router-core": "^1.121.2",
|
|
67
67
|
"@tanstack/router-generator": "^1.121.10",
|
|
68
|
-
"@tanstack/router-plugin": "^1.121.10",
|
|
69
68
|
"@tanstack/router-utils": "^1.121.0",
|
|
70
69
|
"@tanstack/server-functions-plugin": "^1.121.0",
|
|
71
|
-
"@tanstack/start-server-core": "^1.121.10"
|
|
70
|
+
"@tanstack/start-server-core": "^1.121.10",
|
|
71
|
+
"@tanstack/router-plugin": "^1.121.10"
|
|
72
72
|
},
|
|
73
73
|
"devDependencies": {
|
|
74
74
|
"vite": "^6.0.0"
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { promises as fsp } from 'node:fs'
|
|
2
|
+
import { pathToFileURL } from 'node:url'
|
|
2
3
|
import os from 'node:os'
|
|
3
4
|
import path from 'node:path'
|
|
4
5
|
import { getRollupConfig } from 'nitropack/rollup'
|
|
@@ -22,7 +23,7 @@ export async function prerender({
|
|
|
22
23
|
builder: ViteBuilder
|
|
23
24
|
}) {
|
|
24
25
|
const logger = createLogger('prerender')
|
|
25
|
-
logger.info('
|
|
26
|
+
logger.info('Prerendering pages...')
|
|
26
27
|
|
|
27
28
|
// If prerender is enabled but no pages are provided, default to prerendering the root page
|
|
28
29
|
if (options.prerender?.enabled && !options.pages.length) {
|
|
@@ -84,9 +85,9 @@ export async function prerender({
|
|
|
84
85
|
? nodeNitroRollupOptions.output.entryFileNames
|
|
85
86
|
: 'index.mjs'
|
|
86
87
|
|
|
87
|
-
const serverEntrypoint =
|
|
88
|
-
path.join(nodeNitro.options.output.serverDir, serverFilename),
|
|
89
|
-
)
|
|
88
|
+
const serverEntrypoint = pathToFileURL(
|
|
89
|
+
path.resolve(path.join(nodeNitro.options.output.serverDir, serverFilename)),
|
|
90
|
+
).toString()
|
|
90
91
|
|
|
91
92
|
const { closePrerenderer, localFetch } = (await import(serverEntrypoint)) as {
|
|
92
93
|
closePrerenderer: () => void
|