vite-react-ssg 0.6.1 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/node.cjs CHANGED
@@ -6,22 +6,17 @@ const kolorist = require('kolorist');
6
6
  const fs = require('fs-extra');
7
7
  const vite = require('vite');
8
8
  const JSDOM = require('jsdom');
9
- const state = require('./shared/vite-react-ssg.e6991406.cjs');
9
+ const state = require('./shared/vite-react-ssg.bee8a5a9.cjs');
10
10
  const node_fs = require('node:fs');
11
11
  const React = require('react');
12
12
  const reactHelmetAsync = require('react-helmet-async');
13
13
  const node_stream = require('node:stream');
14
14
  const server = require('react-dom/server');
15
- const https = require('node:https');
16
- const express = require('express');
17
- const devcert = require('@childrentime/devcert');
18
15
 
19
16
  function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
20
17
 
21
18
  const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
22
19
  const React__default = /*#__PURE__*/_interopDefaultCompat(React);
23
- const https__default = /*#__PURE__*/_interopDefaultCompat(https);
24
- const express__default = /*#__PURE__*/_interopDefaultCompat(express);
25
20
 
26
21
  function getDefaultExportFromCjs (x) {
27
22
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
@@ -866,10 +861,18 @@ async function routesToPaths(routes) {
866
861
  if (!routes || routes.length === 0)
867
862
  return { paths: ["/"], pathToEntry };
868
863
  const paths = /* @__PURE__ */ new Set();
869
- const lazyPaths = /* @__PURE__ */ new Set();
870
864
  const getPaths = async (routes2, prefix = "") => {
871
865
  prefix = prefix.replace(/\/$/g, "");
872
- for (const route of routes2) {
866
+ for (let route of routes2) {
867
+ if (route.lazy) {
868
+ const lazyData = await route.lazy();
869
+ if (lazyData) {
870
+ route = {
871
+ ...route,
872
+ ...lazyData
873
+ };
874
+ }
875
+ }
873
876
  let path = route.path;
874
877
  path = handlePath(path, prefix, route.entry);
875
878
  if (route.getStaticPaths && isDynamicSegmentsRoute(path)) {
@@ -880,8 +883,6 @@ async function routesToPaths(routes) {
880
883
  await getPaths(route.children, staticPath);
881
884
  }
882
885
  }
883
- if (route.lazy)
884
- lazyPaths.add(route.index ? prefix : path ?? "");
885
886
  if (route.index)
886
887
  addEntry(prefix, route.entry);
887
888
  if (Array.isArray(route.children))
@@ -889,7 +890,7 @@ async function routesToPaths(routes) {
889
890
  }
890
891
  };
891
892
  await getPaths(routes);
892
- return { paths: Array.from(paths), pathToEntry, lazyPaths: Array.from(lazyPaths) };
893
+ return { paths: Array.from(paths), pathToEntry };
893
894
  function handlePath(path, prefix, entry) {
894
895
  if (path != null) {
895
896
  path = prefix && !path.startsWith("/") ? `${prefix}${path ? `/${path}` : ""}` : path;
@@ -903,31 +904,6 @@ async function routesToPaths(routes) {
903
904
  return path;
904
905
  }
905
906
  }
906
- function createFetchRequest(req) {
907
- const origin = `${req.protocol}://${req.get("host")}`;
908
- const url = new URL(req.originalUrl || req.url, origin);
909
- const controller = new AbortController();
910
- req.on("close", () => controller.abort());
911
- const headers = new Headers();
912
- for (const [key, values] of Object.entries(req.headers)) {
913
- if (values) {
914
- if (Array.isArray(values)) {
915
- for (const value of values)
916
- headers.append(key, value);
917
- } else {
918
- headers.set(key, values);
919
- }
920
- }
921
- }
922
- const init = {
923
- method: req.method,
924
- headers,
925
- signal: controller.signal
926
- };
927
- if (req.method !== "GET" && req.method !== "HEAD")
928
- init.body = req.body;
929
- return new Request(url.href, init);
930
- }
931
907
  async function resolveAlias(config, entry) {
932
908
  const resolver = config.createResolver();
933
909
  const result = await resolver(entry, config.root);
@@ -960,10 +936,6 @@ function withTrailingSlash(path) {
960
936
  return `${path}/`;
961
937
  return path;
962
938
  }
963
- const postfixRE = /[?#].*$/s;
964
- function cleanUrl(url) {
965
- return url.replace(postfixRE, "");
966
- }
967
939
  const dynamicRE = /[:*?]/;
968
940
  function isDynamicSegmentsRoute(route) {
969
941
  if (!route)
@@ -1063,17 +1035,6 @@ async function render(routesOrApp, request, styleCollector, basename) {
1063
1035
  const { htmlAttributes, bodyAttributes, metaAttributes, styleTag } = extractHelmet(helmetContext, styleCollector);
1064
1036
  return { appHTML, htmlAttributes, bodyAttributes, metaAttributes, styleTag, routerContext: context };
1065
1037
  }
1066
- async function preLoad(routes, paths) {
1067
- if (!paths || paths.length === 0)
1068
- return routes;
1069
- const { createStaticHandler } = await import('react-router-dom/server.js');
1070
- const { dataRoutes, query } = createStaticHandler(routes);
1071
- await Promise.all(paths.map(async (path) => {
1072
- const request = createRequest(path);
1073
- return query(request);
1074
- }));
1075
- return dataRoutes;
1076
- }
1077
1038
  function extractHelmet(context, styleCollector) {
1078
1039
  const { helmet } = context;
1079
1040
  const htmlAttributes = helmet.htmlAttributes.toString();
@@ -1089,56 +1050,6 @@ function extractHelmet(context, styleCollector) {
1089
1050
  return { htmlAttributes, bodyAttributes, metaAttributes, styleTag };
1090
1051
  }
1091
1052
 
1092
- function renderPreloadLinks(document, modules, ssrManifest) {
1093
- const seen = /* @__PURE__ */ new Set();
1094
- const preloadLinks = [];
1095
- Array.from(modules).forEach((id) => {
1096
- const files = ssrManifest[id] || [];
1097
- files.forEach((file) => {
1098
- if (!preloadLinks.includes(file))
1099
- preloadLinks.push(file);
1100
- });
1101
- });
1102
- if (preloadLinks) {
1103
- preloadLinks.forEach((file) => {
1104
- if (!seen.has(file)) {
1105
- seen.add(file);
1106
- renderPreloadLink(document, file);
1107
- }
1108
- });
1109
- }
1110
- }
1111
- function renderPreloadLink(document, file) {
1112
- if (file.endsWith(".js")) {
1113
- appendLink(document, {
1114
- rel: "modulepreload",
1115
- crossOrigin: "",
1116
- href: file
1117
- });
1118
- } else if (file.endsWith(".css")) {
1119
- appendLink(document, {
1120
- rel: "stylesheet",
1121
- href: file
1122
- });
1123
- }
1124
- }
1125
- function createLink$1(document) {
1126
- return document.createElement("link");
1127
- }
1128
- function setAttrs(el, attrs) {
1129
- const keys = Object.keys(attrs);
1130
- for (const key of keys)
1131
- el.setAttribute(key, attrs[key]);
1132
- }
1133
- function appendLink(document, attrs) {
1134
- const exits = document.head.querySelector(`link[href='${attrs.file}']`);
1135
- if (exits)
1136
- return;
1137
- const link = createLink$1(document);
1138
- setAttrs(link, attrs);
1139
- document.head.appendChild(link);
1140
- }
1141
-
1142
1053
  async function renderHTML({
1143
1054
  rootContainerId,
1144
1055
  indexHTML,
@@ -1182,7 +1093,7 @@ async function renderHTML({
1182
1093
  return renderedOutput;
1183
1094
  }
1184
1095
  async function detectEntry(root) {
1185
- const scriptSrcReg = /<script(?:.*?)src=["'](.+?)["'](?!<)(?:.*)\>(?:[\n\r\s]*?)(?:<\/script>)/img;
1096
+ const scriptSrcReg = /<script(?:.*?)src=["'](.+?)["'](?!<)(?:.*)\>(?:[\n\r\s]*?)(?:<\/script>)/gim;
1186
1097
  const html = await fs__default.readFile(node_path.join(root, "index.html"), "utf-8");
1187
1098
  const scripts = [...html.matchAll(scriptSrcReg)];
1188
1099
  const [, entry] = scripts.find((matchResult) => {
@@ -1192,10 +1103,61 @@ async function detectEntry(root) {
1192
1103
  }) || [];
1193
1104
  return entry || "src/main.ts";
1194
1105
  }
1195
- function createLink(href) {
1106
+ function createLink$1(href) {
1196
1107
  return `<link rel="stylesheet" href="${href}">`;
1197
1108
  }
1198
1109
 
1110
+ function renderPreloadLinks(document, modules, ssrManifest) {
1111
+ const seen = /* @__PURE__ */ new Set();
1112
+ const preloadLinks = [];
1113
+ Array.from(modules).forEach((id) => {
1114
+ const files = ssrManifest[id] || [];
1115
+ files.forEach((file) => {
1116
+ if (!preloadLinks.includes(file))
1117
+ preloadLinks.push(file);
1118
+ });
1119
+ });
1120
+ if (preloadLinks) {
1121
+ preloadLinks.forEach((file) => {
1122
+ if (!seen.has(file)) {
1123
+ seen.add(file);
1124
+ renderPreloadLink(document, file);
1125
+ }
1126
+ });
1127
+ }
1128
+ }
1129
+ function renderPreloadLink(document, file) {
1130
+ if (file.endsWith(".js")) {
1131
+ appendLink(document, {
1132
+ rel: "modulepreload",
1133
+ crossOrigin: "",
1134
+ href: file
1135
+ });
1136
+ } else if (file.endsWith(".css")) {
1137
+ appendLink(document, {
1138
+ rel: "stylesheet",
1139
+ href: file,
1140
+ crossOrigin: ""
1141
+ });
1142
+ }
1143
+ }
1144
+ function createLink(document) {
1145
+ return document.createElement("link");
1146
+ }
1147
+ function setAttrs(el, attrs) {
1148
+ const keys = Object.keys(attrs);
1149
+ for (const key of keys)
1150
+ el.setAttribute(key, attrs[key]);
1151
+ }
1152
+ function appendLink(document, attrs) {
1153
+ const exits = document.head.querySelector(`link[href='${attrs.file}']`);
1154
+ if (exits)
1155
+ return;
1156
+ const link = createLink(document);
1157
+ setAttrs(link, attrs);
1158
+ document.head.appendChild(link);
1159
+ }
1160
+
1199
1161
  function DefaultIncludedRoutes(paths, _routes) {
1200
1162
  return paths.filter((i) => !i.includes(":") && !i.includes("*"));
1201
1163
  }
@@ -1277,9 +1239,7 @@ async function build(ssgOptions = {}, viteConfig = {}) {
1277
1239
  const { createRoot, includedRoutes: serverEntryIncludedRoutes } = format === "esm" ? await import(serverEntry) : _require(serverEntry);
1278
1240
  const includedRoutes = serverEntryIncludedRoutes || configIncludedRoutes;
1279
1241
  const { routes } = await createRoot(false);
1280
- const { lazyPaths } = await routesToPaths(routes);
1281
- const dataRoutes = await preLoad([...routes || []], lazyPaths);
1282
- const { paths, pathToEntry } = await routesToPaths(dataRoutes);
1242
+ const { paths, pathToEntry } = await routesToPaths(routes);
1283
1243
  let routesPaths = includeAllRoutes ? paths : await includedRoutes(paths, routes || []);
1284
1244
  routesPaths = DefaultIncludedRoutes(routesPaths);
1285
1245
  routesPaths = Array.from(new Set(routesPaths));
@@ -1319,8 +1279,10 @@ async function build(ssgOptions = {}, viteConfig = {}) {
1319
1279
  renderPreloadLinks(jsdom.window.document, modules, ssrManifest);
1320
1280
  const html = jsdom.serialize();
1321
1281
  let transformed = await onPageRendered?.(path, html, appCtx) || html;
1322
- if (critters)
1282
+ if (critters) {
1323
1283
  transformed = await crittersQueue.add(() => critters.process(transformed));
1284
+ transformed = transformed.replace(/<link\srel="stylesheet"/g, '<link rel="stylesheet" crossorigin');
1285
+ }
1324
1286
  if (styleTag)
1325
1287
  transformed = transformed.replace("<head>", `<head>${styleTag}`);
1326
1288
  const formatted = await formatHtml(transformed, formatting);
@@ -1370,9 +1332,14 @@ async function formatHtml(html, formatting) {
1370
1332
  minifyCSS: true
1371
1333
  });
1372
1334
  } else if (formatting === "prettify") {
1373
- const prettier = (await import('prettier/esm/standalone.mjs')).default;
1374
- const parserHTML = (await import('prettier/esm/parser-html.mjs')).default;
1375
- return prettier.format(html, { semi: false, parser: "html", plugins: [parserHTML] });
1335
+ try {
1336
+ const prettier = (await import('prettier/esm/standalone.mjs')).default;
1337
+ const parserHTML = (await import('prettier/esm/parser-html.mjs')).default;
1338
+ return prettier.format(html, { semi: false, parser: "html", plugins: [parserHTML] });
1339
+ } catch (e) {
1340
+ console.error(`${kolorist.gray("[vite-react-ssg]")} ${kolorist.red(`Error formatting html: ${e?.message}`)}`);
1341
+ return html;
1342
+ }
1376
1343
  }
1377
1344
  return html;
1378
1345
  }
@@ -1394,114 +1361,48 @@ function collectModules(manifest, entry, mods = /* @__PURE__ */ new Set()) {
1394
1361
  return mods;
1395
1362
  }
1396
1363
 
1397
- const SHORTCUTS = [
1398
- {
1399
- key: "u",
1400
- description: "show server url",
1401
- action(vite, _) {
1402
- vite.config.logger.info("");
1403
- printServerInfo(vite, true);
1404
- }
1405
- },
1406
- {
1407
- key: "c",
1408
- description: "clear console",
1409
- action(vite, _) {
1410
- vite.config.logger.clearScreen("error");
1411
- }
1412
- },
1413
- {
1414
- key: "q",
1415
- description: "quit",
1416
- action(_, server) {
1417
- server.close(() => process.exit());
1418
- }
1364
+ function invariant(value, message) {
1365
+ if (value === false || value === null || typeof value === "undefined") {
1366
+ console.error(
1367
+ "The following error is a bug in Remix; please open an issue! https://github.com/remix-run/remix/issues/new"
1368
+ );
1369
+ throw new Error(message);
1419
1370
  }
1420
- ];
1421
- function bindShortcuts(viteServer, server) {
1422
- if (!process.stdin.isTTY || process.env.CI)
1423
- return;
1424
- viteServer.config.logger.info(
1425
- kolorist.dim(kolorist.green(" \u279C")) + kolorist.dim(" press ") + kolorist.bold("h") + kolorist.dim(" to show help")
1426
- );
1427
- const shortcuts = SHORTCUTS;
1428
- let actionRunning = false;
1429
- const onInput = async (input) => {
1430
- if (input === "" || input === "") {
1431
- try {
1432
- await server.close();
1433
- } finally {
1434
- process.exit(1);
1435
- }
1436
- return;
1437
- }
1438
- if (actionRunning)
1439
- return;
1440
- if (input === "h") {
1441
- viteServer.config.logger.info(
1442
- [
1443
- "",
1444
- kolorist.bold(" Shortcuts"),
1445
- ...shortcuts.map(
1446
- (shortcut2) => kolorist.dim(" press ") + kolorist.bold(shortcut2.key) + kolorist.dim(` to ${shortcut2.description}`)
1447
- )
1448
- ].join("\n")
1449
- );
1450
- }
1451
- const shortcut = shortcuts.find((shortcut2) => shortcut2.key === input);
1452
- if (!shortcut)
1453
- return;
1454
- actionRunning = true;
1455
- await shortcut.action(viteServer, server);
1456
- actionRunning = false;
1457
- };
1458
- process.stdin.setRawMode(true);
1459
- process.stdin.on("data", onInput).setEncoding("utf8").resume();
1460
- server.on("close", () => {
1461
- process.stdin.off("data", onInput).pause();
1462
- });
1463
1371
  }
1464
1372
 
1465
- function baseMiddleware(rawBase) {
1466
- return (req, res, next) => {
1467
- const url = req.url;
1468
- const pathname = cleanUrl(url);
1469
- const base = rawBase;
1470
- if (pathname.startsWith(base))
1471
- return next();
1472
- if (pathname === "/" || pathname === "/index.html") {
1473
- res.writeHead(302, {
1474
- Location: base + url.slice(pathname.length)
1475
- });
1476
- res.end();
1477
- return;
1478
- }
1479
- const redirectPath = withTrailingSlash(url) !== base ? joinUrlSegments(base, url) : base;
1480
- if (req.headers.accept?.includes("text/html")) {
1481
- res.writeHead(404, {
1482
- "Content-Type": "text/html"
1483
- });
1484
- res.end(
1485
- `The server is configured with a public base URL of ${base} - did you mean to visit <a href="${redirectPath}">${redirectPath}</a> instead?`
1486
- );
1487
- } else {
1488
- res.writeHead(404, {
1489
- "Content-Type": "text/plain"
1490
- });
1491
- res.end(
1492
- `The server is configured with a public base URL of ${base} - did you mean to visit ${redirectPath} instead?`
1493
- );
1373
+ function fromNodeHeaders(nodeHeaders) {
1374
+ const headers = new Headers();
1375
+ for (const [key, values] of Object.entries(nodeHeaders)) {
1376
+ if (values) {
1377
+ if (Array.isArray(values)) {
1378
+ for (const value of values)
1379
+ headers.append(key, value);
1380
+ } else {
1381
+ headers.set(key, values);
1382
+ }
1494
1383
  }
1384
+ }
1385
+ return headers;
1386
+ }
1387
+ function fromNodeRequest(nodeReq) {
1388
+ const origin = nodeReq.headers.origin && nodeReq.headers.origin !== "null" ? nodeReq.headers.origin : `http://${nodeReq.headers.host}`;
1389
+ invariant(
1390
+ nodeReq.originalUrl,
1391
+ "Expected `nodeReq.originalUrl` to be defined"
1392
+ );
1393
+ const url = new URL(nodeReq.originalUrl, origin);
1394
+ const init = {
1395
+ method: nodeReq.method,
1396
+ headers: fromNodeHeaders(nodeReq.headers)
1495
1397
  };
1398
+ return new Request(url.href, init);
1496
1399
  }
1497
1400
 
1498
- async function dev(ssgOptions = {}, viteConfig = {}) {
1401
+ async function dev(ssgOptions = {}, viteConfig = {}, customOptions) {
1499
1402
  const mode = process.env.MODE || process.env.NODE_ENV || ssgOptions.mode || "development";
1500
1403
  const config = await vite.resolveConfig(viteConfig, "serve", mode, mode);
1501
1404
  const cwd = process.cwd();
1502
1405
  const root = config.root || cwd;
1503
- const httpsOptions = config.server.https;
1504
- setBase(config.rawBase);
1505
1406
  const {
1506
1407
  entry = await detectEntry(root),
1507
1408
  onBeforePageRender,
@@ -1513,21 +1414,12 @@ async function dev(ssgOptions = {}, viteConfig = {}) {
1513
1414
  const template = await fs__default.readFile(node_path.join(root, "index.html"), "utf-8");
1514
1415
  let viteServer;
1515
1416
  globalThis.__ssr_start_time = performance.now();
1516
- createServer().then(async (app) => {
1517
- const port = viteServer.config.server.port || 5173;
1518
- if (httpsOptions) {
1519
- const localHttpsOptions = typeof httpsOptions === "boolean" ? await devcert.certificateFor(["localhost"]) : httpsOptions;
1520
- const server = https__default.createServer(localHttpsOptions, app);
1521
- server.listen(port, () => {
1522
- printServerInfo(viteServer, false, true);
1523
- bindShortcuts(viteServer, server);
1524
- });
1525
- } else {
1526
- const server = app.listen(port, () => {
1527
- printServerInfo(viteServer);
1528
- bindShortcuts(viteServer, server);
1529
- });
1530
- }
1417
+ createServer().catch((err) => {
1418
+ console.error(
1419
+ `${kolorist.red(`failed to start server. error:`)}
1420
+ ${err.stack}`
1421
+ );
1422
+ process.exit(1);
1531
1423
  });
1532
1424
  async function createServer() {
1533
1425
  process.env.__DEV_MODE_SSR = "true";
@@ -1535,108 +1427,105 @@ async function dev(ssgOptions = {}, viteConfig = {}) {
1535
1427
  const { jsdomGlobal } = await import('./chunks/jsdomGlobal.cjs');
1536
1428
  jsdomGlobal();
1537
1429
  }
1538
- const app = express__default();
1539
1430
  viteServer = await vite.createServer({
1540
- // ...options,
1541
- server: { middlewareMode: true },
1542
- appType: "custom"
1543
- });
1544
- app.use(baseMiddleware(getBase()));
1545
- app.use((req, res, next) => {
1546
- viteServer.middlewares.handle(req, res, next);
1547
- });
1548
- app.use("*", async (req, res) => {
1549
- try {
1550
- const url = req.originalUrl;
1551
- const indexHTML = await viteServer.transformIndexHtml(url, template);
1552
- const createRoot = await viteServer.ssrLoadModule(ssrEntry).then((m) => m.createRoot);
1553
- const appCtx = await createRoot(false, url);
1554
- const { routes, getStyleCollector, base: base2, app: app2 } = appCtx;
1555
- const transformedIndexHTML = await onBeforePageRender?.(url, indexHTML, appCtx) || indexHTML;
1556
- const styleCollector = getStyleCollector ? await getStyleCollector() : null;
1557
- const { appHTML, bodyAttributes, htmlAttributes, metaAttributes, styleTag, routerContext } = await render(app2 ?? [...routes], createFetchRequest(req), styleCollector, base2);
1558
- metaAttributes.push(styleTag);
1559
- const matchesEntries = routerContext?.matches.map((match) => match.route.entry).filter((entry2) => !!entry2).map((entry2) => entry2[0] === "/" ? entry2 : `/${entry2}`) ?? [];
1560
- const mods = await Promise.all(
1561
- [entry, ...matchesEntries].map(async (entry2) => await viteServer.moduleGraph.getModuleByUrl(entry2))
1562
- );
1563
- const assetsUrls = /* @__PURE__ */ new Set();
1564
- const collectAssets = async (mod) => {
1565
- if (!mod || !mod?.ssrTransformResult)
1566
- return;
1567
- const { deps = [], dynamicDeps = [] } = mod?.ssrTransformResult;
1568
- const allDeps = [...deps, ...dynamicDeps];
1569
- for (const dep of allDeps) {
1570
- if (dep.endsWith(".css")) {
1571
- assetsUrls.add(dep);
1572
- } else if (dep.endsWith(".ts") || dep.endsWith(".tsx")) {
1573
- const depModule = await viteServer.moduleGraph.getModuleByUrl(dep);
1574
- depModule && await collectAssets(depModule);
1575
- }
1431
+ ...viteConfig,
1432
+ plugins: [
1433
+ ...viteConfig.plugins ?? [],
1434
+ {
1435
+ name: "vite-react-ssg:dev-server-remix",
1436
+ configureServer(server) {
1437
+ return () => {
1438
+ server.middlewares.use(async (req, res, _next) => {
1439
+ try {
1440
+ const url = req.originalUrl;
1441
+ const indexHTML = await viteServer.transformIndexHtml(url, template);
1442
+ const createRoot = await viteServer.ssrLoadModule(ssrEntry).then((m) => m.createRoot);
1443
+ const appCtx = await createRoot(false, url);
1444
+ const { routes, getStyleCollector, base, app } = appCtx;
1445
+ const transformedIndexHTML = await onBeforePageRender?.(url, indexHTML, appCtx) || indexHTML;
1446
+ const styleCollector = getStyleCollector ? await getStyleCollector() : null;
1447
+ const { appHTML, bodyAttributes, htmlAttributes, metaAttributes, styleTag, routerContext } = await render(app ?? [...routes], fromNodeRequest(req), styleCollector, base);
1448
+ metaAttributes.push(styleTag);
1449
+ const matchesEntries = routerContext?.matches.map((match) => match.route.entry).filter((entry2) => !!entry2).map((entry2) => entry2[0] === "/" ? entry2 : `/${entry2}`) ?? [];
1450
+ const mods = await Promise.all(
1451
+ [ssrEntry, entry, ...matchesEntries].map(async (entry2) => await viteServer.moduleGraph.getModuleByUrl(entry2))
1452
+ );
1453
+ const assetsUrls = /* @__PURE__ */ new Set();
1454
+ const collectAssets = async (mod) => {
1455
+ if (!mod || !mod?.ssrTransformResult)
1456
+ return;
1457
+ const { deps = [], dynamicDeps = [] } = mod?.ssrTransformResult;
1458
+ const allDeps = [...deps, ...dynamicDeps];
1459
+ for (const dep of allDeps) {
1460
+ if (dep.endsWith(".css")) {
1461
+ assetsUrls.add(dep);
1462
+ } else if (dep.endsWith(".ts") || dep.endsWith(".tsx")) {
1463
+ const depModule = await viteServer.moduleGraph.getModuleByUrl(dep);
1464
+ depModule && await collectAssets(depModule);
1465
+ }
1466
+ }
1467
+ };
1468
+ await Promise.all(mods.map(async (mod) => collectAssets(mod)));
1469
+ const preloadLink = [...assetsUrls].map((item) => createLink$1(joinUrlSegments(config.base, item)));
1470
+ metaAttributes.push(...preloadLink);
1471
+ const renderedHTML = await renderHTML({
1472
+ rootContainerId,
1473
+ appHTML,
1474
+ indexHTML: transformedIndexHTML,
1475
+ metaAttributes,
1476
+ bodyAttributes,
1477
+ htmlAttributes,
1478
+ initialState: null
1479
+ });
1480
+ const transformed = await onPageRendered?.(url, renderedHTML, appCtx) || renderedHTML;
1481
+ res.statusCode = 200;
1482
+ res.setHeader("Content-Type", "text/html");
1483
+ const isDev = "pluginContainer" in server;
1484
+ const headers = isDev ? server.config.server.headers : server.config.preview.headers;
1485
+ vite.send(req, res, transformed, "html", { headers });
1486
+ } catch (e) {
1487
+ viteServer.ssrFixStacktrace(e);
1488
+ console.error(`[vite-react-ssg] error: ${e.stack}`);
1489
+ res.statusCode = 500;
1490
+ res.end(e.stack);
1491
+ }
1492
+ });
1493
+ };
1576
1494
  }
1577
- };
1578
- await Promise.all(mods.map(async (mod) => collectAssets(mod)));
1579
- const preloadLink = [...assetsUrls].map((item) => createLink(item));
1580
- metaAttributes.push(...preloadLink);
1581
- const renderedHTML = await renderHTML({
1582
- rootContainerId,
1583
- appHTML,
1584
- indexHTML: transformedIndexHTML,
1585
- metaAttributes,
1586
- bodyAttributes,
1587
- htmlAttributes,
1588
- initialState: null
1589
- });
1590
- const transformed = await onPageRendered?.(url, renderedHTML, appCtx) || renderedHTML;
1591
- res.status(200).set({ "Content-Type": "text/html" }).end(transformed);
1592
- } catch (e) {
1593
- viteServer.ssrFixStacktrace(e);
1594
- console.error(`[vite-react-ssg] error: ${e.stack}`);
1595
- res.status(500).end(e.stack);
1596
- }
1495
+ }
1496
+ ]
1597
1497
  });
1598
- return app;
1498
+ await viteServer.listen();
1499
+ printServerInfo(viteServer, !!customOptions);
1500
+ viteServer.bindCLIShortcuts({ print: true });
1501
+ return viteServer;
1599
1502
  }
1600
1503
  }
1601
- async function printServerInfo(server, onlyUrl = false, https2 = false) {
1504
+ async function printServerInfo(server, onlyUrl = false) {
1505
+ if (onlyUrl)
1506
+ return server.printUrls();
1602
1507
  const info = server.config.logger.info;
1603
- const port = server.config.server.port || 5173;
1604
- const protocol = https2 ? "https" : "http";
1605
- const url = `${protocol}://localhost:${port}/${removeLeadingSlash(getBase())}`;
1606
- if (!onlyUrl) {
1607
- let ssrReadyMessage = " -- SSR";
1608
- if (globalThis.__ssr_start_time) {
1609
- ssrReadyMessage += ` ready in ${kolorist.reset(kolorist.bold(`${Math.round(
1610
- // @ts-expect-error global var
1611
- performance.now() - globalThis.__ssr_start_time
1612
- )}ms`))}`;
1613
- }
1614
- info(
1615
- `
1508
+ let ssrReadyMessage = " -- SSR";
1509
+ if (globalThis.__ssr_start_time) {
1510
+ ssrReadyMessage += ` ready in ${kolorist.reset(kolorist.bold(`${Math.round(
1511
+ // @ts-expect-error global var
1512
+ performance.now() - globalThis.__ssr_start_time
1513
+ )}ms`))}`;
1514
+ }
1515
+ info(
1516
+ `
1616
1517
  ${kolorist.bgLightCyan(` VITE-REACT-SSG v${version} `)}`,
1617
- { clear: !server.config.logger.hasWarned }
1618
- );
1619
- info(
1620
- `${kolorist.cyan(`
1518
+ { clear: !server.config.logger.hasWarned }
1519
+ );
1520
+ info(
1521
+ `${kolorist.cyan(`
1621
1522
  VITE v${vite.version}`) + kolorist.dim(ssrReadyMessage)}
1622
1523
  `
1623
- );
1624
- }
1524
+ );
1625
1525
  info(
1626
1526
  kolorist.green(" dev server running at:")
1627
1527
  );
1628
- printUrls(url, info);
1629
- }
1630
- function printUrls(url, info) {
1631
- const colorUrl = (url2) => kolorist.cyan(url2.replace(/:(\d+)\//, (_, port) => `:${kolorist.bold(port)}/`));
1632
- info(` ${kolorist.green("\u279C")} ${kolorist.bold("Local")}: ${colorUrl(url)}`);
1633
- }
1634
- let base = "";
1635
- function getBase() {
1636
- return base;
1637
- }
1638
- function setBase(newBase) {
1639
- base = newBase;
1528
+ server.printUrls();
1640
1529
  }
1641
1530
 
1642
1531
  exports.build = build;
package/dist/node.d.cts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { InlineConfig } from 'vite';
2
- import { b as ViteReactSSGOptions } from './shared/vite-react-ssg.d734eb79.cjs';
2
+ import { b as ViteReactSSGOptions } from './shared/vite-react-ssg.870c683b.cjs';
3
3
  import 'critters';
4
4
  import 'react';
5
5
  import 'react-router-dom';
6
6
 
7
7
  declare function build(ssgOptions?: Partial<ViteReactSSGOptions>, viteConfig?: InlineConfig): Promise<void>;
8
8
 
9
- declare function dev(ssgOptions?: Partial<ViteReactSSGOptions>, viteConfig?: InlineConfig): Promise<void>;
9
+ declare function dev(ssgOptions?: Partial<ViteReactSSGOptions>, viteConfig?: InlineConfig, customOptions?: unknown): Promise<void>;
10
10
 
11
11
  export { build, dev };