@inglorious/ssx 2.3.2 → 2.4.0

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/README.md CHANGED
@@ -49,15 +49,15 @@ SSX renders your entity-based web apps to HTML on the server, then hydrates them
49
49
  ### Installation
50
50
 
51
51
  ```bash
52
- npm install @inglorious/ssx @inglorious/web
52
+ pnpm add @inglorious/ssx @inglorious/web
53
53
  ```
54
54
 
55
55
  ### Create Your First Site
56
56
 
57
57
  ```bash
58
- npx @inglorious/create-app my-site --template ssx-js
58
+ pnpm create @inglorious/app my-site --template=ssx-js
59
59
  cd my-site
60
- npm run dev
60
+ pnpm dev
61
61
  ```
62
62
 
63
63
  Or manually:
@@ -118,28 +118,28 @@ export const metadata = {
118
118
  ### Development
119
119
 
120
120
  ```bash
121
- npm run dev
121
+ pnpm dev
122
122
  # → Dev server at http://localhost:3000
123
123
  ```
124
124
 
125
125
  ### Build
126
126
 
127
127
  ```bash
128
- npm run build
128
+ pnpm build
129
129
  # → Static site in dist/
130
130
  ```
131
131
 
132
132
  ### Preview
133
133
 
134
134
  ```bash
135
- npm run preview
135
+ pnpm preview
136
136
  # → Production server at http://localhost:3000 (serves static files + API routes)
137
137
  ```
138
138
 
139
139
  Or use the CLI directly:
140
140
 
141
141
  ```bash
142
- npx ssx serve
142
+ pnpm exec ssx serve
143
143
  ```
144
144
 
145
145
  Deploy `dist/` to:
@@ -505,6 +505,25 @@ api.notify("navigate", {
505
505
 
506
506
  Routes are lazy-loaded on demand, keeping initial bundle size small.
507
507
 
508
+ ### 🎨 Styles
509
+
510
+ Import CSS where it's used, as in any Vite app: CSS modules, a component's `style.css`, a package's stylesheet. `ssx build` links what each page needs in that page's HTML, so it is styled before any JavaScript runs:
511
+
512
+ ```javascript
513
+ // src/pages/about.js
514
+ import { html } from "@inglorious/web"
515
+
516
+ import styles from "./about.module.css"
517
+
518
+ export const About = {
519
+ render() {
520
+ return html`<h1 class=${styles.title}>About</h1>`
521
+ },
522
+ }
523
+ ```
524
+
525
+ For stylesheets in `public/`, list them in `site.config.js` as `styles`: every page links them.
526
+
508
527
  ### 🖼️ Image Optimization
509
528
 
510
529
  SSX includes built-in image optimization using `vite-plugin-image-optimizer`.
package/bin/ssx.js CHANGED
@@ -14,7 +14,6 @@ import { ssr } from "../src/ssr/index.js"
14
14
  const __filename = fileURLToPath(import.meta.url)
15
15
  const __dirname = path.dirname(__filename)
16
16
 
17
- // Read package.json for version
18
17
  const packageJson = JSON.parse(
19
18
  await readFile(path.join(__dirname, "../package.json"), "utf-8"),
20
19
  )
@@ -31,7 +30,6 @@ program
31
30
  .description("Start development server with hot reload")
32
31
  .option("-c, --config <file>", "config file name", "site.config.js")
33
32
  .option("-r, --root <dir>", "root directory", ".")
34
- // No default here: an explicit port overrides the config's, 3000 otherwise.
35
33
  .option("-p, --port <port>", "dev server port (default: 3000)")
36
34
  .action(async (options) => {
37
35
  const cwd = process.cwd()
@@ -78,12 +76,6 @@ program
78
76
  rootDir,
79
77
  outDir,
80
78
  })
81
-
82
- // if (result.skipped) {
83
- // console.log(
84
- // `\n⚡ Incremental build saved time by skipping ${result.skipped} unchanged pages`,
85
- // )
86
- // }
87
79
  } catch (error) {
88
80
  console.error("Build failed:", error)
89
81
  process.exit(1)
@@ -96,13 +88,13 @@ program
96
88
  .option("-c, --config <file>", "config file name", "site.config.js")
97
89
  .option("-r, --root <dir>", "root directory", ".")
98
90
  .option("-o, --out <dir>", "output directory", "dist")
99
- .option("-p, --port <port>", "server port", 3000)
91
+ .option("-p, --port <port>", "server port (default: 3000)")
100
92
  .action(async (options) => {
101
93
  const cwd = process.cwd()
102
94
  const rootDir = path.resolve(cwd, options.root)
103
95
  const configPath = resolveConfigFile(rootDir, options.config)
104
96
  const outDir = path.resolve(cwd, options.out)
105
- const port = Number(options.port)
97
+ const port = options.port ? Number(options.port) : undefined
106
98
 
107
99
  try {
108
100
  await serve({
@@ -126,12 +118,12 @@ program
126
118
  .description("Start an SSR runtime server that renders pages on demand")
127
119
  .option("-c, --config <file>", "config file name", "site.config.js")
128
120
  .option("-r, --root <dir>", "root directory", ".")
129
- .option("-p, --port <port>", "server port", 3000)
121
+ .option("-p, --port <port>", "server port (default: 3000)")
130
122
  .action(async (options) => {
131
123
  const cwd = process.cwd()
132
124
  const rootDir = path.resolve(cwd, options.root)
133
125
  const configPath = resolveConfigFile(rootDir, options.config)
134
- const port = Number(options.port)
126
+ const port = options.port ? Number(options.port) : undefined
135
127
 
136
128
  try {
137
129
  await ssr({
@@ -150,8 +142,6 @@ program
150
142
 
151
143
  program.parse()
152
144
 
153
- // The config lives in src/, where it is loaded from: site.config.ts is used
154
- // when there is no site.config.js.
155
145
  function resolveConfigFile(rootDir, configFile) {
156
146
  if (configFile === "site.config.js") {
157
147
  const jsPath = path.resolve(rootDir, "src", "site.config.js")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/ssx",
3
- "version": "2.3.2",
3
+ "version": "2.4.0",
4
4
  "description": "Server-Side-X. Xecution? Xperience? Who knows.",
5
5
  "author": "Matteo Antony Mistretta <antony.mistretta@gmail.com> (https://ingloriouscoderz.it)",
6
6
  "license": "MIT",
@@ -49,33 +49,33 @@
49
49
  },
50
50
  "sideEffects": false,
51
51
  "dependencies": {
52
- "@inglorious/store": "^12.1.1",
53
- "@inglorious/utils": "^5.1.0",
54
- "@inglorious/web": "^6.10.2",
52
+ "@inglorious/store": "^12.9.1",
53
+ "@inglorious/utils": "^5.4.1",
54
+ "@inglorious/web": "^6.31.1",
55
55
  "@lit-labs/ssr": "^4.1.0",
56
- "commander": "^15.0.0",
56
+ "commander": "^15.1.0",
57
57
  "connect": "^3.7.0",
58
- "fast-xml-parser": "^5.11.1",
59
- "glob": "^13.0.6",
58
+ "fast-xml-parser": "^5.12.1",
59
+ "glob": "^14.0.6",
60
60
  "gray-matter": "^4.0.3",
61
61
  "highlight.js": "^11.12.0",
62
- "katex": "^0.19.0",
62
+ "katex": "^0.19.1",
63
63
  "markdown-it": "^15.0.3",
64
64
  "markdown-it-texmath": "^1.0.0",
65
- "mermaid": "^12.2.0",
66
- "sharp": "^0.35.4",
65
+ "mermaid": "^12.3.0",
66
+ "sharp": "^0.35.5",
67
67
  "svgo": "^4.1.0",
68
- "vite": "^8.3.4",
68
+ "vite": "^8.3.8",
69
69
  "vite-plugin-image-optimizer": "^2.0.3"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@inglorious/eslint-config": "1.2.0",
73
- "@inglorious/logo": "3.0.27",
74
- "prettier": "^3.9.6",
75
- "vitest": "^5.0.0"
73
+ "@inglorious/logo": "3.0.28",
74
+ "prettier": "^3.10.1",
75
+ "vitest": "^5.1.1"
76
76
  },
77
77
  "engines": {
78
- "node": ">= 22"
78
+ "node": ">= 26"
79
79
  },
80
80
  "scripts": {
81
81
  "format": "prettier --write .",
@@ -21,6 +21,7 @@ import { generatePages } from "./pages.js"
21
21
  import { copyPublicDir } from "./public.js"
22
22
  import { generateRSS } from "./rss.js"
23
23
  import { generateSitemap } from "./sitemap.js"
24
+ import { linkPageStyles } from "./styles.js"
24
25
  import { createViteConfig } from "./vite-config.js"
25
26
 
26
27
  const mockRm = vi.hoisted(() => vi.fn())
@@ -52,10 +53,13 @@ vi.mock("./pages.js")
52
53
  vi.mock("./public.js")
53
54
  vi.mock("./rss.js")
54
55
  vi.mock("./sitemap.js")
56
+ vi.mock("./styles.js", async (importOriginal) => ({
57
+ ...(await importOriginal()),
58
+ linkPageStyles: vi.fn(),
59
+ }))
55
60
  vi.mock("./vite-config.js")
56
61
 
57
62
  describe("build", () => {
58
- // Mock console to keep output clean
59
63
  vi.spyOn(console, "log").mockImplementation(() => {})
60
64
 
61
65
  beforeEach(() => {
@@ -71,9 +75,8 @@ describe("build", () => {
71
75
  })
72
76
 
73
77
  it("should run a full build sequence", async () => {
74
- // Setup mocks
75
78
  loadConfig.mockResolvedValue({})
76
- loadManifest.mockResolvedValue(null) // First build
79
+ loadManifest.mockResolvedValue(null)
77
80
  getPages.mockResolvedValue([{ path: "/" }])
78
81
  hashSharedSources.mockResolvedValue("hash")
79
82
  generateStore.mockResolvedValue({
@@ -91,13 +94,12 @@ describe("build", () => {
91
94
 
92
95
  const result = await build({ rootDir: "src", outDir: "dist" })
93
96
 
94
- // Verify sequence
95
97
  expect(fs.rm).toHaveBeenCalledWith("dist", { recursive: true, force: true })
96
98
  expect(fs.mkdir).toHaveBeenCalledWith("dist", { recursive: true })
97
99
  expect(copyPublicDir).toHaveBeenCalled()
98
100
  expect(getPages).toHaveBeenCalled()
99
101
  expect(generateStore).toHaveBeenCalled()
100
- expect(generatePages).toHaveBeenCalledTimes(2) // Changed + Skipped (empty)
102
+ expect(generatePages).toHaveBeenCalledTimes(2)
101
103
  expect(fs.writeFile).toHaveBeenCalledWith(
102
104
  path.normalize("dist/index.html"),
103
105
  "<html></html>",
@@ -105,6 +107,10 @@ describe("build", () => {
105
107
  )
106
108
  expect(generateApp).toHaveBeenCalled()
107
109
  expect(viteBuild).toHaveBeenCalled()
110
+ expect(linkPageStyles).toHaveBeenCalledWith(
111
+ [{ path: "/", html: "<html></html>" }],
112
+ { outDir: "dist", viteConfig: { mode: "production" } },
113
+ )
108
114
  expect(saveManifest).toHaveBeenCalled()
109
115
 
110
116
  expect(result).toEqual({ changed: 1, skipped: 0 })
@@ -124,14 +130,13 @@ describe("build", () => {
124
130
  })
125
131
 
126
132
  generatePages
127
- .mockResolvedValueOnce([{ path: "/changed", html: "<html></html>" }]) // Changed
128
- .mockResolvedValueOnce([{ path: "/skipped" }]) // Skipped
133
+ .mockResolvedValueOnce([{ path: "/changed", html: "<html></html>" }])
134
+ .mockResolvedValueOnce([{ path: "/skipped" }])
129
135
 
130
136
  const result = await build({ incremental: true })
131
137
 
132
138
  expect(determineRebuildPages).toHaveBeenCalled()
133
139
  expect(generatePages).toHaveBeenCalledTimes(2)
134
- // Should only write changed pages
135
140
  expect(fs.writeFile).toHaveBeenCalledWith(
136
141
  expect.stringContaining("changed"),
137
142
  expect.any(String),
@@ -20,6 +20,7 @@ import { generatePages } from "./pages.js"
20
20
  import { copyPublicDir } from "./public.js"
21
21
  import { generateRSS } from "./rss.js"
22
22
  import { generateSitemap } from "./sitemap.js"
23
+ import { linkPageStyles, pageFilePath } from "./styles.js"
23
24
  import { createViteConfig } from "./vite-config.js"
24
25
 
25
26
  /**
@@ -54,39 +55,29 @@ export async function build(options = {}) {
54
55
 
55
56
  console.log("🔨 Starting build...\n")
56
57
 
57
- // Create a temporary Vite server to load modules (supports TS)
58
58
  const vite = await createServer({
59
59
  ...createViteConfig(mergedOptions),
60
60
  mode: "production",
61
61
  server: { middlewareMode: true, hmr: false },
62
62
  appType: "custom",
63
- // This server only loads modules for SSR. Discovering client deps would
64
- // scan the client entry, which is not written yet.
65
63
  optimizeDeps: { noDiscovery: true },
66
64
  })
67
65
  const loader = (p) => vite.ssrLoadModule(p)
68
66
 
69
- // 0. Get all pages to build (Fail fast if source is broken)
70
67
  const allPages = await getPages(pagesDir, mergedOptions, loader)
71
68
  console.log(`📄 Found ${allPages.length} pages\n`)
72
69
 
73
- // Load previous build manifest
74
70
  const manifest = incremental && !force ? await loadManifest(outDir) : null
75
71
 
76
- // 1. Clean and create output directory
77
72
  if (force || !manifest) {
78
- // Clean output directory if forced or first build
79
73
  await fs.rm(outDir, { recursive: true, force: true })
80
74
  await fs.mkdir(outDir, { recursive: true })
81
75
  } else {
82
- // Ensure output directory exists
83
76
  await fs.mkdir(outDir, { recursive: true })
84
77
  }
85
78
 
86
- // 2. Copy public assets before generating pages (could be useful if need to read `public/data.json`)
87
79
  await copyPublicDir(mergedOptions)
88
80
 
89
- // Determine which pages need rebuilding
90
81
  const sharedHash = await hashSharedSources(rootDir)
91
82
  const runtimeHash = await hashRuntime()
92
83
  const getPageHash = createPageHasher(vite)
@@ -111,17 +102,14 @@ export async function build(options = {}) {
111
102
  }
112
103
  }
113
104
 
114
- // 4. Generate store with all types and initial entities
115
105
  const store = await generateStore(allPages, mergedOptions, loader)
116
106
 
117
- // 5. Render only pages that changed
118
107
  const changedPages = await generatePages(
119
108
  store,
120
109
  pagesToChange,
121
110
  mergedOptions,
122
111
  loader,
123
112
  )
124
- // For skipped pages, load their metadata from disk if needed for sitemap/RSS
125
113
  const skippedPages = await generatePages(
126
114
  store,
127
115
  pagesToSkip,
@@ -134,21 +122,17 @@ export async function build(options = {}) {
134
122
  (page) => page.html || page.metadata,
135
123
  )
136
124
 
137
- // Combine rendered and skipped pages for sitemap/RSS
138
125
  const allGeneratedPages = [...staticChangedPages, ...staticSkippedPages]
139
126
 
140
127
  if (staticChangedPages.length) {
141
- // 6. Generate client-side JavaScript
142
128
  console.log("\n💾 Writing files...\n")
143
129
 
144
- // 7. Write HTML pages
145
130
  for (const page of staticChangedPages) {
146
131
  const filePath = await writePageToDisk(page.path, page.html, outDir)
147
132
  console.log(` ✓ ${filePath}`)
148
133
  }
149
134
  }
150
135
 
151
- // 8. Always regenerate client-side JavaScript (it's cheap and ensures consistency)
152
136
  console.log("\n📝 Generating client scripts...\n")
153
137
 
154
138
  const app = await generateApp(
@@ -159,31 +143,26 @@ export async function build(options = {}) {
159
143
  await fs.writeFile(path.join(outDir, "main.js"), app, "utf-8")
160
144
  console.log(` ✓ main.js\n`)
161
145
 
162
- // 9. Generate sitemap if enabled
163
146
  if (sitemap?.hostname) {
164
147
  console.log("\n🗺️ Generating sitemap.xml...\n")
165
148
  await generateSitemap(allGeneratedPages, { outDir, ...sitemap })
166
149
  }
167
150
 
168
- // 10. Generate RSS feed if enabled
169
151
  if (rss?.link) {
170
152
  console.log("\n📡 Generating RSS feed...\n")
171
153
  await generateRSS(allGeneratedPages, { outDir, ...rss })
172
154
  }
173
155
 
174
- // 11. Bundle with Vite
175
156
  console.log("\n📦 Bundling with Vite...\n")
176
157
  const viteConfig = {
177
158
  ...createViteConfig(mergedOptions),
178
159
  mode: "production",
179
160
  }
180
161
  await viteBuild(viteConfig)
162
+ await linkPageStyles(allGeneratedPages, { outDir, viteConfig })
181
163
 
182
164
  await vite.close()
183
- // 12. Cleanup
184
- // console.log("\n🧹 Cleaning up...\n")
185
165
 
186
- // 13. Save manifest for next build
187
166
  if (incremental) {
188
167
  const newManifest = await createManifest(
189
168
  allGeneratedPages,
@@ -219,19 +198,10 @@ export async function build(options = {}) {
219
198
  * @returns {Promise<string>} The absolute path of the written file.
220
199
  */
221
200
  async function writePageToDisk(pagePath, html, outDir = "dist") {
222
- // Convert URL path to file path
223
- // / -> dist/index.html
224
- // /about -> dist/about/index.html
225
- // /blog/post-1 -> dist/blog/post-1/index.html
201
+ const filePath = pageFilePath(pagePath, outDir)
226
202
 
227
- // Remove leading slash
228
- const cleanPath = pagePath.replace(/^\//, "")
229
- const filePath = path.join(outDir, cleanPath, "index.html")
230
-
231
- // Ensure directory exists
232
203
  await fs.mkdir(path.dirname(filePath), { recursive: true })
233
204
 
234
- // Write file
235
205
  await fs.writeFile(filePath, html, "utf-8")
236
206
 
237
207
  return filePath
@@ -26,7 +26,6 @@ export async function loadManifest(outDir) {
26
26
  const content = await fs.readFile(manifestPath, "utf-8")
27
27
  return JSON.parse(content)
28
28
  } catch {
29
- // No manifest exists (first build or clean build)
30
29
  return { pages: {}, shared: null, runtime: null, buildTime: null }
31
30
  }
32
31
  }
@@ -206,7 +205,6 @@ export async function determineRebuildPages(
206
205
  runtimeHash,
207
206
  getPageHash = hashPageAlone,
208
207
  ) {
209
- // If shared sources changed, rebuild all pages
210
208
  if (manifest.shared !== sharedHash) {
211
209
  console.log("📦 Shared sources changed, rebuilding all pages\n")
212
210
  return { pagesToBuild: pages, pagesToSkip: [] }
@@ -102,7 +102,6 @@ describe("manifest", () => {
102
102
  describe("hashFile", () => {
103
103
  it("should return md5 hash of file content", async () => {
104
104
  fs.readFile.mockResolvedValue("content")
105
- // md5("content") = 9a0364b9e99bb480dd25e1f0284c8555
106
105
  const hash = await hashFile("file.txt")
107
106
  expect(hash).toBe("9a0364b9e99bb480dd25e1f0284c8555")
108
107
  })
@@ -172,11 +171,10 @@ describe("manifest", () => {
172
171
  shared: "hash",
173
172
  pages: {
174
173
  "/changed": { hash: "old-hash" },
175
- "/same": { hash: "9a0364b9e99bb480dd25e1f0284c8555" }, // md5("content")
174
+ "/same": { hash: "9a0364b9e99bb480dd25e1f0284c8555" },
176
175
  },
177
176
  }
178
177
 
179
- // Mock hashFile behavior via fs.readFile
180
178
  fs.readFile.mockImplementation(async (path) => {
181
179
  if (path === "changed.js") return "new content"
182
180
  if (path === "same.js") return "content"
@@ -17,12 +17,10 @@ export function extractPageMetadata(store, page, entity, options = {}) {
17
17
 
18
18
  const getPageOption = createGetPageOption(store, module, entity)
19
19
 
20
- // common metadata
21
20
  const updatedAt = getPageOption("updatedAt", DEFAULT_OPTIONS)
22
21
  const changefreq = getPageOption("changefreq", DEFAULT_OPTIONS)
23
22
  const priority = getPageOption("priority", DEFAULT_OPTIONS)
24
23
 
25
- // sitemap metadata
26
24
  const loc = `${hostname}${path}`
27
25
 
28
26
  let lastmod
@@ -35,7 +33,6 @@ export function extractPageMetadata(store, page, entity, options = {}) {
35
33
  lastmod = new Date().toISOString().split("T")[0]
36
34
  }
37
35
 
38
- // rss metadata
39
36
  const title = getPageOption("title", DEFAULT_OPTIONS)
40
37
  const meta = getPageOption("meta", DEFAULT_OPTIONS)
41
38
  const description = meta.description
@@ -43,7 +43,6 @@ export async function generatePages(store, pages, options = {}, loader) {
43
43
  if (page.locale) {
44
44
  entity.locale = page.locale
45
45
  }
46
- // Translations in the page's locale, for `load` and the render.
47
46
  await waitForLocale(store, page.locale)
48
47
 
49
48
  if (module.load) {
@@ -15,16 +15,13 @@ vi.mock("../store/index.js", () => ({
15
15
  vi.mock("./metadata.js")
16
16
 
17
17
  describe("generatePages", () => {
18
- // Create a temporary page module for testing dynamic imports
19
18
  const tempDir = path.join(import.meta.dirname, "__temp_pages__")
20
19
  const pageFile = path.join(tempDir, "test-page.js")
21
20
 
22
- // Mock console.log to keep test output clean
23
21
  vi.spyOn(console, "log").mockImplementation(() => {})
24
22
 
25
23
  beforeAll(async () => {
26
24
  await fs.mkdir(tempDir, { recursive: true })
27
- // Create a dummy module that exports a load function
28
25
  await fs.writeFile(
29
26
  pageFile,
30
27
  `
@@ -57,7 +54,7 @@ describe("generatePages", () => {
57
54
 
58
55
  expect(pages[0].html).toBe("<html></html>")
59
56
  expect(pages[0].metadata).toEqual({ title: "Test" })
60
- expect(pages[0].loaded).toBe(true) // Verify load() was called
57
+ expect(pages[0].loaded).toBe(true)
61
58
  expect(renderPage).toHaveBeenCalled()
62
59
  expect(extractPageMetadata).toHaveBeenCalled()
63
60
  })
@@ -12,7 +12,6 @@ import path from "node:path"
12
12
  export async function copyPublicDir(options = {}) {
13
13
  const { outDir = "dist", publicDir = "public" } = options
14
14
 
15
- // Copy public directory to dist
16
15
  const publicPath = path.join(process.cwd(), publicDir)
17
16
  const publicExists = await fs
18
17
  .access(publicPath)
@@ -36,12 +36,8 @@ describe("copyPublicDir", () => {
36
36
  })
37
37
 
38
38
  it("should copy public assets when directory exists", async () => {
39
- // Mock access to succeed
40
39
  fs.access.mockResolvedValue(undefined)
41
40
 
42
- // Mock readdir sequence:
43
- // 1. Root directory contains 'favicon.ico' (file) and 'assets' (dir)
44
- // 2. 'assets' directory contains 'logo.png' (file)
45
41
  fs.readdir
46
42
  .mockResolvedValueOnce([
47
43
  { name: "favicon.ico", isDirectory: () => false },
@@ -51,17 +47,13 @@ describe("copyPublicDir", () => {
51
47
 
52
48
  await copyPublicDir({ outDir: "dist", publicDir: "public" })
53
49
 
54
- // Verify mkdir calls (root dest + subfolder)
55
50
  expect(fs.mkdir).toHaveBeenCalledTimes(2)
56
51
  expect(fs.mkdir).toHaveBeenCalledWith("dist", { recursive: true })
57
52
  expect(fs.mkdir).toHaveBeenCalledWith(expect.stringContaining("assets"), {
58
53
  recursive: true,
59
54
  })
60
55
 
61
- // Verify copyFile calls
62
56
  expect(fs.copyFile).toHaveBeenCalledTimes(2)
63
- // We can't easily check exact paths without mocking process.cwd() or doing complex string matching,
64
- // but we can check that it was called for the files we defined.
65
57
  const copyCalls = fs.copyFile.mock.calls
66
58
  const filesCopied = copyCalls.map((call) => path.basename(call[0]))
67
59
  expect(filesCopied).toContain("favicon.ico")
@@ -21,7 +21,6 @@ export async function generateSitemap(pages = [], options = {}) {
21
21
 
22
22
  const items = pages.filter(filter).map(({ metadata }) => metadata)
23
23
 
24
- // Build XML
25
24
  const urls = items.map(renderItem)
26
25
 
27
26
  const xml = `<?xml version="1.0" encoding="UTF-8"?>
@@ -0,0 +1,110 @@
1
+ import fs from "node:fs/promises"
2
+ import path from "node:path"
3
+
4
+ export const STYLES_MANIFEST = ".vite/ssx-styles.json"
5
+
6
+ const VITE_DEFAULT_MANIFEST = ".vite/manifest.json"
7
+ const LINK_MARKER = "data-ssx-style"
8
+ const LINK_PATTERN = new RegExp(
9
+ `\\s*<link rel="stylesheet" href="[^"]*" ${LINK_MARKER}>`,
10
+ "g",
11
+ )
12
+
13
+ /**
14
+ * Links the CSS that page modules import into each pre-rendered page, so a
15
+ * page is styled before any JavaScript runs: the entry's own styles, and
16
+ * those of the page module and everything it statically imports (CSS
17
+ * modules, a component's `style.css`, a package's stylesheet).
18
+ *
19
+ * Reads the Vite manifest the build wrote, and removes it afterwards when
20
+ * SSX asked for it. Running it again replaces the links it added before, so
21
+ * pages skipped by an incremental build stay current.
22
+ *
23
+ * @param {Array<{ path: string, filePath: string }>} pages - Pages written to `outDir`.
24
+ * @param {Object} options
25
+ * @param {string} options.outDir
26
+ * @param {Object} options.viteConfig - The config the client bundle was built with.
27
+ */
28
+ export async function linkPageStyles(pages, { outDir, viteConfig }) {
29
+ const manifestFile = getManifestFile(viteConfig)
30
+ if (!manifestFile) return
31
+
32
+ const manifestPath = path.join(outDir, manifestFile)
33
+ const manifest = await readManifest(manifestPath)
34
+ if (!manifest) return
35
+
36
+ const base = viteConfig.base ?? "/"
37
+ const entryKeys = Object.keys(manifest).filter((key) => manifest[key].isEntry)
38
+
39
+ for (const page of pages) {
40
+ const keys = [...entryKeys, toManifestKey(page.filePath)]
41
+ const files = [...new Set(keys.flatMap((key) => collectCss(manifest, key)))]
42
+ const hrefs = files.map((file) => `${base}${file}`)
43
+ await linkStyles(pageFilePath(page.path, outDir), hrefs)
44
+ }
45
+
46
+ if (manifestFile === STYLES_MANIFEST) {
47
+ await fs.rm(manifestPath, { force: true })
48
+ await fs.rmdir(path.dirname(manifestPath)).catch(() => {})
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Where a page's HTML lives in the output directory.
54
+ *
55
+ * @param {string} pagePath - The URL path of the page, e.g. "/blog/hello".
56
+ * @param {string} [outDir="dist"]
57
+ * @returns {string}
58
+ */
59
+ export function pageFilePath(pagePath, outDir = "dist") {
60
+ const cleanPath = pagePath.replace(/^\//, "")
61
+ return path.join(outDir, cleanPath, "index.html")
62
+ }
63
+
64
+ function getManifestFile(viteConfig) {
65
+ const manifest = viteConfig.build?.manifest
66
+ if (manifest === true) return VITE_DEFAULT_MANIFEST
67
+ return typeof manifest === "string" ? manifest : null
68
+ }
69
+
70
+ async function readManifest(manifestPath) {
71
+ try {
72
+ return JSON.parse(await fs.readFile(manifestPath, "utf-8"))
73
+ } catch {
74
+ return null
75
+ }
76
+ }
77
+
78
+ // The manifest is keyed by source paths relative to the project root.
79
+ function toManifestKey(filePath) {
80
+ return path
81
+ .relative(process.cwd(), path.resolve(filePath))
82
+ .split(path.sep)
83
+ .join("/")
84
+ }
85
+
86
+ function collectCss(manifest, key, seen = new Set()) {
87
+ const chunk = manifest[key]
88
+ if (!chunk || seen.has(key)) return []
89
+ seen.add(key)
90
+
91
+ const imported = (chunk.imports ?? []).flatMap((importKey) =>
92
+ collectCss(manifest, importKey, seen),
93
+ )
94
+ return [...imported, ...(chunk.css ?? [])]
95
+ }
96
+
97
+ async function linkStyles(htmlPath, hrefs) {
98
+ const html = await fs.readFile(htmlPath, "utf-8").catch(() => null)
99
+ if (html === null) return
100
+
101
+ const links = hrefs
102
+ .map((href) => `<link rel="stylesheet" href="${href}" ${LINK_MARKER}>`)
103
+ .join("\n")
104
+ const unlinked = html.replace(LINK_PATTERN, "")
105
+ const linked = links
106
+ ? unlinked.replace("</head>", `${links}\n</head>`)
107
+ : unlinked
108
+
109
+ if (linked !== html) await fs.writeFile(htmlPath, linked, "utf-8")
110
+ }