@inglorious/ssx 2.1.20 → 2.2.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 +96 -26
- package/package.json +4 -3
- package/src/dev/api.js +7 -1
- package/src/dev/index.js +2 -1
- package/src/render/html.test.js +6 -3
- package/src/router/index.js +43 -1
- package/src/router/router.test.js +40 -1
- package/src/scripts/app.js +17 -1
- package/src/scripts/app.test.js +5 -1
- package/src/ssr/index.js +28 -8
- package/src/ssr/render-request.test.js +85 -0
package/README.md
CHANGED
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
[](https://www.npmjs.com/package/@inglorious/ssx)
|
|
4
4
|
[](https://opensource.org/licenses/MIT)
|
|
5
5
|
|
|
6
|
-
**Static Site Xecution** -
|
|
6
|
+
**Static Site Xecution** - Pre-rendered sites with [@inglorious/web](https://www.npmjs.com/package/@inglorious/web): static-site generation, server-side rendering on demand, client-side hydration, API routes and zero-config routing.
|
|
7
7
|
|
|
8
|
-
SSX
|
|
8
|
+
SSX renders your entity-based web apps to HTML on the server, then hydrates them in the browser. Pages are generated at build time as static files, or rendered on each request when they need fresh data or per-request behavior: one page can be static and the next server-rendered. Think Next.js or Astro, but with the simplicity and predictability of Inglorious Web's entity architecture.
|
|
9
9
|
|
|
10
10
|
---
|
|
11
11
|
|
|
@@ -13,14 +13,14 @@ SSX takes your entity-based web apps and generates optimized static HTML with fu
|
|
|
13
13
|
|
|
14
14
|
### ⚡️ Fast by Default
|
|
15
15
|
|
|
16
|
-
- **Pre-rendered HTML** - Every page
|
|
17
|
-
- **Instant load times** -
|
|
18
|
-
- **CDN-ready** -
|
|
16
|
+
- **Pre-rendered HTML** - Every page arrives as HTML, built ahead or rendered on request
|
|
17
|
+
- **Instant load times** - Static pages need no server work at all
|
|
18
|
+
- **CDN-ready** - A static site deploys anywhere static files are served
|
|
19
19
|
- **Perfect Lighthouse scores** - SEO and performance out of the box
|
|
20
20
|
|
|
21
21
|
### 🎯 Simple Architecture
|
|
22
22
|
|
|
23
|
-
- **
|
|
23
|
+
- **Static or server-rendered** - Pure static files, or a server for the pages that need one
|
|
24
24
|
- **No complex build configs** - Convention over configuration
|
|
25
25
|
- **File-based routing** - Pages are just files in `src/pages/`
|
|
26
26
|
- **Entity-based state** - Same familiar patterns from @inglorious/web
|
|
@@ -154,11 +154,12 @@ Deploy `dist/` to:
|
|
|
154
154
|
|
|
155
155
|
## Features
|
|
156
156
|
|
|
157
|
-
### ⚙️ Rendering Modes: SSG
|
|
157
|
+
### ⚙️ Rendering Modes: SSG and SSR
|
|
158
158
|
|
|
159
|
-
|
|
159
|
+
Every page is rendered to HTML on the server and hydrated in the browser. What changes is _when_ it is rendered:
|
|
160
160
|
|
|
161
|
-
|
|
161
|
+
- **Static (the default).** `ssx build` renders the page once and writes it to `dist/`. Its `load` runs at build time.
|
|
162
|
+
- **Server-rendered.** A page that exports `ssr` is rendered on each request, with its `load` run for that request, so it can show fresh data or vary per request:
|
|
162
163
|
|
|
163
164
|
```javascript
|
|
164
165
|
// src/pages/checkout.js
|
|
@@ -178,7 +179,29 @@ export const Checkout = {
|
|
|
178
179
|
}
|
|
179
180
|
```
|
|
180
181
|
|
|
181
|
-
|
|
182
|
+
Each request gets a store of its own, so one visitor's data never reaches another's page. `load` gets the page with the `request`, a Web Fetch API `Request` like the one API routes get, to read headers and cookies from:
|
|
183
|
+
|
|
184
|
+
```javascript
|
|
185
|
+
export const ssr = true
|
|
186
|
+
|
|
187
|
+
export async function load(entity, page) {
|
|
188
|
+
const session = page.request.headers.get("cookie")
|
|
189
|
+
entity.orders = await getOrders(session)
|
|
190
|
+
}
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
A dynamic route that exports `ssr` needs no `staticPaths`: any path its pattern matches is a page, and `page.params` come from the URL. `src/pages/orders/_id.js` answers `/orders/42`, with `page.params.id === "42"`, and every other order alike.
|
|
194
|
+
|
|
195
|
+
#### Deploying
|
|
196
|
+
|
|
197
|
+
| The site has… | Build | Run in production | Serves |
|
|
198
|
+
| ----------------------- | ----------- | ---------------------------------------------- | ----------------------------------------------------------- |
|
|
199
|
+
| Only static pages | `ssx build` | Any static host, or `ssx serve` for API routes | `dist/`, and `src/api/` with `ssx serve` |
|
|
200
|
+
| Pages that export `ssr` | — | `ssx ssr` | Every page, rendered on request, the API routes, and assets |
|
|
201
|
+
|
|
202
|
+
`ssx build` skips the pages that export `ssr`, and `ssx serve` only serves what the build wrote, so a site with server-rendered pages runs on `ssx ssr`. It renders every page on request, static ones included, from your sources through Vite, with no build step. In development, `ssx dev` renders every page on request as well.
|
|
203
|
+
|
|
204
|
+
A static dynamic route lists its paths with [`staticPaths`](#-dynamic-routes-with-staticpaths), as the build has to know them; a server-rendered one does not.
|
|
182
205
|
|
|
183
206
|
### 🗺️ Sitemap & RSS Generation
|
|
184
207
|
|
|
@@ -325,7 +348,7 @@ export const entities = {
|
|
|
325
348
|
|
|
326
349
|
### 🔄 Data Loading
|
|
327
350
|
|
|
328
|
-
Load
|
|
351
|
+
Load a page's data with the `load` export: at build time for a static page, on each request for one that exports `ssr`:
|
|
329
352
|
|
|
330
353
|
```javascript
|
|
331
354
|
// src/pages/blog.js
|
|
@@ -348,7 +371,7 @@ export const Blog = {
|
|
|
348
371
|
},
|
|
349
372
|
}
|
|
350
373
|
|
|
351
|
-
//
|
|
374
|
+
// Runs on the server, before the page renders
|
|
352
375
|
export async function load(entity) {
|
|
353
376
|
const response = await fetch("https://api.example.com/posts")
|
|
354
377
|
entity.posts = await response.json()
|
|
@@ -359,7 +382,7 @@ export const metadata = {
|
|
|
359
382
|
}
|
|
360
383
|
```
|
|
361
384
|
|
|
362
|
-
The `load` function runs on the server during build.
|
|
385
|
+
The `load` function runs on the server: during the build for a static page, on every request for a server-rendered one. Its data is serialized into the HTML and available immediately on the client.
|
|
363
386
|
|
|
364
387
|
### 🎨 Dynamic Routes with `staticPaths`
|
|
365
388
|
|
|
@@ -520,6 +543,35 @@ title: My Post
|
|
|
520
543
|
This is a markdown page.
|
|
521
544
|
```
|
|
522
545
|
|
|
546
|
+
### 🧩 JSX and Vue Pages
|
|
547
|
+
|
|
548
|
+
Pages can be written in JSX or Vue-like templates instead of lit-html. Add the plugin to the `vite` config in `site.config.js`, and SSX uses it both to render pages at build time and to hydrate them in the browser:
|
|
549
|
+
|
|
550
|
+
```javascript
|
|
551
|
+
import { jsx } from "@inglorious/vite-plugin-jsx"
|
|
552
|
+
|
|
553
|
+
export default {
|
|
554
|
+
vite: {
|
|
555
|
+
plugins: [jsx()],
|
|
556
|
+
},
|
|
557
|
+
}
|
|
558
|
+
```
|
|
559
|
+
|
|
560
|
+
With [`@inglorious/vite-plugin-jsx`](https://www.npmjs.com/package/@inglorious/vite-plugin-jsx), pages are `.jsx` or `.tsx` files, exporting their type and `metadata` as usual.
|
|
561
|
+
|
|
562
|
+
With [`@inglorious/vite-plugin-vue`](https://www.npmjs.com/package/@inglorious/vite-plugin-vue), a `.vue` file only exports its type, so SSX does not route it. Each page is a `.js` or `.ts` module that re-exports the type from its `.vue` file, next to its `metadata`:
|
|
563
|
+
|
|
564
|
+
```javascript
|
|
565
|
+
// src/pages/about.js
|
|
566
|
+
export { About } from "./about.vue"
|
|
567
|
+
|
|
568
|
+
export const metadata = {
|
|
569
|
+
title: "About",
|
|
570
|
+
}
|
|
571
|
+
```
|
|
572
|
+
|
|
573
|
+
`create-app` sets either up with `--template=ssx-js --syntax=jsx` or `--syntax=vue`.
|
|
574
|
+
|
|
523
575
|
### ⚡ Serverless Functions (API Routes)
|
|
524
576
|
|
|
525
577
|
SSX supports serverless functions for dynamic API endpoints. Create files in `src/api/` that export HTTP method handlers:
|
|
@@ -671,7 +723,7 @@ Options:
|
|
|
671
723
|
|
|
672
724
|
### `ssx serve`
|
|
673
725
|
|
|
674
|
-
Serves the production build with static files and API routes:
|
|
726
|
+
Serves the production build with static files and API routes. Pages that export `ssr` are not in the build: serve a site with them with `ssx ssr`.
|
|
675
727
|
|
|
676
728
|
```bash
|
|
677
729
|
pnpm ssx serve [options]
|
|
@@ -685,7 +737,7 @@ Options:
|
|
|
685
737
|
|
|
686
738
|
### `ssx ssr`
|
|
687
739
|
|
|
688
|
-
Starts a
|
|
740
|
+
Starts a server that renders every page on request, those that export `ssr` and static ones alike, and serves the API routes and assets. It renders from your sources through Vite, so it needs no `ssx build`:
|
|
689
741
|
|
|
690
742
|
```bash
|
|
691
743
|
pnpm ssx ssr [options]
|
|
@@ -723,19 +775,20 @@ my-site/
|
|
|
723
775
|
|
|
724
776
|
## Comparison to Other Tools
|
|
725
777
|
|
|
726
|
-
| Feature | SSX | Next.js
|
|
727
|
-
| ------------------ | ----------- |
|
|
728
|
-
| Pre-rendered HTML | ✅ | ✅
|
|
729
|
-
|
|
|
730
|
-
| Client
|
|
731
|
-
|
|
|
732
|
-
|
|
|
733
|
-
|
|
|
734
|
-
|
|
|
778
|
+
| Feature | SSX | Next.js | Astro | Eleventy |
|
|
779
|
+
| ------------------ | ----------- | -------- | ------ | -------- |
|
|
780
|
+
| Pre-rendered HTML | ✅ | ✅ | ✅ | ✅ |
|
|
781
|
+
| SSR on request | ✅ | ✅ | ✅ | ❌ |
|
|
782
|
+
| Client hydration | ✅ lit-html | ✅ React | ✅ Any | ❌ |
|
|
783
|
+
| Client routing | ✅ | ✅ | ✅ | ❌ |
|
|
784
|
+
| Lazy loading | ✅ | ✅ | ✅ | ❌ |
|
|
785
|
+
| Entity-based state | ✅ | ❌ | ❌ | ❌ |
|
|
786
|
+
| Zero config | ✅ | ❌ | ❌ | ❌ |
|
|
787
|
+
| Framework agnostic | ❌ | ❌ | ✅ | ✅ |
|
|
735
788
|
|
|
736
789
|
SSX is perfect if you:
|
|
737
790
|
|
|
738
|
-
- Want static site performance
|
|
791
|
+
- Want static site performance, with server rendering where it is needed
|
|
739
792
|
- Love entity-based architecture
|
|
740
793
|
- Prefer convention over configuration
|
|
741
794
|
- Need full client-side interactivity
|
|
@@ -909,6 +962,22 @@ await dev({
|
|
|
909
962
|
})
|
|
910
963
|
```
|
|
911
964
|
|
|
965
|
+
### SSR Server API
|
|
966
|
+
|
|
967
|
+
Renders every page on request, and serves the API routes:
|
|
968
|
+
|
|
969
|
+
```javascript
|
|
970
|
+
import { ssr } from "@inglorious/ssx/ssr"
|
|
971
|
+
|
|
972
|
+
const server = await ssr({
|
|
973
|
+
rootDir: ".",
|
|
974
|
+
port: 3000,
|
|
975
|
+
configFile: "site.config.js",
|
|
976
|
+
})
|
|
977
|
+
|
|
978
|
+
server.close()
|
|
979
|
+
```
|
|
980
|
+
|
|
912
981
|
### Production Server API
|
|
913
982
|
|
|
914
983
|
```javascript
|
|
@@ -942,6 +1011,7 @@ Check out these example projects:
|
|
|
942
1011
|
- [x] Markdown support
|
|
943
1012
|
- [x] i18n routing and locale-aware client navigation
|
|
944
1013
|
- [x] API routes (serverless functions)
|
|
1014
|
+
- [x] Server-side rendering on request
|
|
945
1015
|
|
|
946
1016
|
---
|
|
947
1017
|
|
|
@@ -954,7 +1024,7 @@ SSX embraces the philosophy of [@inglorious/web](https://www.npmjs.com/package/@
|
|
|
954
1024
|
- **Predictability over magic** - Explicit is better than implicit
|
|
955
1025
|
- **Standards over abstractions** - Use the platform
|
|
956
1026
|
|
|
957
|
-
|
|
1027
|
+
Rendering on the server should be simple, at build time or on request. SSX makes it simple.
|
|
958
1028
|
|
|
959
1029
|
---
|
|
960
1030
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inglorious/ssx",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.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",
|
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
"./dev": "./src/dev/index.js",
|
|
31
31
|
"./build": "./src/build/index.js",
|
|
32
32
|
"./serve": "./src/serve/index.js",
|
|
33
|
+
"./ssr": "./src/ssr/index.js",
|
|
33
34
|
"./markdown": "./src/utils/markdown.js",
|
|
34
35
|
"./i18n": {
|
|
35
36
|
"types": "./types/i18n.d.ts",
|
|
@@ -50,7 +51,7 @@
|
|
|
50
51
|
"dependencies": {
|
|
51
52
|
"@inglorious/store": "12.0.0",
|
|
52
53
|
"@inglorious/utils": "5.1.0",
|
|
53
|
-
"@inglorious/web": "6.9.
|
|
54
|
+
"@inglorious/web": "6.9.1",
|
|
54
55
|
"@lit-labs/ssr": "^4.1.0",
|
|
55
56
|
"commander": "^15.0.0",
|
|
56
57
|
"connect": "^3.7.0",
|
|
@@ -69,7 +70,7 @@
|
|
|
69
70
|
},
|
|
70
71
|
"devDependencies": {
|
|
71
72
|
"@inglorious/eslint-config": "1.2.0",
|
|
72
|
-
"@inglorious/logo": "3.0.
|
|
73
|
+
"@inglorious/logo": "3.0.24",
|
|
73
74
|
"prettier": "^3.9.6",
|
|
74
75
|
"vitest": "^5.0.0"
|
|
75
76
|
},
|
package/src/dev/api.js
CHANGED
|
@@ -53,7 +53,13 @@ export const createApiMiddleware = (rootDir, loader, onError) => {
|
|
|
53
53
|
}
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
-
|
|
56
|
+
/**
|
|
57
|
+
* The incoming request as a Web Fetch API `Request`, as API routes and
|
|
58
|
+
* server-rendered pages receive it.
|
|
59
|
+
* @param {import("node:http").IncomingMessage} req
|
|
60
|
+
* @returns {Request}
|
|
61
|
+
*/
|
|
62
|
+
export function createRequest(req) {
|
|
57
63
|
const protocol = req.socket.encrypted ? "https" : "http"
|
|
58
64
|
const host = req.headers.host || "localhost"
|
|
59
65
|
const url = `${protocol}://${host}${req.url}`
|
package/src/dev/index.js
CHANGED
|
@@ -3,7 +3,7 @@ import { createServer } from "vite"
|
|
|
3
3
|
|
|
4
4
|
import { renderRequest } from "../ssr/index.js"
|
|
5
5
|
import { loadConfig } from "../utils/config.js"
|
|
6
|
-
import { createApiMiddleware } from "./api.js"
|
|
6
|
+
import { createApiMiddleware, createRequest } from "./api.js"
|
|
7
7
|
import { createViteConfig } from "./vite-config.js"
|
|
8
8
|
|
|
9
9
|
/**
|
|
@@ -55,6 +55,7 @@ export async function dev(options = {}) {
|
|
|
55
55
|
options: { ...mergedOptions, isDev: true },
|
|
56
56
|
loader,
|
|
57
57
|
viteServer,
|
|
58
|
+
request: createRequest(req),
|
|
58
59
|
})
|
|
59
60
|
|
|
60
61
|
if (!result) {
|
package/src/render/html.test.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createStore } from "@inglorious/store"
|
|
2
2
|
import { html } from "@inglorious/web"
|
|
3
|
+
import { when } from "@inglorious/web/directives/when"
|
|
3
4
|
import { describe, expect, it } from "vitest"
|
|
4
5
|
|
|
5
6
|
import { toHTML } from "./html.js"
|
|
@@ -99,9 +100,11 @@ describe("await toHTML", () => {
|
|
|
99
100
|
types: {
|
|
100
101
|
content: {
|
|
101
102
|
render: (entity) =>
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
103
|
+
when(
|
|
104
|
+
entity.isVisible,
|
|
105
|
+
() => html`<p>Visible content</p>`,
|
|
106
|
+
() => html`<p>Hidden</p>`,
|
|
107
|
+
),
|
|
105
108
|
},
|
|
106
109
|
},
|
|
107
110
|
entities: {
|
package/src/router/index.js
CHANGED
|
@@ -31,7 +31,19 @@ export async function getPages(pagesDir = "pages", options, loader) {
|
|
|
31
31
|
const module = await load(route.filePath)
|
|
32
32
|
const moduleName = getModuleName(module)
|
|
33
33
|
|
|
34
|
-
if (isDynamic(route.pattern)) {
|
|
34
|
+
if (isDynamic(route.pattern) && module.ssr) {
|
|
35
|
+
// Rendered on request: any path the pattern matches is a page, its
|
|
36
|
+
// params read from the URL then. No staticPaths needed.
|
|
37
|
+
addPages(pages, options, {
|
|
38
|
+
pattern: route.pattern,
|
|
39
|
+
path: route.pattern,
|
|
40
|
+
params: {},
|
|
41
|
+
isDynamic: true,
|
|
42
|
+
moduleName,
|
|
43
|
+
modulePath: route.modulePath,
|
|
44
|
+
filePath: route.filePath,
|
|
45
|
+
})
|
|
46
|
+
} else if (isDynamic(route.pattern)) {
|
|
35
47
|
let { staticPaths = [] } = module
|
|
36
48
|
if (typeof staticPaths === "function") {
|
|
37
49
|
staticPaths = await staticPaths()
|
|
@@ -144,6 +156,36 @@ export function matchRoute(pattern, url) {
|
|
|
144
156
|
})
|
|
145
157
|
}
|
|
146
158
|
|
|
159
|
+
/**
|
|
160
|
+
* The params a URL gives a route pattern, such as `{ id: "42" }` for
|
|
161
|
+
* `/posts/:id` and `/posts/42`, or null when it does not match. A catch-all
|
|
162
|
+
* `*` takes the rest of the URL as `path`.
|
|
163
|
+
*
|
|
164
|
+
* @param {string} pattern - The route pattern (e.g. "/posts/:id").
|
|
165
|
+
* @param {string} url - The actual URL (e.g. "/posts/42").
|
|
166
|
+
* @returns {Object|null} The params, or null.
|
|
167
|
+
*/
|
|
168
|
+
export function matchParams(pattern, url) {
|
|
169
|
+
const patternParts = pattern.split("/").filter(Boolean)
|
|
170
|
+
const urlParts = url.split("/").filter(Boolean)
|
|
171
|
+
const params = {}
|
|
172
|
+
|
|
173
|
+
for (const [index, part] of patternParts.entries()) {
|
|
174
|
+
if (part === "*") {
|
|
175
|
+
params.path = urlParts.slice(index).map(decodeURIComponent).join("/")
|
|
176
|
+
return params
|
|
177
|
+
}
|
|
178
|
+
if (index >= urlParts.length) return null
|
|
179
|
+
if (part.startsWith(":")) {
|
|
180
|
+
params[part.slice(1)] = decodeURIComponent(urlParts[index])
|
|
181
|
+
} else if (part !== urlParts[index]) {
|
|
182
|
+
return null
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
return patternParts.length === urlParts.length ? params : null
|
|
187
|
+
}
|
|
188
|
+
|
|
147
189
|
/**
|
|
148
190
|
* Converts a file path to a route pattern.
|
|
149
191
|
* Examples:
|
|
@@ -2,7 +2,7 @@ import path from "node:path"
|
|
|
2
2
|
|
|
3
3
|
import { afterEach, describe, expect, it, vi } from "vitest"
|
|
4
4
|
|
|
5
|
-
import { getPages, getRoutes, matchRoute } from "./index.js"
|
|
5
|
+
import { getPages, getRoutes, matchParams, matchRoute } from "./index.js"
|
|
6
6
|
|
|
7
7
|
const ROOT_DIR = path.join(import.meta.dirname, "..", "fixtures")
|
|
8
8
|
const PAGES_DIR = path.join(ROOT_DIR, "src", "pages")
|
|
@@ -127,4 +127,43 @@ describe("router", () => {
|
|
|
127
127
|
expect(matchRoute("/about", "/about/")).toBe(true)
|
|
128
128
|
})
|
|
129
129
|
})
|
|
130
|
+
|
|
131
|
+
describe("matchParams", () => {
|
|
132
|
+
it("reads a dynamic segment's value from the URL", () => {
|
|
133
|
+
expect(matchParams("/posts/:id", "/posts/42")).toEqual({ id: "42" })
|
|
134
|
+
expect(matchParams("/posts/:id", "/posts/caf%C3%A9")).toEqual({
|
|
135
|
+
id: "café",
|
|
136
|
+
})
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
it("takes the rest of the URL for a catch-all", () => {
|
|
140
|
+
expect(matchParams("/docs/*", "/docs/guide/intro")).toEqual({
|
|
141
|
+
path: "guide/intro",
|
|
142
|
+
})
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
it("is null when the URL does not match", () => {
|
|
146
|
+
expect(matchParams("/posts/:id", "/posts")).toBeNull()
|
|
147
|
+
expect(matchParams("/posts/:id", "/blog/42")).toBeNull()
|
|
148
|
+
expect(matchParams("/posts/:id", "/posts/42/edit")).toBeNull()
|
|
149
|
+
})
|
|
150
|
+
})
|
|
151
|
+
|
|
152
|
+
describe("server-rendered dynamic pages", () => {
|
|
153
|
+
it("are registered by their pattern, with no staticPaths", async () => {
|
|
154
|
+
const warn = vi.spyOn(console, "warn").mockImplementation(() => {})
|
|
155
|
+
const loader = async (filePath) =>
|
|
156
|
+
filePath.endsWith("_slug.js")
|
|
157
|
+
? { ssr: true, Post: { render: () => "" } }
|
|
158
|
+
: import(filePath)
|
|
159
|
+
|
|
160
|
+
const pages = await getPages(PAGES_DIR, {}, loader)
|
|
161
|
+
const post = pages.find((page) => page.pattern === "/posts/:slug")
|
|
162
|
+
|
|
163
|
+
expect(post).toMatchObject({ path: "/posts/:slug", isDynamic: true })
|
|
164
|
+
expect(warn).not.toHaveBeenCalledWith(
|
|
165
|
+
expect.stringContaining("posts/_slug.js"),
|
|
166
|
+
)
|
|
167
|
+
})
|
|
168
|
+
})
|
|
130
169
|
})
|
package/src/scripts/app.js
CHANGED
|
@@ -76,8 +76,24 @@ const pages = ${JSON.stringify(
|
|
|
76
76
|
null,
|
|
77
77
|
2,
|
|
78
78
|
)}
|
|
79
|
+
// A server-rendered dynamic page is listed by its pattern, such as /posts/:id.
|
|
80
|
+
const matchesPattern = (pattern, path) => {
|
|
81
|
+
const patternParts = pattern.split("/").filter(Boolean)
|
|
82
|
+
const pathParts = path.split("/").filter(Boolean)
|
|
83
|
+
if (patternParts.includes("*")) {
|
|
84
|
+
const fixed = patternParts.slice(0, patternParts.indexOf("*"))
|
|
85
|
+
return fixed.every((part, i) => part.startsWith(":") || part === pathParts[i])
|
|
86
|
+
}
|
|
87
|
+
return (
|
|
88
|
+
patternParts.length === pathParts.length &&
|
|
89
|
+
patternParts.every((part, i) => part.startsWith(":") || part === pathParts[i])
|
|
90
|
+
)
|
|
91
|
+
}
|
|
92
|
+
|
|
79
93
|
const path = normalizeRoutePath(window.location.pathname)
|
|
80
|
-
const page =
|
|
94
|
+
const page =
|
|
95
|
+
pages.find((page) => normalizeRoutePath(page.path) === path) ??
|
|
96
|
+
pages.find((page) => matchesPattern(page.path, path))
|
|
81
97
|
|
|
82
98
|
const types = { Router }
|
|
83
99
|
${typesAssignment}
|
package/src/scripts/app.test.js
CHANGED
|
@@ -92,8 +92,12 @@ describe("generateApp", () => {
|
|
|
92
92
|
expect(app).toContain(
|
|
93
93
|
`const path = normalizeRoutePath(window.location.pathname)`,
|
|
94
94
|
)
|
|
95
|
+
// Its own path first, then a server-rendered page's pattern.
|
|
95
96
|
expect(app).toContain(
|
|
96
|
-
`
|
|
97
|
+
`pages.find((page) => normalizeRoutePath(page.path) === path) ??`,
|
|
98
|
+
)
|
|
99
|
+
expect(app).toContain(
|
|
100
|
+
`pages.find((page) => matchesPattern(page.path, path))`,
|
|
97
101
|
)
|
|
98
102
|
})
|
|
99
103
|
})
|
package/src/ssr/index.js
CHANGED
|
@@ -3,10 +3,10 @@ import path from "node:path"
|
|
|
3
3
|
import connect from "connect"
|
|
4
4
|
import { createServer } from "vite"
|
|
5
5
|
|
|
6
|
-
import { createApiMiddleware } from "../dev/api.js"
|
|
6
|
+
import { createApiMiddleware, createRequest } from "../dev/api.js"
|
|
7
7
|
import { createViteConfig, virtualFiles } from "../dev/vite-config.js"
|
|
8
8
|
import { renderPage } from "../render/index.js"
|
|
9
|
-
import { getPages, matchRoute } from "../router/index.js"
|
|
9
|
+
import { getPages, matchParams, matchRoute } from "../router/index.js"
|
|
10
10
|
import { generateApp } from "../scripts/app.js"
|
|
11
11
|
import { generateStore } from "../store/index.js"
|
|
12
12
|
import { loadConfig } from "../utils/config.js"
|
|
@@ -53,6 +53,7 @@ export async function ssr(options = {}) {
|
|
|
53
53
|
loader,
|
|
54
54
|
viteServer,
|
|
55
55
|
pages,
|
|
56
|
+
request: createRequest(req),
|
|
56
57
|
})
|
|
57
58
|
|
|
58
59
|
if (!result) {
|
|
@@ -81,9 +82,18 @@ export async function ssr(options = {}) {
|
|
|
81
82
|
}
|
|
82
83
|
}
|
|
83
84
|
|
|
85
|
+
/**
|
|
86
|
+
* Renders the page a URL asks for, with a store of its own: its `load` gets
|
|
87
|
+
* the entity and the page, with the URL's `params` and the `request`.
|
|
88
|
+
*
|
|
89
|
+
* @param {string} url - The URL requested.
|
|
90
|
+
* @param {Object} [context]
|
|
91
|
+
* @param {Request} [context.request] - The request, for `load` to read headers and cookies from.
|
|
92
|
+
* @returns {Promise<{html: string, page: Object, entity: Object, store: Object}|null>} Null when no page matches.
|
|
93
|
+
*/
|
|
84
94
|
export async function renderRequest(
|
|
85
95
|
url,
|
|
86
|
-
{ rootDir = ".", options = {}, loader, viteServer, pages } = {},
|
|
96
|
+
{ rootDir = ".", options = {}, loader, viteServer, pages, request } = {},
|
|
87
97
|
) {
|
|
88
98
|
const [pathname] = String(url || "").split("?")
|
|
89
99
|
|
|
@@ -103,16 +113,26 @@ export async function renderRequest(
|
|
|
103
113
|
await registerApp(resolvedPages, options, loader, viteServer)
|
|
104
114
|
}
|
|
105
115
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
116
|
+
// A page of its own path first, then one whose pattern matches the URL.
|
|
117
|
+
const origPage =
|
|
118
|
+
resolvedPages.find(
|
|
119
|
+
(candidate) =>
|
|
120
|
+
!candidate.isDynamic && matchRoute(candidate.path, pathname),
|
|
121
|
+
) ??
|
|
122
|
+
resolvedPages.find(
|
|
123
|
+
(candidate) =>
|
|
124
|
+
candidate.isDynamic && matchParams(candidate.path, pathname),
|
|
125
|
+
)
|
|
109
126
|
if (!origPage) {
|
|
110
127
|
return null
|
|
111
128
|
}
|
|
112
129
|
|
|
113
130
|
const module = await loader(origPage.filePath)
|
|
114
|
-
const page = { ...origPage }
|
|
115
|
-
|
|
131
|
+
const page = { ...origPage, module, request }
|
|
132
|
+
if (origPage.isDynamic) {
|
|
133
|
+
page.path = pathname
|
|
134
|
+
page.params = matchParams(origPage.path, pathname)
|
|
135
|
+
}
|
|
116
136
|
|
|
117
137
|
const store = await generateStore(resolvedPages, options, loader)
|
|
118
138
|
const [entity] = store._api.getEntities(page.moduleName)
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// @vitest-environment node
|
|
2
|
+
// The server runs on Node, whose Request keeps cookies; a browser-like one
|
|
3
|
+
// drops them.
|
|
4
|
+
import { describe, expect, it, vi } from "vitest"
|
|
5
|
+
|
|
6
|
+
const { generateStore, renderPage } = vi.hoisted(() => ({
|
|
7
|
+
generateStore: vi.fn(),
|
|
8
|
+
renderPage: vi.fn(async () => "<html></html>"),
|
|
9
|
+
}))
|
|
10
|
+
|
|
11
|
+
vi.mock("../store/index.js", () => ({ generateStore }))
|
|
12
|
+
vi.mock("../render/index.js", () => ({ renderPage }))
|
|
13
|
+
vi.mock("../scripts/app.js", () => ({ generateApp: vi.fn(async () => "") }))
|
|
14
|
+
vi.mock("../dev/vite-config.js", () => ({ virtualFiles: new Map() }))
|
|
15
|
+
|
|
16
|
+
import { renderRequest } from "./index.js"
|
|
17
|
+
|
|
18
|
+
const pages = [
|
|
19
|
+
{
|
|
20
|
+
path: "/posts/new",
|
|
21
|
+
pattern: "/posts/new",
|
|
22
|
+
filePath: "new.js",
|
|
23
|
+
moduleName: "newPost",
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
path: "/posts/:id",
|
|
27
|
+
pattern: "/posts/:id",
|
|
28
|
+
isDynamic: true,
|
|
29
|
+
filePath: "post.js",
|
|
30
|
+
moduleName: "post",
|
|
31
|
+
},
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
async function render(url, request) {
|
|
35
|
+
const load = vi.fn()
|
|
36
|
+
const entity = {}
|
|
37
|
+
generateStore.mockResolvedValue({
|
|
38
|
+
_api: { getEntities: () => [entity] },
|
|
39
|
+
})
|
|
40
|
+
const result = await renderRequest(url, {
|
|
41
|
+
pages,
|
|
42
|
+
request,
|
|
43
|
+
loader: async () => ({ ssr: true, load }),
|
|
44
|
+
})
|
|
45
|
+
return { result, load, entity }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
describe("renderRequest for server-rendered pages", () => {
|
|
49
|
+
it("renders a dynamic page for any path its pattern matches, its params from the URL", async () => {
|
|
50
|
+
const { result, load } = await render("/posts/42?ref=home")
|
|
51
|
+
|
|
52
|
+
expect(result.page).toMatchObject({
|
|
53
|
+
moduleName: "post",
|
|
54
|
+
path: "/posts/42",
|
|
55
|
+
params: { id: "42" },
|
|
56
|
+
})
|
|
57
|
+
expect(load).toHaveBeenCalledWith(
|
|
58
|
+
expect.anything(),
|
|
59
|
+
expect.objectContaining({ params: { id: "42" } }),
|
|
60
|
+
)
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
it("prefers a page of its own path to a pattern", async () => {
|
|
64
|
+
const { result } = await render("/posts/new")
|
|
65
|
+
|
|
66
|
+
expect(result.page.moduleName).toBe("newPost")
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
it("gives load the request, for its headers and cookies", async () => {
|
|
70
|
+
const request = new Request("http://localhost/posts/7", {
|
|
71
|
+
headers: { cookie: "session=abc" },
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
const { load } = await render("/posts/7", request)
|
|
75
|
+
|
|
76
|
+
const [, page] = load.mock.calls[0]
|
|
77
|
+
expect(page.request.headers.get("cookie")).toBe("session=abc")
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
it("matches nothing for a path no page has", async () => {
|
|
81
|
+
const { result } = await render("/about")
|
|
82
|
+
|
|
83
|
+
expect(result).toBeNull()
|
|
84
|
+
})
|
|
85
|
+
})
|