@foliwake/next 0.0.0-stage → 0.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/CHANGELOG.md +78 -0
- package/LICENSE +202 -0
- package/README.md +540 -2
- package/dist/cache.d.ts +14 -0
- package/dist/cache.js +31 -0
- package/dist/client.d.ts +1 -0
- package/dist/client.js +3 -0
- package/dist/config.d.ts +33 -0
- package/dist/config.js +53 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +7 -0
- package/dist/page.d.ts +55 -0
- package/dist/page.js +71 -0
- package/dist/routes.d.ts +35 -0
- package/dist/routes.js +35 -0
- package/dist/server.d.ts +10 -0
- package/dist/server.js +22 -0
- package/dist/settings.d.ts +4 -0
- package/dist/settings.js +22 -0
- package/package.json +85 -3
package/README.md
CHANGED
|
@@ -1,3 +1,541 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @foliwake/next
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<!-- usage -->
|
|
4
|
+
|
|
5
|
+
`@foliwake/next` embeds Foliwake pages in a Next.js App Router app. On the server it reads a page's body from
|
|
6
|
+
your Foliwake site with the credential, caches the origin's answer (`'use cache'`, tagged for revalidation),
|
|
7
|
+
checks and prepares the body per request, and adds preload hints. Route handlers serve the page's code
|
|
8
|
+
release and pictures from your app's own origin, and `withFoliwake` validates the config and sets a
|
|
9
|
+
Content-Security-Policy that fits. In the browser, `@foliwake/next/client` (everything of `@foliwake/react`)
|
|
10
|
+
mounts the page's blocks. Use it when your app is a Next 16.2+ App Router app with `cacheComponents`; for
|
|
11
|
+
another React app use `@foliwake/react` with `@foliwake/server`.
|
|
12
|
+
|
|
13
|
+
| Entry | What |
|
|
14
|
+
| --- | --- |
|
|
15
|
+
| `@foliwake/next/config` | `withFoliwake`, `foliwakeCspHeader` for `next.config.ts` |
|
|
16
|
+
| `@foliwake/next` | server-only: `<FoliwakeServerPage>`, `readPage`, `readEnvelopeCached`, `foliwakeTags`, config and origin client |
|
|
17
|
+
| `@foliwake/next/routes` | `codeRoute`, `mediaRoute`: the code and media proxies |
|
|
18
|
+
| `@foliwake/next/cache` | `readEnvelopeCached`: the cached live read alone |
|
|
19
|
+
| `@foliwake/next/client` | `'use client'`: everything of `@foliwake/react` |
|
|
20
|
+
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
The packages are published on npm (npmjs.com) under the `@foliwake` scope; no registry setup or token is
|
|
24
|
+
needed. Install exact versions, the same for every `@foliwake/*` package:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pnpm add @foliwake/next@0.3.0 @foliwake/react@0.3.0 @foliwake/server@0.3.0
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The app also needs `foliwake.remote.json` in its root (or `FOLIWAKE_REMOTE` naming another file): the site,
|
|
31
|
+
its live and preview origins, the names of the variables that hold passwords, and the app settings. The guide
|
|
32
|
+
below describes every key; the schema ships in `@foliwake/server/schemas/remote-2.schema.json`.
|
|
33
|
+
|
|
34
|
+
## Minimal example
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
// next.config.ts
|
|
38
|
+
import { withFoliwake } from '@foliwake/next/config';
|
|
39
|
+
|
|
40
|
+
export default withFoliwake({ cacheComponents: true }, { csp: { reportUri: '/csp-report' } });
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
```tsx
|
|
44
|
+
// app/pages/[[...path]]/page.tsx
|
|
45
|
+
import { Suspense } from 'react';
|
|
46
|
+
import { FoliwakeServerPage } from '@foliwake/next';
|
|
47
|
+
import { FoliwakePage } from '@foliwake/next/client';
|
|
48
|
+
|
|
49
|
+
type Params = Promise<{ path?: string[] }>;
|
|
50
|
+
|
|
51
|
+
export default function Page({ params }: { params: Params }) {
|
|
52
|
+
return (
|
|
53
|
+
<Suspense fallback={null}>
|
|
54
|
+
<LivePage params={params} />
|
|
55
|
+
</Suspense>
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function LivePage({ params }: { params: Params }) {
|
|
60
|
+
const { path } = await params;
|
|
61
|
+
return (
|
|
62
|
+
<FoliwakeServerPage
|
|
63
|
+
path={`/${(path ?? []).join('/')}`}
|
|
64
|
+
prepare={{ rewriteLink: (href) => `/pages${href === '/' ? '' : href}` }}
|
|
65
|
+
render={(page) => <FoliwakePage page={page} as="article" />}
|
|
66
|
+
/>
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
// app/foliwake-code/[...path]/route.ts (the path is app.proxies.code of the config)
|
|
73
|
+
import { codeRoute } from '@foliwake/next/routes';
|
|
74
|
+
|
|
75
|
+
export const { GET, HEAD } = codeRoute({ authorizePreview: false });
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
A missing page, or one outside `app.pages`, calls `notFound()`; a body the check refuses throws to your
|
|
79
|
+
`error.tsx`. The `Suspense` boundary is required with `cacheComponents`.
|
|
80
|
+
|
|
81
|
+
## Examples
|
|
82
|
+
|
|
83
|
+
### Code and media proxies with preview for authors
|
|
84
|
+
|
|
85
|
+
The proxies serve only files of a code release and hashed pictures, add the credential on the server and
|
|
86
|
+
forward nothing from the browser. `authorizePreview` is required: your own author check, or `false` when the
|
|
87
|
+
app never shows preview.
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
// app/foliwake-media/[...path]/route.ts
|
|
91
|
+
import { mediaRoute } from '@foliwake/next/routes';
|
|
92
|
+
|
|
93
|
+
// Your app's sign-in decides; this cookie check is only a placeholder.
|
|
94
|
+
const isAuthor = (request: Request) => (request.headers.get('cookie') ?? '').includes('role=author');
|
|
95
|
+
|
|
96
|
+
export const { GET, HEAD } = mediaRoute({ authorizePreview: isAuthor });
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### A preview page
|
|
100
|
+
|
|
101
|
+
Preview is read on every request (never cached) and loads the preview's code and pictures through the
|
|
102
|
+
proxies, which ask `authorizePreview`. Protect the page itself too.
|
|
103
|
+
|
|
104
|
+
```tsx
|
|
105
|
+
// app/preview/[[...path]]/page.tsx
|
|
106
|
+
import { Suspense } from 'react';
|
|
107
|
+
import { cookies } from 'next/headers';
|
|
108
|
+
import { notFound } from 'next/navigation';
|
|
109
|
+
import { FoliwakeServerPage } from '@foliwake/next';
|
|
110
|
+
import { FoliwakePage } from '@foliwake/next/client';
|
|
111
|
+
|
|
112
|
+
type Params = Promise<{ path?: string[] }>;
|
|
113
|
+
|
|
114
|
+
export default function Preview({ params }: { params: Params }) {
|
|
115
|
+
return <Suspense fallback={null}><PreviewPage params={params} /></Suspense>;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function PreviewPage({ params }: { params: Params }) {
|
|
119
|
+
if ((await cookies()).get('role')?.value !== 'author') notFound();
|
|
120
|
+
const { path } = await params;
|
|
121
|
+
return <FoliwakeServerPage path={`/${(path ?? []).join('/')}`} channel="preview" render={(page) => <FoliwakePage page={page} />} />;
|
|
122
|
+
}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### CSP when the app sets its own headers
|
|
126
|
+
|
|
127
|
+
`withFoliwake(…, { csp })` adds `script-src 'self' 'unsafe-inline'` and the rest of the policy to every route.
|
|
128
|
+
If your app builds its own headers, leave `csp` out and use the value:
|
|
129
|
+
|
|
130
|
+
```ts
|
|
131
|
+
// next.config.ts
|
|
132
|
+
import { foliwakeCspHeader, withFoliwake } from '@foliwake/next/config';
|
|
133
|
+
|
|
134
|
+
export default withFoliwake({
|
|
135
|
+
cacheComponents: true,
|
|
136
|
+
async headers() {
|
|
137
|
+
const csp = foliwakeCspHeader({ reportUri: '/csp-report', extra: { 'connect-src': ['https://api.example.org'] } });
|
|
138
|
+
return [{ source: '/pages/:path*', headers: [{ key: 'Content-Security-Policy', value: csp }] }];
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
A nonce-based policy does not work with partial prerendering and is not supported.
|
|
144
|
+
|
|
145
|
+
### Cache tags and revalidation
|
|
146
|
+
|
|
147
|
+
Only the live origin answer is cached, for `app.revalidate` seconds (default 300) with stale-while-revalidate
|
|
148
|
+
and at most 24 hours. Its tags are `foliwake`, `foliwake:<site>`, `foliwake:<site>:live` and
|
|
149
|
+
`foliwake:<site>:live:page:<path>` (`foliwakeTags`). Foliwake does not notify apps of publications yet, so
|
|
150
|
+
expire them from your own webhook or admin action:
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
// app/api/foliwake-revalidate/route.ts
|
|
154
|
+
import { revalidateTag } from 'next/cache';
|
|
155
|
+
import { foliwakeTags } from '@foliwake/next';
|
|
156
|
+
|
|
157
|
+
export async function POST(request: Request) {
|
|
158
|
+
if (request.headers.get('authorization') !== `Bearer ${process.env.REVALIDATE_TOKEN}`) return new Response(null, { status: 401 });
|
|
159
|
+
const { path } = (await request.json()) as { path?: string };
|
|
160
|
+
// One page, or every live page of the site.
|
|
161
|
+
const tag = path ? foliwakeTags('live', path).at(-1)! : foliwakeTags('live')[2]!;
|
|
162
|
+
revalidateTag(tag, { expire: 0 });
|
|
163
|
+
return Response.json({ revalidated: tag });
|
|
164
|
+
}
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
`revalidateTag(tag, 'max')` refreshes in the background instead (the next request still gets the cached
|
|
168
|
+
page).
|
|
169
|
+
|
|
170
|
+
### Read the page yourself
|
|
171
|
+
|
|
172
|
+
`readPage` gives the prepared page without rendering, for example to pass it to your own client component
|
|
173
|
+
together with other data, or to build metadata.
|
|
174
|
+
|
|
175
|
+
```tsx
|
|
176
|
+
// app/lessons/[slug]/page.tsx
|
|
177
|
+
import { Suspense } from 'react';
|
|
178
|
+
import { FoliwakeImportMap, readPage, emitPreloadHints } from '@foliwake/next';
|
|
179
|
+
import { FoliwakePage } from '@foliwake/next/client';
|
|
180
|
+
|
|
181
|
+
type Params = Promise<{ slug: string }>;
|
|
182
|
+
|
|
183
|
+
export default function Lesson({ params }: { params: Params }) {
|
|
184
|
+
return <Suspense fallback={null}><LessonBody params={params} /></Suspense>;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function LessonBody({ params }: { params: Params }) {
|
|
188
|
+
const { slug } = await params;
|
|
189
|
+
const page = await readPage(`/lessons/${slug}`, { mode: 'practice' });
|
|
190
|
+
emitPreloadHints(page); // <link rel="preload" as="script"> for the blocks, in <head>
|
|
191
|
+
return (
|
|
192
|
+
<>
|
|
193
|
+
<FoliwakeImportMap page={page} />
|
|
194
|
+
<FoliwakePage page={page} />
|
|
195
|
+
</>
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
`<FoliwakeImportMap>` renders the page's import map: blocks import the block kit as `@foliwake/block-kit`,
|
|
201
|
+
and the map points that name at the kit of the page's own code release, scoped to the release's code path
|
|
202
|
+
(`<FoliwakeServerPage>` renders it for you). `@foliwake/client` adds the same map when it is missing. A map
|
|
203
|
+
that arrives after the document's first module load (a client navigation to a page of another code release)
|
|
204
|
+
is honoured only by browsers with multiple import maps (Chrome 133+); module hints are therefore `preload
|
|
205
|
+
as="script"`, never `modulepreload`, which would resolve the kit's specifier before the map is there. With the CSP
|
|
206
|
+
strategy `nonce`, pass the request's nonce to `<FoliwakeServerPage nonce>` / `<FoliwakeImportMap nonce>` and to
|
|
207
|
+
`<FoliwakePage nonce>` (the map the client adds on a navigation).
|
|
208
|
+
|
|
209
|
+
Unlike `<FoliwakeServerPage>`, `readPage` does not call `notFound()`: it throws `FoliwakePageError` (with
|
|
210
|
+
`kind` `not_found`, `not_allowed`, `invalid`, …) for you to handle.
|
|
211
|
+
|
|
212
|
+
### Write the cached read yourself
|
|
213
|
+
|
|
214
|
+
If Next does not compile the packaged cache (an unusual setup), write the cached live read in your app and
|
|
215
|
+
pass it to `<FoliwakeServerPage read={readLiveEnvelope}>`:
|
|
216
|
+
|
|
217
|
+
```ts
|
|
218
|
+
// lib/foliwake.ts
|
|
219
|
+
import { cacheLife, cacheTag } from 'next/cache';
|
|
220
|
+
import { foliwakeConfig, foliwakeTags, originClient, readEnvelope } from '@foliwake/next';
|
|
221
|
+
|
|
222
|
+
export async function readLiveEnvelope(path: string) {
|
|
223
|
+
'use cache';
|
|
224
|
+
cacheLife({ stale: 300, revalidate: 300, expire: 86400 });
|
|
225
|
+
cacheTag(...foliwakeTags('live', path));
|
|
226
|
+
const config = foliwakeConfig();
|
|
227
|
+
return readEnvelope(config, originClient(), config.site, 'live', path);
|
|
228
|
+
}
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
## Compatibility
|
|
232
|
+
|
|
233
|
+
| | |
|
|
234
|
+
| --- | --- |
|
|
235
|
+
| Next.js | 16.2 or newer, below 17 (peer `>=16.2.0 <17`; tested with 16.2.12), App Router with `cacheComponents: true` |
|
|
236
|
+
| React | 19.2 or newer (tested with 19.3.0) |
|
|
237
|
+
| Node.js | 22.22 or newer |
|
|
238
|
+
| Foliwake origin | plain/2: `X-Code-Release` with every `.plain.html` (a body without it is refused) |
|
|
239
|
+
| Config | `foliwake.remote.json` version 2 |
|
|
240
|
+
|
|
241
|
+
Changes per version, breaking ones marked: `CHANGELOG.md` in the package
|
|
242
|
+
(`node_modules/@foliwake/next/CHANGELOG.md`).
|
|
243
|
+
|
|
244
|
+
## Good to know
|
|
245
|
+
|
|
246
|
+
- `withFoliwake` adds `@foliwake/next` to `transpilePackages`: Next compiles `'use cache'` only in code it
|
|
247
|
+
transpiles. If you do not use `withFoliwake`, add it yourself, or write the cached read in your app and pass
|
|
248
|
+
it as `read` (see "Write the cached read yourself" above).
|
|
249
|
+
- Under partial prerendering the status line is sent with the static shell, so a not-found page answers HTTP
|
|
250
|
+
200 with the not-found content.
|
|
251
|
+
- The server modules import `server-only`, which throws when imported outside React Server Components. In unit
|
|
252
|
+
tests outside Next (for example vitest), alias `server-only` to an empty module or run with the
|
|
253
|
+
`react-server` condition. The package imports `next/cache.js`, `next/navigation.js` and `next/server.js`
|
|
254
|
+
fully specified, so Node's ESM resolution finds them; builds of 0.1.0 made before this change import the bare
|
|
255
|
+
`next/cache` and need an alias (`next/cache` → `next/cache.js`) in such tests.
|
|
256
|
+
- Block stylesheets: `<FoliwakePage>` links `components/<name>/<name>.css` for every block on the page
|
|
257
|
+
without reading `components.json`, so blocks without a stylesheet produce 404 links. See the
|
|
258
|
+
`@foliwake/react` notes for the workaround with `page.preload`.
|
|
259
|
+
|
|
260
|
+
## See also
|
|
261
|
+
|
|
262
|
+
- [`@foliwake/server`](https://www.npmjs.com/package/@foliwake/server): every key of `foliwake.remote.json`,
|
|
263
|
+
the proxies and the body check.
|
|
264
|
+
- [`@foliwake/react`](https://www.npmjs.com/package/@foliwake/react): `<FoliwakePage>`, the host and events.
|
|
265
|
+
- [`@foliwake/client`](https://www.npmjs.com/package/@foliwake/client): the browser lifecycle under both.
|
|
266
|
+
|
|
267
|
+
License: Apache-2.0.
|
|
268
|
+
|
|
269
|
+
<!-- usagestop -->
|
|
270
|
+
|
|
271
|
+
## API
|
|
272
|
+
|
|
273
|
+
<!-- api -->
|
|
274
|
+
|
|
275
|
+
<!-- Generated by `pnpm packages:reference` from the type declarations; do not edit by hand. -->
|
|
276
|
+
|
|
277
|
+
### `@foliwake/next`
|
|
278
|
+
|
|
279
|
+
**Functions and components**
|
|
280
|
+
|
|
281
|
+
#### `emitPreloadHints()`
|
|
282
|
+
|
|
283
|
+
Emits the page's hints into the document head (React DOM resource APIs; deduplicated by React). Modules are hinted as `preload as="script"` (the bytes, fetched in parallel), not `modulepreload`: a module preloaded before the page's import map is in the document fails to resolve the kit's specifier for good, and in a Next app the hints reach <head> before the map (which renders with the page, and on a client navigation arrives later).
|
|
284
|
+
|
|
285
|
+
```ts
|
|
286
|
+
function emitPreloadHints(page: FoliwakePageData): void
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
**Returns** `void`
|
|
290
|
+
|
|
291
|
+
#### `foliwakeConfig()`
|
|
292
|
+
|
|
293
|
+
The app's Foliwake config (validated at build time by withFoliwake).
|
|
294
|
+
|
|
295
|
+
```ts
|
|
296
|
+
function foliwakeConfig(): FoliwakeAppConfig
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
**Returns** `FoliwakeAppConfig`
|
|
300
|
+
|
|
301
|
+
#### `FoliwakeImportMap()`
|
|
302
|
+
|
|
303
|
+
The import map of the page's code release (`@foliwake/block-kit` → its block-kit, scoped to the release's code path), as an element to render before the page's blocks load; null for a page without a code release. Browsers honour a map that arrives after the document's first module load (client navigation, a second release) only with multiple import maps (Chrome 133+); `@foliwake/client` adds the same map when it is missing.
|
|
304
|
+
|
|
305
|
+
```ts
|
|
306
|
+
function FoliwakeImportMap({ page, nonce }: {
|
|
307
|
+
page: FoliwakePageData;
|
|
308
|
+
nonce?: string;
|
|
309
|
+
}): ReactNode
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
**Returns** `ReactNode`
|
|
313
|
+
|
|
314
|
+
#### `FoliwakeServerPage()`
|
|
315
|
+
|
|
316
|
+
A Foliwake page in a server component. Missing or not allowed → notFound(); other errors throw (error.tsx).
|
|
317
|
+
|
|
318
|
+
```ts
|
|
319
|
+
function FoliwakeServerPage(props: FoliwakeServerPageProps): Promise<ReactNode>
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
**Returns** `Promise<ReactNode>`
|
|
323
|
+
|
|
324
|
+
#### `foliwakeTags()`
|
|
325
|
+
|
|
326
|
+
Cache tags of a channel (and page): foliwake, foliwake:<site>, foliwake:<site>:<channel>, …:page:<path>.
|
|
327
|
+
|
|
328
|
+
```ts
|
|
329
|
+
function foliwakeTags(channel: ChannelName, path?: string): string[]
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
**Returns** `string[]`
|
|
333
|
+
|
|
334
|
+
#### `originClient()`
|
|
335
|
+
|
|
336
|
+
The origin client; credentials are read from process.env per request.
|
|
337
|
+
|
|
338
|
+
```ts
|
|
339
|
+
function originClient(): OriginClient
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
**Returns** `OriginClient`
|
|
343
|
+
|
|
344
|
+
#### `readEnvelopeCached()`
|
|
345
|
+
|
|
346
|
+
The live envelope of `path` from Next's cache (stale-while-revalidate); 404 → FoliwakePageError('not_found').
|
|
347
|
+
|
|
348
|
+
```ts
|
|
349
|
+
function readEnvelopeCached(path: string): Promise<PageEnvelope>
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
**Returns** `Promise<PageEnvelope>`
|
|
353
|
+
|
|
354
|
+
#### `readPage()`
|
|
355
|
+
|
|
356
|
+
The prepared page. Preview: `connection()` first (per request, never cached).
|
|
357
|
+
|
|
358
|
+
```ts
|
|
359
|
+
function readPage(path: string, opts?: ReadPageOptions): Promise<FoliwakePageData>
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
**Returns** `Promise<FoliwakePageData>`
|
|
363
|
+
|
|
364
|
+
**Interfaces**
|
|
365
|
+
|
|
366
|
+
#### `FoliwakeServerPageProps`
|
|
367
|
+
|
|
368
|
+
Props of `<FoliwakeServerPage>`.
|
|
369
|
+
|
|
370
|
+
```ts
|
|
371
|
+
interface FoliwakeServerPageProps
|
|
372
|
+
```
|
|
373
|
+
|
|
374
|
+
| Member | Type | Description |
|
|
375
|
+
| --- | --- | --- |
|
|
376
|
+
| `path` | `string` | The site's page path (`/`, `/lessons/a`); it must match `app.pages`. |
|
|
377
|
+
| `channel?` | `ChannelName` | `live` (default, cached) or `preview` (per request, never cached; protect the route). |
|
|
378
|
+
| `prepare?` | `PrepareOptions` | `preparePage` options: `rewriteLink`, `transform`, `mode`. |
|
|
379
|
+
| `read?` | `(path: string) => Promise<PageEnvelope>` | The live envelope reader; default readEnvelopeCached. |
|
|
380
|
+
| `hints?` | `boolean` | Preload hints for the blocks (default true): modulepreload/preload links in <head>, same-origin. |
|
|
381
|
+
| `nonce?` | `string` | The request's CSP nonce (`foliwakeCsp({ strategy: 'nonce', nonce })`): set on the page's import map. Pass it to your `<FoliwakePage nonce>` too, so a map the browser adds on a client navigation carries it. |
|
|
382
|
+
| `render` | `(page: FoliwakePageData) => ReactNode` | Runs on the server; returns the app's client component with the page. |
|
|
383
|
+
|
|
384
|
+
#### `ReadPageOptions`
|
|
385
|
+
|
|
386
|
+
Options of `readPage`: the channel, the reader, hints, and `preparePage`'s options.
|
|
387
|
+
|
|
388
|
+
```ts
|
|
389
|
+
interface ReadPageOptions extends PrepareOptions
|
|
390
|
+
```
|
|
391
|
+
|
|
392
|
+
| Member | Type | Description |
|
|
393
|
+
| --- | --- | --- |
|
|
394
|
+
| `channel?` | `ChannelName` | `live` (default, cached) or `preview` (read per request, never cached). |
|
|
395
|
+
| `read?` | `(path: string) => Promise<PageEnvelope>` | The live envelope reader; default readEnvelopeCached (or the app's own 'use cache' wrapper). |
|
|
396
|
+
| `hints?` | `boolean` | Compute same-origin preload hints for the page's blocks into `page.preload` (default true). |
|
|
397
|
+
|
|
398
|
+
**Also exported** (documented where they are defined)
|
|
399
|
+
|
|
400
|
+
- from `@foliwake/blocks-contract`: `ChannelName`
|
|
401
|
+
- from `@foliwake/blocks-contract/import-map`: `pageImportMap`
|
|
402
|
+
- from `@foliwake/blocks-contract/page`: `FoliwakePageData`, `PageEnvelope`, `PreloadHint`
|
|
403
|
+
- from `@foliwake/server/config`: `FoliwakeAppConfig`
|
|
404
|
+
- from `@foliwake/server/page`: `FoliwakePageError`, `PageErrorKind`, `PrepareOptions`, `preparePage`, `readEnvelope`
|
|
405
|
+
- from `@foliwake/server/preload`: `preloadHints`
|
|
406
|
+
|
|
407
|
+
### `@foliwake/next/client`
|
|
408
|
+
|
|
409
|
+
**Also exported** (documented where they are defined)
|
|
410
|
+
|
|
411
|
+
- from `@foliwake/blocks-contract`: `BlockEventDetail`, `BlockEvents`, `BlockEventType`, `BlockHost`, `BlocksModule`, `ContractVersion`, `FoliwakeEvent`, `HostCore`, `MountHandle`, `MountReport`, `MountStatus`
|
|
412
|
+
- from `@foliwake/blocks-contract/page`: `ClientSettings`, `FoliwakePageData`
|
|
413
|
+
- from `@foliwake/client`: `BLOCK_EVENT_TYPES`, `CreatedHost`, `cssMounts`, `FoliwakeEventHandlers`, `FoliwakeHooks`, `FoliwakePageError`, `FoliwakePageStatus`, `HOST_CONTRACT_MINOR`, `HostInit`, `listenBlockEvents`
|
|
414
|
+
- from `@foliwake/react`: `createHost`, `FoliwakePage`, `FoliwakePageProps`, `FoliwakeProvider`, `useFoliwakeEvents`, `useFoliwakeSettings`
|
|
415
|
+
|
|
416
|
+
### `@foliwake/next/config`
|
|
417
|
+
|
|
418
|
+
**Functions and components**
|
|
419
|
+
|
|
420
|
+
#### `foliwakeCspHeader()`
|
|
421
|
+
|
|
422
|
+
The CSP value for this app's config (strategy A, media base included, 'unsafe-eval' in development).
|
|
423
|
+
|
|
424
|
+
```ts
|
|
425
|
+
function foliwakeCspHeader(opts?: {
|
|
426
|
+
configFile?: string;
|
|
427
|
+
reportUri?: string;
|
|
428
|
+
extra?: CspOptions['extra'];
|
|
429
|
+
dev?: boolean;
|
|
430
|
+
}): string
|
|
431
|
+
```
|
|
432
|
+
|
|
433
|
+
**Returns** `string`
|
|
434
|
+
|
|
435
|
+
#### `withFoliwake()`
|
|
436
|
+
|
|
437
|
+
Validates the Foliwake config when Next loads next.config (build and start) and makes it available to the package's server-only modules (Next `env`, never to client code); adds the package to transpilePackages (its 'use cache' read). Throws when the file is missing or invalid, naming the field.
|
|
438
|
+
|
|
439
|
+
```ts
|
|
440
|
+
function withFoliwake(nextConfig?: NextConfig, opts?: WithFoliwakeOptions): NextConfig
|
|
441
|
+
```
|
|
442
|
+
|
|
443
|
+
| Parameter | Type | Description |
|
|
444
|
+
| --- | --- | --- |
|
|
445
|
+
| `nextConfig?` | `NextConfig` | The app's own Next config; its `transpilePackages`, `env` and `headers` are kept. |
|
|
446
|
+
| `opts?` | `WithFoliwakeOptions` | |
|
|
447
|
+
|
|
448
|
+
**Returns** `NextConfig`: The Next config to export from next.config.ts.
|
|
449
|
+
|
|
450
|
+
**Interfaces**
|
|
451
|
+
|
|
452
|
+
#### `WithFoliwakeOptions`
|
|
453
|
+
|
|
454
|
+
Options of `withFoliwake`.
|
|
455
|
+
|
|
456
|
+
```ts
|
|
457
|
+
interface WithFoliwakeOptions
|
|
458
|
+
```
|
|
459
|
+
|
|
460
|
+
| Member | Type | Description |
|
|
461
|
+
| --- | --- | --- |
|
|
462
|
+
| `configFile?` | `string` | The config file (default FOLIWAKE_REMOTE, else ./foliwake.remote.json). |
|
|
463
|
+
| `csp?` | `false \| { reportUri?: string; extra?: CspOptions['extra']; source?: string; }` | Adds the Content-Security-Policy header (strategy 'self-inline': `script-src 'self' 'unsafe-inline'`) to the routes matching `source` (default every route, `/:path*`). `reportUri` adds `report-uri`; `extra` adds sources per directive. `false` (default): the app sets its own; use foliwakeCspHeader() for the value. |
|
|
464
|
+
|
|
465
|
+
### `@foliwake/next/routes`
|
|
466
|
+
|
|
467
|
+
**Functions and components**
|
|
468
|
+
|
|
469
|
+
#### `codeRoute()`
|
|
470
|
+
|
|
471
|
+
Route handlers for `app/<proxies.code>/[...path]/route.ts`: serve the files of a code release from the app's origin (`codeHandler` of `@foliwake/server/handlers`). Usage: `export const { GET, HEAD } = codeRoute({ authorizePreview: isAuthor })`. Each handler takes `(request, { params })` and returns a `Response`.
|
|
472
|
+
|
|
473
|
+
```ts
|
|
474
|
+
function codeRoute(opts: {
|
|
475
|
+
authorizePreview: AuthorizePreview;
|
|
476
|
+
}): {
|
|
477
|
+
GET: RouteHandler;
|
|
478
|
+
HEAD: RouteHandler;
|
|
479
|
+
}
|
|
480
|
+
```
|
|
481
|
+
|
|
482
|
+
| Parameter | Type | Description |
|
|
483
|
+
| --- | --- | --- |
|
|
484
|
+
| `opts` | `{ authorizePreview: AuthorizePreview; }` | `authorizePreview`: the app's author check for preview files, or `false`; required. |
|
|
485
|
+
|
|
486
|
+
**Returns** `{ GET: RouteHandler; HEAD: RouteHandler; }`
|
|
487
|
+
|
|
488
|
+
#### `mediaRoute()`
|
|
489
|
+
|
|
490
|
+
Route handlers for `app/<proxies.media>/[...path]/route.ts`: serve hashed pictures (`mediaHandler` of `@foliwake/server/handlers`). Usage: `export const { GET, HEAD } = mediaRoute({ authorizePreview: isAuthor })`.
|
|
491
|
+
|
|
492
|
+
```ts
|
|
493
|
+
function mediaRoute(opts: {
|
|
494
|
+
authorizePreview: AuthorizePreview;
|
|
495
|
+
}): {
|
|
496
|
+
GET: RouteHandler;
|
|
497
|
+
HEAD: RouteHandler;
|
|
498
|
+
}
|
|
499
|
+
```
|
|
500
|
+
|
|
501
|
+
| Parameter | Type | Description |
|
|
502
|
+
| --- | --- | --- |
|
|
503
|
+
| `opts` | `{ authorizePreview: AuthorizePreview; }` | `authorizePreview`: the app's author check for preview pictures, or `false`; required. |
|
|
504
|
+
|
|
505
|
+
**Returns** `{ GET: RouteHandler; HEAD: RouteHandler; }`
|
|
506
|
+
|
|
507
|
+
### `@foliwake/next/cache`
|
|
508
|
+
|
|
509
|
+
**Functions and components**
|
|
510
|
+
|
|
511
|
+
#### `readEnvelopeCachedEntry()`
|
|
512
|
+
|
|
513
|
+
The cached entry itself (`'use cache'`, tags of `foliwakeTags('live', path)`); readEnvelopeCached unwraps it.
|
|
514
|
+
|
|
515
|
+
```ts
|
|
516
|
+
function readEnvelopeCachedEntry(path: string): Promise<CachedEnvelope>
|
|
517
|
+
```
|
|
518
|
+
|
|
519
|
+
**Returns** `Promise<CachedEnvelope>`
|
|
520
|
+
|
|
521
|
+
**Types**
|
|
522
|
+
|
|
523
|
+
#### `CachedEnvelope`
|
|
524
|
+
|
|
525
|
+
What the cache stores: an envelope, or the fact that the page does not exist.
|
|
526
|
+
|
|
527
|
+
```ts
|
|
528
|
+
type CachedEnvelope = {
|
|
529
|
+
found: true;
|
|
530
|
+
envelope: PageEnvelope;
|
|
531
|
+
} | {
|
|
532
|
+
found: false;
|
|
533
|
+
path: string;
|
|
534
|
+
}
|
|
535
|
+
```
|
|
536
|
+
|
|
537
|
+
**Also exported** (documented where they are defined)
|
|
538
|
+
|
|
539
|
+
- from `@foliwake/next`: `readEnvelopeCached`
|
|
540
|
+
|
|
541
|
+
<!-- apistop -->
|
package/dist/cache.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import 'server-only';
|
|
2
|
+
import type { PageEnvelope } from '@foliwake/blocks-contract/page';
|
|
3
|
+
/** What the cache stores: an envelope, or the fact that the page does not exist. */
|
|
4
|
+
export type CachedEnvelope = {
|
|
5
|
+
found: true;
|
|
6
|
+
envelope: PageEnvelope;
|
|
7
|
+
} | {
|
|
8
|
+
found: false;
|
|
9
|
+
path: string;
|
|
10
|
+
};
|
|
11
|
+
/** The cached entry itself (`'use cache'`, tags of `foliwakeTags('live', path)`); readEnvelopeCached unwraps it. */
|
|
12
|
+
export declare function readEnvelopeCachedEntry(path: string): Promise<CachedEnvelope>;
|
|
13
|
+
/** The live envelope of `path` from Next's cache (stale-while-revalidate); 404 → FoliwakePageError('not_found'). */
|
|
14
|
+
export declare function readEnvelopeCached(path: string): Promise<PageEnvelope>;
|
package/dist/cache.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// @foliwake/next/cache: the cached live envelope read (design §6.5). Primitive input only (`path`); the site is
|
|
2
|
+
// the configured one and the channel is live. Kept: a body (200) and "not found" (404); anything else throws
|
|
3
|
+
// and is not stored. Needs @foliwake/next in transpilePackages (withFoliwake adds it): Next compiles
|
|
4
|
+
// 'use cache' only in code it transpiles.
|
|
5
|
+
import 'server-only';
|
|
6
|
+
import { cacheLife, cacheTag } from 'next/cache.js';
|
|
7
|
+
import { FoliwakePageError, readEnvelope } from '@foliwake/server/page';
|
|
8
|
+
import { foliwakeConfig, foliwakeTags, originClient } from './server.js';
|
|
9
|
+
/** The cached entry itself (`'use cache'`, tags of `foliwakeTags('live', path)`); readEnvelopeCached unwraps it. */
|
|
10
|
+
export async function readEnvelopeCachedEntry(path) {
|
|
11
|
+
'use cache';
|
|
12
|
+
const config = foliwakeConfig();
|
|
13
|
+
const revalidate = config.app?.revalidate ?? 300;
|
|
14
|
+
cacheLife({ stale: revalidate, revalidate, expire: 86_400 });
|
|
15
|
+
cacheTag(...foliwakeTags('live', path));
|
|
16
|
+
try {
|
|
17
|
+
return { found: true, envelope: await readEnvelope(config, originClient(), config.site, 'live', path) };
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
if (error instanceof FoliwakePageError && error.kind === 'not_found')
|
|
21
|
+
return { found: false, path };
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** The live envelope of `path` from Next's cache (stale-while-revalidate); 404 → FoliwakePageError('not_found'). */
|
|
26
|
+
export async function readEnvelopeCached(path) {
|
|
27
|
+
const entry = await readEnvelopeCachedEntry(path);
|
|
28
|
+
if (!entry.found)
|
|
29
|
+
throw new FoliwakePageError('not_found', `${path} does not exist on the live site.`, { status: 404 });
|
|
30
|
+
return entry.envelope;
|
|
31
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from '@foliwake/react';
|
package/dist/client.js
ADDED
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { NextConfig } from 'next';
|
|
2
|
+
import { type CspOptions } from '@foliwake/server/csp';
|
|
3
|
+
/** Options of `withFoliwake`. */
|
|
4
|
+
export interface WithFoliwakeOptions {
|
|
5
|
+
/** The config file (default FOLIWAKE_REMOTE, else ./foliwake.remote.json). */
|
|
6
|
+
configFile?: string;
|
|
7
|
+
/**
|
|
8
|
+
* Adds the Content-Security-Policy header (strategy 'self-inline': `script-src 'self' 'unsafe-inline'`) to the
|
|
9
|
+
* routes matching `source` (default every route, `/:path*`). `reportUri` adds `report-uri`; `extra` adds sources
|
|
10
|
+
* per directive. `false` (default): the app sets its own; use foliwakeCspHeader() for the value.
|
|
11
|
+
*/
|
|
12
|
+
csp?: false | {
|
|
13
|
+
reportUri?: string;
|
|
14
|
+
extra?: CspOptions['extra'];
|
|
15
|
+
source?: string;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/** The CSP value for this app's config (strategy A, media base included, 'unsafe-eval' in development). */
|
|
19
|
+
export declare function foliwakeCspHeader(opts?: {
|
|
20
|
+
configFile?: string;
|
|
21
|
+
reportUri?: string;
|
|
22
|
+
extra?: CspOptions['extra'];
|
|
23
|
+
dev?: boolean;
|
|
24
|
+
}): string;
|
|
25
|
+
/**
|
|
26
|
+
* Validates the Foliwake config when Next loads next.config (build and start) and makes it available to the
|
|
27
|
+
* package's server-only modules (Next `env`, never to client code); adds the package to transpilePackages
|
|
28
|
+
* (its 'use cache' read). Throws when the file is missing or invalid, naming the field.
|
|
29
|
+
*
|
|
30
|
+
* @param nextConfig - The app's own Next config; its `transpilePackages`, `env` and `headers` are kept.
|
|
31
|
+
* @returns The Next config to export from next.config.ts.
|
|
32
|
+
*/
|
|
33
|
+
export declare function withFoliwake(nextConfig?: NextConfig, opts?: WithFoliwakeOptions): NextConfig;
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// @foliwake/next/config: next.config helpers.
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { configFilePath, parseFoliwakeConfig } from '@foliwake/server/config';
|
|
5
|
+
import { foliwakeCsp } from '@foliwake/server/csp';
|
|
6
|
+
import { CONFIG_ENV_KEY } from './settings.js';
|
|
7
|
+
/** The CSP value for this app's config (strategy A, media base included, 'unsafe-eval' in development). */
|
|
8
|
+
export function foliwakeCspHeader(opts = {}) {
|
|
9
|
+
const file = configFilePath({ file: opts.configFile });
|
|
10
|
+
const config = parseFoliwakeConfig(readFileSync(file, 'utf8'), { file: path.basename(file) });
|
|
11
|
+
return foliwakeCsp({
|
|
12
|
+
strategy: 'self-inline',
|
|
13
|
+
mediaBase: config.app?.media?.base ?? null,
|
|
14
|
+
dev: opts.dev ?? process.env.NODE_ENV === 'development',
|
|
15
|
+
...(opts.reportUri ? { reportUri: opts.reportUri } : {}),
|
|
16
|
+
...(opts.extra ? { extra: opts.extra } : {}),
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Validates the Foliwake config when Next loads next.config (build and start) and makes it available to the
|
|
21
|
+
* package's server-only modules (Next `env`, never to client code); adds the package to transpilePackages
|
|
22
|
+
* (its 'use cache' read). Throws when the file is missing or invalid, naming the field.
|
|
23
|
+
*
|
|
24
|
+
* @param nextConfig - The app's own Next config; its `transpilePackages`, `env` and `headers` are kept.
|
|
25
|
+
* @returns The Next config to export from next.config.ts.
|
|
26
|
+
*/
|
|
27
|
+
export function withFoliwake(nextConfig = {}, opts = {}) {
|
|
28
|
+
const file = configFilePath({ file: opts.configFile });
|
|
29
|
+
let text;
|
|
30
|
+
try {
|
|
31
|
+
text = readFileSync(file, 'utf8');
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
throw new Error(`withFoliwake: cannot read ${file} (${error.code ?? 'error'}). Create foliwake.remote.json or set FOLIWAKE_REMOTE.`);
|
|
35
|
+
}
|
|
36
|
+
parseFoliwakeConfig(text, { file: path.basename(file) }); // throws a FoliwakeConfigError naming the field
|
|
37
|
+
const transpile = new Set([...(nextConfig.transpilePackages ?? []), '@foliwake/next']);
|
|
38
|
+
const out = {
|
|
39
|
+
...nextConfig,
|
|
40
|
+
transpilePackages: [...transpile],
|
|
41
|
+
env: { ...(nextConfig.env ?? {}), [CONFIG_ENV_KEY]: JSON.stringify({ file: path.basename(file), text }) },
|
|
42
|
+
};
|
|
43
|
+
if (opts.csp) {
|
|
44
|
+
const csp = opts.csp;
|
|
45
|
+
const previous = nextConfig.headers;
|
|
46
|
+
out.headers = async () => {
|
|
47
|
+
const own = previous ? await previous() : [];
|
|
48
|
+
const value = foliwakeCspHeader({ ...(opts.configFile ? { configFile: opts.configFile } : {}), ...(csp.reportUri ? { reportUri: csp.reportUri } : {}), ...(csp.extra ? { extra: csp.extra } : {}) });
|
|
49
|
+
return [...own, { source: csp.source ?? '/:path*', headers: [{ key: 'Content-Security-Policy', value }] }];
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|