@foliwake/next 0.0.0-stage → 0.3.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 ADDED
@@ -0,0 +1,44 @@
1
+ # Changelog: @foliwake/next
2
+
3
+ The packages of this repository (`@foliwake/blocks-contract`, `@foliwake/block-kit`, `@foliwake/site-check`,
4
+ `@foliwake/client`, `@foliwake/server`, `@foliwake/react`, `@foliwake/next`, `create-foliwake`) share one version
5
+ and are released together; each changelog lists the changes of its own package. While the version is 0.x, a
6
+ minor release may break; breaking changes are marked **BREAKING**.
7
+
8
+ Entries are written from the changesets of each pull request (`.changeset/`, CONTRIBUTING.md), newest first.
9
+
10
+ ## 0.3.0
11
+
12
+ ### Minor Changes
13
+
14
+ - b0c16ac: First release on npm, together with the new `@foliwake/site-check` and `create-foliwake` (one shared
15
+ version). The changes since the first 0.1.0 tarballs:
16
+
17
+ - **BREAKING** Through `@foliwake/react`: block events are delivered only when listed in the `events` prop
18
+ (core `ready`/`error` always); contract `foliwake-blocks/2`; assessment types come from
19
+ `@foliwake/blocks-contract/assessment`.
20
+ - **BREAKING** Through `@foliwake/server`: page `mode` is a site token (none by default), the stricter page path
21
+ grammar, `https` media base for the CSP.
22
+ - Added: `<FoliwakeImportMap>` and a `nonce` prop on `<FoliwakeServerPage>`; the server renders the page's
23
+ import map and hints block modules as `preload as=script`.
24
+ - Added (via `@foliwake/server`): `service-token` origin auth in `foliwake.remote.json`; `.svg` media through
25
+ `mediaRoute` with the sandbox CSP.
26
+ - Fixed: imports `next/cache.js`, `next/navigation.js` and `next/server.js` fully specified, so apps that
27
+ import `@foliwake/next` under Node ESM (vitest) resolve them (`next` 16.2 has no `exports` map).
28
+ - Built without source maps.
29
+
30
+ ### Patch Changes
31
+
32
+ - Updated dependencies
33
+ - Updated dependencies [b0c16ac]
34
+ - Updated dependencies [b0c16ac]
35
+ - Updated dependencies [b0c16ac]
36
+ - Updated dependencies [b0c16ac]
37
+ - @foliwake/blocks-contract@0.3.0
38
+ - @foliwake/server@0.3.0
39
+ - @foliwake/react@0.3.0
40
+
41
+ ## 0.2.0 and earlier (never published on npm)
42
+
43
+ 0.1.0 was packed for review only (GitHub Packages setup); 0.2.0 was prepared but not published. The first
44
+ release on npm lists the changes since the first 0.1.0 tarballs (2026-11-11).
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,521 @@
1
- # Temporary Holding Version
1
+ # @foliwake/next
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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 engine's block-kit as `foliwake`, and
201
+ 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 `foliwake` 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
+ ## Compatibility
213
+
214
+ | | |
215
+ | --- | --- |
216
+ | Next.js | 16.2 or newer, below 17 (peer `>=16.2.0 <17`; tested with 16.2.12), App Router with `cacheComponents: true` |
217
+ | React | 19.2 or newer (tested with 19.3.0) |
218
+ | Node.js | 22.22 or newer |
219
+ | Foliwake origin | sends `X-Code-Release` with `.plain.html` (plain/2); an older origin gives pages without blocks |
220
+ | Config | `foliwake.remote.json` version 2 |
221
+
222
+ Changes per version, breaking ones marked: `CHANGELOG.md` in the package
223
+ (`node_modules/@foliwake/next/CHANGELOG.md`).
224
+
225
+ ## Good to know
226
+
227
+ - `withFoliwake` adds `@foliwake/next` to `transpilePackages`: Next compiles `'use cache'` only in code it
228
+ transpiles. If you do not use `withFoliwake`, add it yourself, or write the cached read in your app and pass
229
+ it as `read` (the guide shows how).
230
+ - Under partial prerendering the status line is sent with the static shell, so a not-found page answers HTTP
231
+ 200 with the not-found content.
232
+ - The server modules import `server-only`, which throws when imported outside React Server Components. In unit
233
+ tests outside Next (for example vitest), alias `server-only` to an empty module or run with the
234
+ `react-server` condition. The package imports `next/cache.js`, `next/navigation.js` and `next/server.js`
235
+ fully specified, so Node's ESM resolution finds them; builds of 0.1.0 made before this change import the bare
236
+ `next/cache` and need an alias (`next/cache` → `next/cache.js`) in such tests.
237
+ - Block stylesheets: `<FoliwakePage>` links `components/<name>/<name>.css` for every block on the page
238
+ without reading `components.json`, so blocks without a stylesheet produce 404 links. See the
239
+ `@foliwake/react` notes for the workaround with `page.preload`.
240
+
241
+ ## Guides
242
+
243
+ - [Embed Foliwake pages in a React or Next app](https://docs.foliwake.dev/guide/embed-in-react): the whole
244
+ setup step by step, the config keys, caching and troubleshooting.
245
+ - [Roll out frontend code](https://docs.foliwake.dev/guide/code-rollout)
246
+
247
+ License: Apache-2.0.
248
+
249
+ <!-- usagestop -->
250
+
251
+ ## API
252
+
253
+ <!-- api -->
254
+
255
+ <!-- Generated by `pnpm packages:reference` from the type declarations; do not edit by hand. -->
256
+
257
+ ### `@foliwake/next`
258
+
259
+ **Functions and components**
260
+
261
+ #### `emitPreloadHints()`
262
+
263
+ 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 `foliwake` for good, and in a Next app the hints reach &lt;head&gt; before the map (which renders with the page, and on a client navigation arrives later).
264
+
265
+ ```ts
266
+ function emitPreloadHints(page: FoliwakePageData): void
267
+ ```
268
+
269
+ **Returns** `void`
270
+
271
+ #### `foliwakeConfig()`
272
+
273
+ The app's Foliwake config (validated at build time by withFoliwake).
274
+
275
+ ```ts
276
+ function foliwakeConfig(): FoliwakeAppConfig
277
+ ```
278
+
279
+ **Returns** `FoliwakeAppConfig`
280
+
281
+ #### `FoliwakeImportMap()`
282
+
283
+ The import map of the page's code release (`foliwake` → 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.
284
+
285
+ ```ts
286
+ function FoliwakeImportMap({ page, nonce }: {
287
+ page: FoliwakePageData;
288
+ nonce?: string;
289
+ }): ReactNode
290
+ ```
291
+
292
+ **Returns** `ReactNode`
293
+
294
+ #### `FoliwakeServerPage()`
295
+
296
+ A Foliwake page in a server component. Missing or not allowed → notFound(); other errors throw (error.tsx).
297
+
298
+ ```ts
299
+ function FoliwakeServerPage(props: FoliwakeServerPageProps): Promise<ReactNode>
300
+ ```
301
+
302
+ **Returns** `Promise<ReactNode>`
303
+
304
+ #### `foliwakeTags()`
305
+
306
+ Cache tags of a channel (and page): foliwake, foliwake:&lt;site&gt;, foliwake:&lt;site&gt;:&lt;channel&gt;, …:page:&lt;path&gt;.
307
+
308
+ ```ts
309
+ function foliwakeTags(channel: ChannelName, path?: string): string[]
310
+ ```
311
+
312
+ **Returns** `string[]`
313
+
314
+ #### `originClient()`
315
+
316
+ The origin client; credentials are read from process.env per request.
317
+
318
+ ```ts
319
+ function originClient(): OriginClient
320
+ ```
321
+
322
+ **Returns** `OriginClient`
323
+
324
+ #### `readEnvelopeCached()`
325
+
326
+ The live envelope of `path` from Next's cache (stale-while-revalidate); 404 → FoliwakePageError('not_found').
327
+
328
+ ```ts
329
+ function readEnvelopeCached(path: string): Promise<PageEnvelope>
330
+ ```
331
+
332
+ **Returns** `Promise<PageEnvelope>`
333
+
334
+ #### `readPage()`
335
+
336
+ The prepared page. Preview: `connection()` first (per request, never cached).
337
+
338
+ ```ts
339
+ function readPage(path: string, opts?: ReadPageOptions): Promise<FoliwakePageData>
340
+ ```
341
+
342
+ **Returns** `Promise<FoliwakePageData>`
343
+
344
+ **Interfaces**
345
+
346
+ #### `FoliwakeServerPageProps`
347
+
348
+ Props of `<FoliwakeServerPage>`.
349
+
350
+ ```ts
351
+ interface FoliwakeServerPageProps
352
+ ```
353
+
354
+ | Member | Type | Description |
355
+ | --- | --- | --- |
356
+ | `path` | `string` | The site's page path (`/`, `/lessons/a`); it must match `app.pages`. |
357
+ | `channel?` | `ChannelName` | `live` (default, cached) or `preview` (per request, never cached; protect the route). |
358
+ | `prepare?` | `PrepareOptions` | `preparePage` options: `rewriteLink`, `transform`, `mode`. |
359
+ | `read?` | `(path: string) => Promise<PageEnvelope>` | The live envelope reader; default readEnvelopeCached. |
360
+ | `hints?` | `boolean` | Preload hints for the blocks (default true): modulepreload/preload links in &lt;head&gt;, same-origin. |
361
+ | `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. |
362
+ | `render` | `(page: FoliwakePageData) => ReactNode` | Runs on the server; returns the app's client component with the page. |
363
+
364
+ #### `ReadPageOptions`
365
+
366
+ Options of `readPage`: the channel, the reader, hints, and `preparePage`'s options.
367
+
368
+ ```ts
369
+ interface ReadPageOptions extends PrepareOptions
370
+ ```
371
+
372
+ | Member | Type | Description |
373
+ | --- | --- | --- |
374
+ | `channel?` | `ChannelName` | `live` (default, cached) or `preview` (read per request, never cached). |
375
+ | `read?` | `(path: string) => Promise<PageEnvelope>` | The live envelope reader; default readEnvelopeCached (or the app's own 'use cache' wrapper). |
376
+ | `hints?` | `boolean` | Compute same-origin preload hints for the page's blocks into `page.preload` (default true). |
377
+
378
+ **Also exported** (documented where they are defined)
379
+
380
+ - from `@foliwake/blocks-contract`: `ChannelName`
381
+ - from `@foliwake/blocks-contract/import-map`: `pageImportMap`
382
+ - from `@foliwake/blocks-contract/page`: `FoliwakePageData`, `PageEnvelope`, `PreloadHint`
383
+ - from `@foliwake/server/config`: `FoliwakeAppConfig`
384
+ - from `@foliwake/server/page`: `FoliwakePageError`, `PageErrorKind`, `PrepareOptions`, `preparePage`, `readEnvelope`
385
+ - from `@foliwake/server/preload`: `preloadHints`
386
+
387
+ ### `@foliwake/next/client`
388
+
389
+ **Also exported** (documented where they are defined)
390
+
391
+ - from `@foliwake/blocks-contract`: `BlockEventDetail`, `BlockEvents`, `BlockEventType`, `BlockHost`, `BlocksModule`, `ContractVersion`, `FoliwakeEvent`, `HostCore`, `MountHandle`, `MountReport`, `MountStatus`
392
+ - from `@foliwake/blocks-contract/page`: `ClientSettings`, `FoliwakePageData`
393
+ - from `@foliwake/client`: `BLOCK_EVENT_TYPES`, `CreatedHost`, `cssMounts`, `FoliwakeEventHandlers`, `FoliwakeHooks`, `FoliwakePageError`, `FoliwakePageStatus`, `HOST_CONTRACT_MINOR`, `HostInit`, `listenBlockEvents`
394
+ - from `@foliwake/react`: `createHost`, `FoliwakePage`, `FoliwakePageProps`, `FoliwakeProvider`, `useFoliwakeEvents`, `useFoliwakeSettings`
395
+
396
+ ### `@foliwake/next/config`
397
+
398
+ **Functions and components**
399
+
400
+ #### `foliwakeCspHeader()`
401
+
402
+ The CSP value for this app's config (strategy A, media base included, 'unsafe-eval' in development).
403
+
404
+ ```ts
405
+ function foliwakeCspHeader(opts?: {
406
+ configFile?: string;
407
+ reportUri?: string;
408
+ extra?: CspOptions['extra'];
409
+ dev?: boolean;
410
+ }): string
411
+ ```
412
+
413
+ **Returns** `string`
414
+
415
+ #### `withFoliwake()`
416
+
417
+ 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.
418
+
419
+ ```ts
420
+ function withFoliwake(nextConfig?: NextConfig, opts?: WithFoliwakeOptions): NextConfig
421
+ ```
422
+
423
+ | Parameter | Type | Description |
424
+ | --- | --- | --- |
425
+ | `nextConfig?` | `NextConfig` | The app's own Next config; its `transpilePackages`, `env` and `headers` are kept. |
426
+ | `opts?` | `WithFoliwakeOptions` | |
427
+
428
+ **Returns** `NextConfig`: The Next config to export from next.config.ts.
429
+
430
+ **Interfaces**
431
+
432
+ #### `WithFoliwakeOptions`
433
+
434
+ Options of `withFoliwake`.
435
+
436
+ ```ts
437
+ interface WithFoliwakeOptions
438
+ ```
439
+
440
+ | Member | Type | Description |
441
+ | --- | --- | --- |
442
+ | `configFile?` | `string` | The config file (default FOLIWAKE_REMOTE, else ./foliwake.remote.json). |
443
+ | `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. |
444
+
445
+ ### `@foliwake/next/routes`
446
+
447
+ **Functions and components**
448
+
449
+ #### `codeRoute()`
450
+
451
+ 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`.
452
+
453
+ ```ts
454
+ function codeRoute(opts: {
455
+ authorizePreview: AuthorizePreview;
456
+ }): {
457
+ GET: RouteHandler;
458
+ HEAD: RouteHandler;
459
+ }
460
+ ```
461
+
462
+ | Parameter | Type | Description |
463
+ | --- | --- | --- |
464
+ | `opts` | `{ authorizePreview: AuthorizePreview; }` | `authorizePreview`: the app's author check for preview files, or `false`; required. |
465
+
466
+ **Returns** `{ GET: RouteHandler; HEAD: RouteHandler; }`
467
+
468
+ #### `mediaRoute()`
469
+
470
+ 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 })`.
471
+
472
+ ```ts
473
+ function mediaRoute(opts: {
474
+ authorizePreview: AuthorizePreview;
475
+ }): {
476
+ GET: RouteHandler;
477
+ HEAD: RouteHandler;
478
+ }
479
+ ```
480
+
481
+ | Parameter | Type | Description |
482
+ | --- | --- | --- |
483
+ | `opts` | `{ authorizePreview: AuthorizePreview; }` | `authorizePreview`: the app's author check for preview pictures, or `false`; required. |
484
+
485
+ **Returns** `{ GET: RouteHandler; HEAD: RouteHandler; }`
486
+
487
+ ### `@foliwake/next/cache`
488
+
489
+ **Functions and components**
490
+
491
+ #### `readEnvelopeCachedEntry()`
492
+
493
+ The cached entry itself (`'use cache'`, tags of `foliwakeTags('live', path)`); readEnvelopeCached unwraps it.
494
+
495
+ ```ts
496
+ function readEnvelopeCachedEntry(path: string): Promise<CachedEnvelope>
497
+ ```
498
+
499
+ **Returns** `Promise<CachedEnvelope>`
500
+
501
+ **Types**
502
+
503
+ #### `CachedEnvelope`
504
+
505
+ What the cache stores: an envelope, or the fact that the page does not exist.
506
+
507
+ ```ts
508
+ type CachedEnvelope = {
509
+ found: true;
510
+ envelope: PageEnvelope;
511
+ } | {
512
+ found: false;
513
+ path: string;
514
+ }
515
+ ```
516
+
517
+ **Also exported** (documented where they are defined)
518
+
519
+ - from `@foliwake/next`: `readEnvelopeCached`
520
+
521
+ <!-- apistop -->
@@ -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
+ }
@@ -0,0 +1 @@
1
+ export * from '@foliwake/react';
package/dist/client.js ADDED
@@ -0,0 +1,3 @@
1
+ 'use client';
2
+ // @foliwake/next/client: the React components for client components of a Next app.
3
+ export * from '@foliwake/react';
@@ -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
+ }
@@ -0,0 +1,8 @@
1
+ import 'server-only';
2
+ export { foliwakeConfig, originClient, foliwakeTags } from './server.js';
3
+ export { readEnvelopeCached } from './cache.js';
4
+ export { FoliwakeServerPage, FoliwakeImportMap, readPage, emitPreloadHints, type FoliwakeServerPageProps, type ReadPageOptions } from './page.js';
5
+ export { readEnvelope, preparePage, pageImportMap, FoliwakePageError, type PrepareOptions, type PageErrorKind } from '@foliwake/server/page';
6
+ export type { FoliwakeAppConfig } from '@foliwake/server/config';
7
+ export { preloadHints } from '@foliwake/server/preload';
8
+ export type { FoliwakePageData, PageEnvelope, ChannelName, PreloadHint } from '@foliwake/blocks-contract/page';
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ // @foliwake/next (server-only): reading and preparing Foliwake pages in the App Router.
2
+ import 'server-only';
3
+ export { foliwakeConfig, originClient, foliwakeTags } from './server.js';
4
+ export { readEnvelopeCached } from './cache.js';
5
+ export { FoliwakeServerPage, FoliwakeImportMap, readPage, emitPreloadHints } from './page.js';
6
+ export { readEnvelope, preparePage, pageImportMap, FoliwakePageError } from '@foliwake/server/page';
7
+ export { preloadHints } from '@foliwake/server/preload';
package/dist/page.d.ts ADDED
@@ -0,0 +1,54 @@
1
+ import 'server-only';
2
+ import type { ReactNode } from 'react';
3
+ import type { ChannelName, FoliwakePageData, PageEnvelope } from '@foliwake/blocks-contract/page';
4
+ import { type PrepareOptions } from '@foliwake/server/page';
5
+ /** Options of `readPage`: the channel, the reader, hints, and `preparePage`'s options. */
6
+ export interface ReadPageOptions extends PrepareOptions {
7
+ /** `live` (default, cached) or `preview` (read per request, never cached). */
8
+ channel?: ChannelName;
9
+ /** The live envelope reader; default readEnvelopeCached (or the app's own 'use cache' wrapper). */
10
+ read?: (path: string) => Promise<PageEnvelope>;
11
+ /** Compute same-origin preload hints for the page's blocks into `page.preload` (default true). */
12
+ hints?: boolean;
13
+ }
14
+ /** The prepared page. Preview: `connection()` first (per request, never cached). */
15
+ export declare function readPage(path: string, opts?: ReadPageOptions): Promise<FoliwakePageData>;
16
+ /**
17
+ * Emits the page's hints into the document head (React DOM resource APIs; deduplicated by React). Modules are
18
+ * hinted as `preload as="script"` (the bytes, fetched in parallel), not `modulepreload`: a module preloaded
19
+ * before the page's import map is in the document fails to resolve `foliwake` for good, and in a Next app the
20
+ * hints reach <head> before the map (which renders with the page, and on a client navigation arrives later).
21
+ */
22
+ export declare function emitPreloadHints(page: FoliwakePageData): void;
23
+ /** Props of `<FoliwakeServerPage>`. */
24
+ export interface FoliwakeServerPageProps {
25
+ /** The site's page path (`/`, `/lessons/a`); it must match `app.pages`. */
26
+ path: string;
27
+ /** `live` (default, cached) or `preview` (per request, never cached; protect the route). */
28
+ channel?: ChannelName;
29
+ /** `preparePage` options: `rewriteLink`, `transform`, `mode`. */
30
+ prepare?: PrepareOptions;
31
+ /** The live envelope reader; default readEnvelopeCached. */
32
+ read?: (path: string) => Promise<PageEnvelope>;
33
+ /** Preload hints for the blocks (default true): modulepreload/preload links in <head>, same-origin. */
34
+ hints?: boolean;
35
+ /**
36
+ * The request's CSP nonce (`foliwakeCsp({ strategy: 'nonce', nonce })`): set on the page's import map. Pass it to
37
+ * your `<FoliwakePage nonce>` too, so a map the browser adds on a client navigation carries it.
38
+ */
39
+ nonce?: string;
40
+ /** Runs on the server; returns the app's client component with the page. */
41
+ render: (page: FoliwakePageData) => ReactNode;
42
+ }
43
+ /**
44
+ * The import map of the page's code release (`foliwake` → its block-kit, scoped to the release's code path), as
45
+ * an element to render before the page's blocks load; null for a page without a code release. Browsers honour a
46
+ * map that arrives after the document's first module load (client navigation, a second release) only with
47
+ * multiple import maps (Chrome 133+); `@foliwake/client` adds the same map when it is missing.
48
+ */
49
+ export declare function FoliwakeImportMap({ page, nonce }: {
50
+ page: FoliwakePageData;
51
+ nonce?: string;
52
+ }): ReactNode;
53
+ /** A Foliwake page in a server component. Missing or not allowed → notFound(); other errors throw (error.tsx). */
54
+ export declare function FoliwakeServerPage(props: FoliwakeServerPageProps): Promise<ReactNode>;
package/dist/page.js ADDED
@@ -0,0 +1,70 @@
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // <FoliwakeServerPage> and readPage: read (live: cached envelope; preview: never cached), prepare per request
3
+ // (callbacks run here, on the server, after the cache), and hand the serialisable page to the app's client
4
+ // component.
5
+ import 'server-only';
6
+ import { notFound } from 'next/navigation.js';
7
+ import { preload } from 'react-dom';
8
+ import { connection } from 'next/server.js';
9
+ import { pageImportMap, preparePage, readEnvelope } from '@foliwake/server/page';
10
+ import { preloadHints } from '@foliwake/server/preload';
11
+ import { readEnvelopeCached } from './cache.js';
12
+ import { foliwakeConfig, originClient } from './server.js';
13
+ const isPageError = (error, ...kinds) => typeof error === 'object' && error !== null && error.name === 'FoliwakePageError' && kinds.includes(error.kind ?? '');
14
+ /** The prepared page. Preview: `connection()` first (per request, never cached). */
15
+ export async function readPage(path, opts = {}) {
16
+ const { channel = 'live', read, hints = true, ...prepare } = opts;
17
+ const config = foliwakeConfig();
18
+ let envelope;
19
+ if (channel === 'preview') {
20
+ await connection();
21
+ envelope = await readEnvelope(config, originClient(), config.site, 'preview', path);
22
+ }
23
+ else {
24
+ envelope = await (read ?? readEnvelopeCached)(path);
25
+ }
26
+ const page = preparePage(config, envelope, prepare);
27
+ if (hints)
28
+ page.preload = await preloadHints(config, originClient(), page);
29
+ return page;
30
+ }
31
+ /**
32
+ * Emits the page's hints into the document head (React DOM resource APIs; deduplicated by React). Modules are
33
+ * hinted as `preload as="script"` (the bytes, fetched in parallel), not `modulepreload`: a module preloaded
34
+ * before the page's import map is in the document fails to resolve `foliwake` for good, and in a Next app the
35
+ * hints reach <head> before the map (which renders with the page, and on a client navigation arrives later).
36
+ */
37
+ export function emitPreloadHints(page) {
38
+ for (const hint of page.preload) {
39
+ if (hint.rel === 'modulepreload')
40
+ preload(hint.href, { as: 'script', crossOrigin: 'anonymous' });
41
+ else
42
+ preload(hint.href, { as: 'style' });
43
+ }
44
+ }
45
+ /**
46
+ * The import map of the page's code release (`foliwake` → its block-kit, scoped to the release's code path), as
47
+ * an element to render before the page's blocks load; null for a page without a code release. Browsers honour a
48
+ * map that arrives after the document's first module load (client navigation, a second release) only with
49
+ * multiple import maps (Chrome 133+); `@foliwake/client` adds the same map when it is missing.
50
+ */
51
+ export function FoliwakeImportMap({ page, nonce }) {
52
+ const text = pageImportMap(page);
53
+ if (text === null)
54
+ return null;
55
+ return _jsx("script", { type: "importmap", nonce: nonce, "data-foliwake-code": page.codeBase ?? undefined, dangerouslySetInnerHTML: { __html: text } });
56
+ }
57
+ /** A Foliwake page in a server component. Missing or not allowed → notFound(); other errors throw (error.tsx). */
58
+ export async function FoliwakeServerPage(props) {
59
+ let page;
60
+ try {
61
+ page = await readPage(props.path, { ...(props.prepare ?? {}), ...(props.channel ? { channel: props.channel } : {}), ...(props.read ? { read: props.read } : {}), hints: props.hints ?? true });
62
+ }
63
+ catch (error) {
64
+ if (isPageError(error, 'not_found', 'not_allowed'))
65
+ notFound();
66
+ throw error;
67
+ }
68
+ emitPreloadHints(page);
69
+ return (_jsxs(_Fragment, { children: [_jsx(FoliwakeImportMap, { page: page, nonce: props.nonce }), props.render(page)] }));
70
+ }
@@ -0,0 +1,35 @@
1
+ import 'server-only';
2
+ import { type AuthorizePreview } from '@foliwake/server/handlers';
3
+ type Context = {
4
+ params: Promise<{
5
+ path: string[];
6
+ }>;
7
+ };
8
+ type RouteHandler = (request: Request, context: Context) => Promise<Response>;
9
+ /**
10
+ * Route handlers for `app/<proxies.code>/[...path]/route.ts`: serve the files of a code release from the app's
11
+ * origin (`codeHandler` of `@foliwake/server/handlers`). Usage:
12
+ * `export const { GET, HEAD } = codeRoute({ authorizePreview: isAuthor })`. Each handler takes
13
+ * `(request, { params })` and returns a `Response`.
14
+ *
15
+ * @param opts - `authorizePreview`: the app's author check for preview files, or `false`; required.
16
+ */
17
+ export declare function codeRoute(opts: {
18
+ authorizePreview: AuthorizePreview;
19
+ }): {
20
+ GET: RouteHandler;
21
+ HEAD: RouteHandler;
22
+ };
23
+ /**
24
+ * Route handlers for `app/<proxies.media>/[...path]/route.ts`: serve hashed pictures (`mediaHandler` of
25
+ * `@foliwake/server/handlers`). Usage: `export const { GET, HEAD } = mediaRoute({ authorizePreview: isAuthor })`.
26
+ *
27
+ * @param opts - `authorizePreview`: the app's author check for preview pictures, or `false`; required.
28
+ */
29
+ export declare function mediaRoute(opts: {
30
+ authorizePreview: AuthorizePreview;
31
+ }): {
32
+ GET: RouteHandler;
33
+ HEAD: RouteHandler;
34
+ };
35
+ export {};
package/dist/routes.js ADDED
@@ -0,0 +1,35 @@
1
+ // @foliwake/next/routes: route handlers for app/<proxies.code>/[...path]/route.ts and the media proxy.
2
+ import 'server-only';
3
+ import { codeHandler, mediaHandler } from '@foliwake/server/handlers';
4
+ import { foliwakeConfig, originClient } from './server.js';
5
+ function route(make, opts) {
6
+ if (!opts || (opts.authorizePreview !== false && typeof opts.authorizePreview !== 'function')) {
7
+ throw new TypeError('Pass { authorizePreview: <your author check> } or { authorizePreview: false }; no default serves preview.');
8
+ }
9
+ let handler = null;
10
+ const run = async (request, context) => {
11
+ handler ??= make(foliwakeConfig(), originClient(), opts);
12
+ return handler(request, { path: (await context.params).path ?? [] });
13
+ };
14
+ return { GET: run, HEAD: run };
15
+ }
16
+ /**
17
+ * Route handlers for `app/<proxies.code>/[...path]/route.ts`: serve the files of a code release from the app's
18
+ * origin (`codeHandler` of `@foliwake/server/handlers`). Usage:
19
+ * `export const { GET, HEAD } = codeRoute({ authorizePreview: isAuthor })`. Each handler takes
20
+ * `(request, { params })` and returns a `Response`.
21
+ *
22
+ * @param opts - `authorizePreview`: the app's author check for preview files, or `false`; required.
23
+ */
24
+ export function codeRoute(opts) {
25
+ return route(codeHandler, opts);
26
+ }
27
+ /**
28
+ * Route handlers for `app/<proxies.media>/[...path]/route.ts`: serve hashed pictures (`mediaHandler` of
29
+ * `@foliwake/server/handlers`). Usage: `export const { GET, HEAD } = mediaRoute({ authorizePreview: isAuthor })`.
30
+ *
31
+ * @param opts - `authorizePreview`: the app's author check for preview pictures, or `false`; required.
32
+ */
33
+ export function mediaRoute(opts) {
34
+ return route(mediaHandler, opts);
35
+ }
@@ -0,0 +1,10 @@
1
+ import 'server-only';
2
+ import type { ChannelName } from '@foliwake/blocks-contract/page';
3
+ import { type OriginClient } from '@foliwake/server/origin';
4
+ import type { FoliwakeAppConfig } from '@foliwake/server/config';
5
+ /** The app's Foliwake config (validated at build time by withFoliwake). */
6
+ export declare function foliwakeConfig(): FoliwakeAppConfig;
7
+ /** The origin client; credentials are read from process.env per request. */
8
+ export declare function originClient(): OriginClient;
9
+ /** Cache tags of a channel (and page): foliwake, foliwake:<site>, foliwake:<site>:<channel>, …:page:<path>. */
10
+ export declare function foliwakeTags(channel: ChannelName, path?: string): string[];
package/dist/server.js ADDED
@@ -0,0 +1,22 @@
1
+ // Server-side helpers (server-only): the config, the origin client and cache tags.
2
+ import 'server-only';
3
+ import { createOriginClient } from '@foliwake/server/origin';
4
+ import { loadConfigSync } from './settings.js';
5
+ let client = null;
6
+ /** The app's Foliwake config (validated at build time by withFoliwake). */
7
+ export function foliwakeConfig() {
8
+ return loadConfigSync();
9
+ }
10
+ /** The origin client; credentials are read from process.env per request. */
11
+ export function originClient() {
12
+ client ??= createOriginClient(foliwakeConfig(), process.env);
13
+ return client;
14
+ }
15
+ /** Cache tags of a channel (and page): foliwake, foliwake:<site>, foliwake:<site>:<channel>, …:page:<path>. */
16
+ export function foliwakeTags(channel, path) {
17
+ const site = foliwakeConfig().site;
18
+ const tags = ['foliwake', `foliwake:${site}`, `foliwake:${site}:${channel}`];
19
+ if (path !== undefined)
20
+ tags.push(`foliwake:${site}:${channel}:page:${path}`);
21
+ return tags;
22
+ }
@@ -0,0 +1,4 @@
1
+ import { type FoliwakeAppConfig } from '@foliwake/server/config';
2
+ /** The Next `env` key withFoliwake() sets. Not NEXT_PUBLIC_: never inlined into client code by name. */
3
+ export declare const CONFIG_ENV_KEY = "FOLIWAKE_APP_CONFIG";
4
+ export declare function loadConfigSync(): FoliwakeAppConfig;
@@ -0,0 +1,22 @@
1
+ // Where the app's Foliwake config comes from at run time: withFoliwake() validates the file at build time and
2
+ // inlines it (Next `env`) into server code only (this module is imported from server-only modules). Without
3
+ // withFoliwake, the file is read on first use (FOLIWAKE_REMOTE or ./foliwake.remote.json).
4
+ import { readFileSync } from 'node:fs';
5
+ import path from 'node:path';
6
+ import { configFilePath, parseFoliwakeConfig } from '@foliwake/server/config';
7
+ /** The Next `env` key withFoliwake() sets. Not NEXT_PUBLIC_: never inlined into client code by name. */
8
+ export const CONFIG_ENV_KEY = 'FOLIWAKE_APP_CONFIG';
9
+ let cached = null;
10
+ export function loadConfigSync() {
11
+ if (cached)
12
+ return cached;
13
+ const inlined = process.env.FOLIWAKE_APP_CONFIG;
14
+ if (inlined) {
15
+ const { file, text } = JSON.parse(inlined);
16
+ cached = parseFoliwakeConfig(text, { file });
17
+ return cached;
18
+ }
19
+ const file = configFilePath();
20
+ cached = parseFoliwakeConfig(readFileSync(file, 'utf8'), { file: path.basename(file) });
21
+ return cached;
22
+ }
package/package.json CHANGED
@@ -1,6 +1,88 @@
1
1
  {
2
2
  "name": "@foliwake/next",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "description": "Next.js App Router adapter for Foliwake pages: withFoliwake, cached envelope read, <FoliwakeServerPage>, preview pages, code and media route handlers, CSP header.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/foliwake/foliwake-js.git",
11
+ "directory": "packages/next"
12
+ },
13
+ "homepage": "https://docs.foliwake.dev/reference/packages/next",
14
+ "bugs": {
15
+ "url": "https://github.com/foliwake/foliwake-js/issues"
16
+ },
17
+ "keywords": [
18
+ "foliwake",
19
+ "cms",
20
+ "headless",
21
+ "blocks",
22
+ "nextjs",
23
+ "next",
24
+ "react",
25
+ "app-router"
26
+ ],
27
+ "engines": {
28
+ "node": ">=22.22"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public",
32
+ "provenance": true
33
+ },
34
+ "foliwake": {
35
+ "plain": 2,
36
+ "blocksContract": 2,
37
+ "remoteConfig": 2
38
+ },
39
+ "exports": {
40
+ ".": {
41
+ "types": "./dist/index.d.ts",
42
+ "default": "./dist/index.js"
43
+ },
44
+ "./client": {
45
+ "types": "./dist/client.d.ts",
46
+ "default": "./dist/client.js"
47
+ },
48
+ "./config": {
49
+ "types": "./dist/config.d.ts",
50
+ "default": "./dist/config.js"
51
+ },
52
+ "./routes": {
53
+ "types": "./dist/routes.d.ts",
54
+ "default": "./dist/routes.js"
55
+ },
56
+ "./cache": {
57
+ "types": "./dist/cache.d.ts",
58
+ "default": "./dist/cache.js"
59
+ },
60
+ "./package.json": "./package.json"
61
+ },
62
+ "dependencies": {
63
+ "server-only": "0.0.1",
64
+ "@foliwake/blocks-contract": "0.3.0",
65
+ "@foliwake/react": "0.3.0",
66
+ "@foliwake/server": "0.3.0"
67
+ },
68
+ "peerDependencies": {
69
+ "next": ">=16.2.0 <17",
70
+ "react": "^19.2.0"
71
+ },
72
+ "devDependencies": {
73
+ "@types/node": "22.20.5",
74
+ "@types/react": "19.3.0",
75
+ "next": "16.2.12",
76
+ "react": "19.3.0",
77
+ "react-dom": "19.3.0"
78
+ },
79
+ "files": [
80
+ "dist/",
81
+ "!dist/**/*.map",
82
+ "!dist/.build-stamp",
83
+ "!dist/.build-manifest.json",
84
+ "LICENSE",
85
+ "README.md",
86
+ "CHANGELOG.md"
87
+ ]
6
88
  }