@foliwake/next 0.7.0 → 0.9.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 CHANGED
@@ -7,6 +7,44 @@ minor release may break; breaking changes are marked **BREAKING**.
7
7
 
8
8
  Entries are written from the changesets of each pull request (`.changeset/`, CONTRIBUTING.md), newest first.
9
9
 
10
+ ## 0.9.0
11
+
12
+ ### Minor Changes
13
+
14
+ - 003f643: Apps can be told when the live site changes. `@foliwake/server/hook` verifies the signed hook a Foliwake server
15
+ sends once a change is live and the caches in front of the origin serve it (`verifyFoliwakeSignature`,
16
+ `parseFoliwakeHook`, `signFoliwakeHook` for tests, payload types). `@foliwake/next/revalidate` adds
17
+ `foliwakeRevalidateHandler({ secretEnv })`, a route handler that expires the live tag of every changed path, or
18
+ of the whole site when every page changed, with `{ expire: 0 }` by default (`mode: 'max'` for background
19
+ refresh), reads up to 20 changed pages again after answering (`warm`), accepts a previous secret while it is
20
+ rotated (`previousSecretEnv`) and calls `onDelivery(payload)`.
21
+ - 6dd1fd4: **BREAKING** `PageEnvelope.generation` is now a number (`X-Site-Generation`, the live generation, which only
22
+ grows), or null when the origin sends none; it was a string. An origin that sends a value that is not a
23
+ non-negative integer is refused (`FoliwakePageError` kind `invalid`). Code that compared or stored the string
24
+ needs updating.
25
+
26
+ `@foliwake/next/cache` adds `setGenerationFloor((site) => Promise<number | null>)`: the app's highest known live
27
+ generation (for example written by the hook's `onDelivery`). A cached live read whose generation is below the
28
+ floor no longer stays for `app.revalidate` seconds: it lives at most 15 seconds and is read again, and the old
29
+ page is shown meanwhile instead of an error. A floor that cannot be read turns the check off for that read and
30
+ logs; without a floor nothing changes.
31
+
32
+ ### Patch Changes
33
+
34
+ - Updated dependencies [003f643]
35
+ - Updated dependencies [6dd1fd4]
36
+ - @foliwake/server@0.9.0
37
+ - @foliwake/blocks-contract@0.9.0
38
+ - @foliwake/react@0.9.0
39
+
40
+ ## 0.8.0
41
+
42
+ ### Patch Changes
43
+
44
+ - @foliwake/blocks-contract@0.8.0
45
+ - @foliwake/react@0.8.0
46
+ - @foliwake/server@0.8.0
47
+
10
48
  ## 0.7.0
11
49
 
12
50
  ### Patch Changes
package/README.md CHANGED
@@ -15,7 +15,8 @@ another React app use `@foliwake/react` with `@foliwake/server`.
15
15
  | `@foliwake/next/config` | `withFoliwake`, `foliwakeCspHeader` for `next.config.ts` |
16
16
  | `@foliwake/next` | server-only: `<FoliwakeServerPage>`, `readPage`, `readEnvelopeCached`, `foliwakeTags`, config and origin client |
17
17
  | `@foliwake/next/routes` | `codeRoute`, `mediaRoute`: the code and media proxies |
18
- | `@foliwake/next/cache` | `readEnvelopeCached`: the cached live read alone |
18
+ | `@foliwake/next/cache` | `readEnvelopeCached`: the cached live read alone; `setGenerationFloor` |
19
+ | `@foliwake/next/revalidate` | `foliwakeRevalidateHandler`: the route of the hook a Foliwake server calls after a change |
19
20
  | `@foliwake/next/client` | `'use client'`: everything of `@foliwake/react` |
20
21
 
21
22
  ## Install
@@ -146,26 +147,50 @@ A nonce-based policy does not work with partial prerendering and is not supporte
146
147
 
147
148
  Only the live origin answer is cached, for `app.revalidate` seconds (default 300) with stale-while-revalidate
148
149
  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:
150
+ `foliwake:<site>:live:page:<path>` (`foliwakeTags`).
151
+
152
+ A Foliwake server whose site lists your app as a hook target calls it once a change is live and the caches in
153
+ front of the origin serve it (`delivery.settled`, signed with a shared secret). Mount the handler:
151
154
 
152
155
  ```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
- }
156
+ // app/api/webhooks/foliwake/route.ts
157
+ import { foliwakeRevalidateHandler } from '@foliwake/next/revalidate';
158
+
159
+ export const { POST } = foliwakeRevalidateHandler({ secretEnv: 'FOLIWAKE_HOOK_SECRET' });
165
160
  ```
166
161
 
167
- `revalidateTag(tag, 'max')` refreshes in the background instead (the next request still gets the cached
168
- page).
162
+ It checks the signature (within 300 s; `previousSecretEnv` names a second accepted secret while you rotate it)
163
+ and expires `foliwake:<site>:live:page:<path>` of every changed path, or `foliwake:<site>:live` when every page
164
+ changed (a code release, a large publication). Paths that are not pages, such as an index, get the same tag:
165
+ tag your own cached reads of them with `foliwakeTags('live', path)`. By default a tag is expired with
166
+ `{ expire: 0 }`: the next request waits for one fresh read and never sees the old page; `mode: 'max'` serves
167
+ the old page once while it is read again. Changed pages (at most 20, never when every page changed) are read
168
+ again right after the answer (`warm: false` turns this off). `onDelivery(payload)` runs for every delivery: a
169
+ throw answers 500 and the server sends it again. A `ping` answers `{ ok: true, site, sdk }` and expires
170
+ nothing. `app.revalidate` stays the safety net when a hook is lost.
171
+
172
+ #### Generation floor
173
+
174
+ Each delivery carries the live `generation`, which only grows. If your app keeps the highest generation it was
175
+ told (a database row written from `onDelivery`), register it with `setGenerationFloor`: a cached read that
176
+ answers an older generation (a cache in front of the origin still had the old page) then lives at most 15
177
+ seconds and is read again, instead of `app.revalidate` seconds. Without a floor nothing changes. A floor that
178
+ cannot be read turns the check off for that read (logged); an origin without `X-Site-Generation` is never
179
+ held back.
180
+
181
+ ```ts
182
+ // lib/foliwake-floor.ts: import it wherever pages are read and from the hook route
183
+ import { setGenerationFloor } from '@foliwake/next/cache';
184
+
185
+ const floors = new Map<string, number>(); // use your database: every server instance must see the floor
186
+
187
+ setGenerationFloor(async (site) => floors.get(site) ?? null);
188
+
189
+ export function recordGeneration(site: string, generation: number, kind: string): void {
190
+ const floor = floors.get(site) ?? 0;
191
+ floors.set(site, kind === 'init' ? generation : Math.max(floor, generation)); // init starts a new history
192
+ }
193
+ ```
169
194
 
170
195
  ### Read the page yourself
171
196
 
@@ -510,7 +535,7 @@ function mediaRoute(opts: {
510
535
 
511
536
  #### `readEnvelopeCachedEntry()`
512
537
 
513
- The cached entry itself (`'use cache'`, tags of `foliwakeTags('live', path)`); readEnvelopeCached unwraps it.
538
+ The cached entry itself (`'use cache'`, tags of `foliwakeTags('live', path)`); readEnvelopeCached unwraps it. It lives `app.revalidate` seconds, or 15 seconds when its generation is below the floor of `setGenerationFloor`.
514
539
 
515
540
  ```ts
516
541
  function readEnvelopeCachedEntry(path: string): Promise<CachedEnvelope>
@@ -518,6 +543,46 @@ function readEnvelopeCachedEntry(path: string): Promise<CachedEnvelope>
518
543
 
519
544
  **Returns** `Promise<CachedEnvelope>`
520
545
 
546
+ #### `setGenerationFloor()`
547
+
548
+ Registers how the cached read learns the generation floor (for example a database row the hook's `onDelivery` writes). A cached answer with an older `X-Site-Generation` is kept at most 15 seconds instead of `app.revalidate`. Call it at module scope of a module that every route reading pages imports; `null` removes it.
549
+
550
+ ```ts
551
+ function setGenerationFloor(floor: GenerationFloor | null): void
552
+ ```
553
+
554
+ | Parameter | Type | Description |
555
+ | --- | --- | --- |
556
+ | `floor` | `GenerationFloor \| null` | `(site) => Promise<number \| null>`; a throw turns the check off for that read (logged). |
557
+
558
+ **Returns** `void`
559
+
560
+ **Constants**
561
+
562
+ #### `BEHIND_FLOOR_LIFETIME`
563
+
564
+ The lifetime of an answer older than the floor: shown at most 15 s, then read again.
565
+
566
+ ```ts
567
+ const BEHIND_FLOOR_LIFETIME: EntryLifetime
568
+ ```
569
+
570
+ **Interfaces**
571
+
572
+ #### `EntryLifetime`
573
+
574
+ A cache lifetime as `cacheLife` takes it, in seconds.
575
+
576
+ ```ts
577
+ interface EntryLifetime
578
+ ```
579
+
580
+ | Member | Type | Description |
581
+ | --- | --- | --- |
582
+ | `stale` | `number` | |
583
+ | `revalidate` | `number` | |
584
+ | `expire` | `number` | |
585
+
521
586
  **Types**
522
587
 
523
588
  #### `CachedEnvelope`
@@ -534,8 +599,69 @@ type CachedEnvelope = {
534
599
  }
535
600
  ```
536
601
 
602
+ #### `GenerationFloor`
603
+
604
+ The highest live generation the app was told for a site, or null when it knows none.
605
+
606
+ ```ts
607
+ type GenerationFloor = (site: string) => Promise<number | null>
608
+ ```
609
+
537
610
  **Also exported** (documented where they are defined)
538
611
 
539
612
  - from `@foliwake/next`: `readEnvelopeCached`
540
613
 
614
+ ### `@foliwake/next/revalidate`
615
+
616
+ **Functions and components**
617
+
618
+ #### `foliwakeRevalidateHandler()`
619
+
620
+ The route handler of the Foliwake hook, for `app/api/webhooks/foliwake/route.ts`: `export const { POST } = foliwakeRevalidateHandler({ secretEnv: 'FOLIWAKE_HOOK_SECRET' })`. A delivery expires `foliwake:<site>:live:page:<path>` of every listed path (pages and other files alike, such as an index), or `foliwake:<site>:live` when every page changed, and answers `{ ok: true, revalidated }`. A `ping` answers `{ ok: true, site, sdk }` and expires nothing. 401: bad or expired signature; 400: not a payload, or another site; 413: over 64 KiB.
621
+
622
+ ```ts
623
+ function foliwakeRevalidateHandler(opts: FoliwakeRevalidateOptions): FoliwakeHookRoute
624
+ ```
625
+
626
+ | Parameter | Type | Description |
627
+ | --- | --- | --- |
628
+ | `opts` | `FoliwakeRevalidateOptions` | `secretEnv` (required), `previousSecretEnv`, `mode`, `warm`, `onDelivery`, `toleranceS`. |
629
+
630
+ **Returns** `FoliwakeHookRoute`
631
+
632
+ **Interfaces**
633
+
634
+ #### `FoliwakeHookRoute`
635
+
636
+ The route module exports of the hook: `export const { POST } = foliwakeRevalidateHandler(…)`.
637
+
638
+ ```ts
639
+ interface FoliwakeHookRoute
640
+ ```
641
+
642
+ | Member | Type | Description |
643
+ | --- | --- | --- |
644
+ | `POST` | `(request: Request) => Promise<Response>` | |
645
+
646
+ #### `FoliwakeRevalidateOptions`
647
+
648
+ Options of `foliwakeRevalidateHandler`.
649
+
650
+ ```ts
651
+ interface FoliwakeRevalidateOptions
652
+ ```
653
+
654
+ | Member | Type | Description |
655
+ | --- | --- | --- |
656
+ | `secretEnv` | `string` | The environment variable holding the shared secret (the one the Foliwake server signs with). |
657
+ | `previousSecretEnv?` | `string` | While the secret is rotated: the variable holding the previous secret, also accepted. |
658
+ | `mode?` | `'expire' \| 'max'` | `expire` (default): `revalidateTag(tag, { expire: 0 })`, the next request waits for a fresh read and never sees the old page; the server sends the hook only after its caches serve the new page. `max`: `revalidateTag(tag, 'max')`, the next request gets the old page once while it is read again in the background. |
659
+ | `warm?` | `boolean` | Read the changed pages again right after the response (at most 20, never when every page changed), so the first visitor of this region finds them cached. Default true. |
660
+ | `onDelivery?` | `(payload: FoliwakeDeliveryPayload) => void \| Promise<void>` | Called for every delivery after its tags are expired (a log, a metric, the generation floor); a throw answers 500 and the server sends the delivery again. |
661
+ | `toleranceS?` | `number` | The allowed clock distance of the signature, in seconds. Default 300. |
662
+
663
+ **Also exported** (documented where they are defined)
664
+
665
+ - from `@foliwake/server/hook`: `FoliwakeDeliveryPayload`, `FoliwakeHookPayload`, `FoliwakeOperationKind`
666
+
541
667
  <!-- apistop -->
package/dist/cache.d.ts CHANGED
@@ -1,14 +1,12 @@
1
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. */
2
+ import { type PageEnvelope } from '@foliwake/server/page';
3
+ import { type CachedEnvelope } from './generation-floor.js';
4
+ export { setGenerationFloor, BEHIND_FLOOR_LIFETIME, type CachedEnvelope, type EntryLifetime, type GenerationFloor, } from './generation-floor.js';
5
+ /**
6
+ * The cached entry itself (`'use cache'`, tags of `foliwakeTags('live', path)`); readEnvelopeCached unwraps it.
7
+ * It lives `app.revalidate` seconds, or 15 seconds when its generation is below the floor of
8
+ * `setGenerationFloor`.
9
+ */
12
10
  export declare function readEnvelopeCachedEntry(path: string): Promise<CachedEnvelope>;
13
11
  /** The live envelope of `path` from Next's cache (stale-while-revalidate); 404 → FoliwakePageError('not_found'). */
14
12
  export declare function readEnvelopeCached(path: string): Promise<PageEnvelope>;
package/dist/cache.js CHANGED
@@ -5,14 +5,10 @@
5
5
  import 'server-only';
6
6
  import { cacheLife, cacheTag } from 'next/cache.js';
7
7
  import { FoliwakePageError, readEnvelope } from '@foliwake/server/page';
8
+ import { entryLifetime } from './generation-floor.js';
8
9
  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));
10
+ export { setGenerationFloor, BEHIND_FLOOR_LIFETIME, } from './generation-floor.js';
11
+ async function readEntry(config, path) {
16
12
  try {
17
13
  return { found: true, envelope: await readEnvelope(config, originClient(), config.site, 'live', path) };
18
14
  }
@@ -22,6 +18,19 @@ export async function readEnvelopeCachedEntry(path) {
22
18
  throw error;
23
19
  }
24
20
  }
21
+ /**
22
+ * The cached entry itself (`'use cache'`, tags of `foliwakeTags('live', path)`); readEnvelopeCached unwraps it.
23
+ * It lives `app.revalidate` seconds, or 15 seconds when its generation is below the floor of
24
+ * `setGenerationFloor`.
25
+ */
26
+ export async function readEnvelopeCachedEntry(path) {
27
+ 'use cache';
28
+ const config = foliwakeConfig();
29
+ cacheTag(...foliwakeTags('live', path));
30
+ const entry = await readEntry(config, path);
31
+ cacheLife(await entryLifetime(entry, config.app?.revalidate ?? 300));
32
+ return entry;
33
+ }
25
34
  /** The live envelope of `path` from Next's cache (stale-while-revalidate); 404 → FoliwakePageError('not_found'). */
26
35
  export async function readEnvelopeCached(path) {
27
36
  const entry = await readEnvelopeCachedEntry(path);
@@ -0,0 +1,34 @@
1
+ import type { PageEnvelope } from '@foliwake/blocks-contract/page';
2
+ /** The highest live generation the app was told for a site, or null when it knows none. */
3
+ export type GenerationFloor = (site: string) => Promise<number | null>;
4
+ /** A cache lifetime as `cacheLife` takes it, in seconds. */
5
+ export interface EntryLifetime {
6
+ stale: number;
7
+ revalidate: number;
8
+ expire: number;
9
+ }
10
+ /** What the cache stores: an envelope, or the fact that the page does not exist. */
11
+ export type CachedEnvelope = {
12
+ found: true;
13
+ envelope: PageEnvelope;
14
+ } | {
15
+ found: false;
16
+ path: string;
17
+ };
18
+ /** The lifetime of an answer older than the floor: shown at most 15 s, then read again. */
19
+ export declare const BEHIND_FLOOR_LIFETIME: EntryLifetime;
20
+ /**
21
+ * Registers how the cached read learns the generation floor (for example a database row the hook's `onDelivery`
22
+ * writes). A cached answer with an older `X-Site-Generation` is kept at most 15 seconds instead of
23
+ * `app.revalidate`. Call it at module scope of a module that every route reading pages imports; `null` removes it.
24
+ *
25
+ * @param floor - `(site) => Promise<number | null>`; a throw turns the check off for that read (logged).
26
+ */
27
+ export declare function setGenerationFloor(floor: GenerationFloor | null): void;
28
+ /**
29
+ * Whether an envelope is older than the registered floor. No floor, no generation on the answer, or a floor
30
+ * that cannot be read: false (fail-open).
31
+ */
32
+ export declare function behindFloor(envelope: PageEnvelope, log?: Pick<Console, 'warn'>): Promise<boolean>;
33
+ /** The lifetime of a cache entry: `revalidate` seconds, or BEHIND_FLOOR_LIFETIME for an answer below the floor. */
34
+ export declare function entryLifetime(entry: CachedEnvelope, revalidate: number): Promise<EntryLifetime>;
@@ -0,0 +1,53 @@
1
+ /** The lifetime of an answer older than the floor: shown at most 15 s, then read again. */
2
+ export const BEHIND_FLOOR_LIFETIME = Object.freeze({ stale: 1, revalidate: 1, expire: 15 });
3
+ const LONGEST_EXPIRE = 86_400;
4
+ // On globalThis, so a second copy of this module in a bundle sees the same registration.
5
+ const KEY = Symbol.for('@foliwake/next.generationFloor');
6
+ /**
7
+ * Registers how the cached read learns the generation floor (for example a database row the hook's `onDelivery`
8
+ * writes). A cached answer with an older `X-Site-Generation` is kept at most 15 seconds instead of
9
+ * `app.revalidate`. Call it at module scope of a module that every route reading pages imports; `null` removes it.
10
+ *
11
+ * @param floor - `(site) => Promise<number | null>`; a throw turns the check off for that read (logged).
12
+ */
13
+ export function setGenerationFloor(floor) {
14
+ globalThis[KEY] = floor;
15
+ }
16
+ function registered() {
17
+ return globalThis[KEY] ?? null;
18
+ }
19
+ async function floorOf(read, site, log) {
20
+ try {
21
+ return await read(site);
22
+ }
23
+ catch (error) {
24
+ log.warn(`[foliwake] the generation floor of ${site} could not be read; the read is not checked`, error);
25
+ return null;
26
+ }
27
+ }
28
+ /**
29
+ * Whether an envelope is older than the registered floor. No floor, no generation on the answer, or a floor
30
+ * that cannot be read: false (fail-open).
31
+ */
32
+ export async function behindFloor(envelope, log = console) {
33
+ const read = registered();
34
+ if (read === null)
35
+ return false;
36
+ const floor = await floorOf(read, envelope.site, log);
37
+ if (floor === null)
38
+ return false;
39
+ if (envelope.generation === null) {
40
+ log.warn(`[foliwake] ${envelope.path} came without X-Site-Generation; the floor is not checked`);
41
+ return false;
42
+ }
43
+ if (envelope.generation >= floor)
44
+ return false;
45
+ log.warn(`[foliwake] ${envelope.path} is at generation ${envelope.generation}, below ${floor}; kept 15 s`);
46
+ return true;
47
+ }
48
+ /** The lifetime of a cache entry: `revalidate` seconds, or BEHIND_FLOOR_LIFETIME for an answer below the floor. */
49
+ export async function entryLifetime(entry, revalidate) {
50
+ if (entry.found && (await behindFloor(entry.envelope)))
51
+ return BEHIND_FLOOR_LIFETIME;
52
+ return { stale: revalidate, revalidate, expire: LONGEST_EXPIRE };
53
+ }
@@ -0,0 +1,33 @@
1
+ import { type FoliwakeDeliveryPayload } from '@foliwake/server/hook';
2
+ /** At most this many pages are read again right after a delivery (`warm`); never on `all`. */
3
+ export declare const WARM_LIMIT = 20;
4
+ /** What the endpoint needs from Next and from the app. */
5
+ export interface RevalidateDeps {
6
+ /** The configured site. */
7
+ site: string;
8
+ /** The accepted secrets, read per request (current, then previous). */
9
+ secrets(): (string | undefined)[];
10
+ /** The live tag of the site (no path) or of one path. */
11
+ liveTag(path?: string): string;
12
+ /** Expires one tag (revalidateTag with the chosen profile). */
13
+ expire(tag: string): void;
14
+ /** Reads one page into the cache again. */
15
+ warm(path: string): Promise<unknown>;
16
+ /** Runs work after the response is sent. */
17
+ schedule(task: () => Promise<void>): void;
18
+ /** Whether pages are read again after a delivery. */
19
+ warmPages: boolean;
20
+ onDelivery?: (payload: FoliwakeDeliveryPayload) => void | Promise<void>;
21
+ toleranceS?: number;
22
+ now?: () => number;
23
+ log: Pick<Console, 'warn' | 'error'>;
24
+ }
25
+ /** The tags a delivery expires: the site's live tag on `all`, else one tag per listed path. */
26
+ export declare function deliveryTags(payload: FoliwakeDeliveryPayload, liveTag: (path?: string) => string): string[];
27
+ /** The pages read again after a delivery: none on `all`, page paths only, at most WARM_LIMIT. */
28
+ export declare function warmPaths(payload: FoliwakeDeliveryPayload): string[];
29
+ /**
30
+ * The hook endpoint as a function of a Request: 413 over 64 KiB, 401 on a bad or expired signature, 400 on a
31
+ * body that is not a payload or names another site, 200 otherwise.
32
+ */
33
+ export declare function createRevalidateHandler(deps: RevalidateDeps): (request: Request) => Promise<Response>;
@@ -0,0 +1,144 @@
1
+ // The hook endpoint without Next: verify, parse, expire tags, answer. `revalidate.ts` wires it to next/cache,
2
+ // next/server and the app's config; tests drive it directly with plain Request objects.
3
+ import { FoliwakeHookError, HOOK_BODY_LIMIT, isFoliwakePagePath, parseFoliwakeHook, verifyFoliwakeSignature, } from '@foliwake/server/hook';
4
+ /** Replaced by the package's version when it is built (tools/build.mjs). */
5
+ const SDK = '@foliwake/next/0.9.0';
6
+ /** At most this many pages are read again right after a delivery (`warm`); never on `all`. */
7
+ export const WARM_LIMIT = 20;
8
+ class TooLarge extends Error {
9
+ }
10
+ function answer(status, body) {
11
+ return Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } });
12
+ }
13
+ function refuse(status, error) {
14
+ return answer(status, { ok: false, error });
15
+ }
16
+ function declaredTooLarge(request) {
17
+ const length = Number(request.headers.get('content-length') ?? '0');
18
+ return Number.isFinite(length) && length > HOOK_BODY_LIMIT;
19
+ }
20
+ function joined(chunks, total) {
21
+ const out = new Uint8Array(total);
22
+ let at = 0;
23
+ for (const chunk of chunks) {
24
+ out.set(chunk, at);
25
+ at += chunk.byteLength;
26
+ }
27
+ return out;
28
+ }
29
+ /** The body, cut at HOOK_BODY_LIMIT whatever Content-Length says. */
30
+ async function readBody(request) {
31
+ if (declaredTooLarge(request))
32
+ throw new TooLarge();
33
+ if (!request.body)
34
+ return new Uint8Array();
35
+ const reader = request.body.getReader();
36
+ const chunks = [];
37
+ let total = 0;
38
+ for (let read = await reader.read(); !read.done; read = await reader.read()) {
39
+ total += read.value.byteLength;
40
+ if (total > HOOK_BODY_LIMIT) {
41
+ await reader.cancel().catch(() => { });
42
+ throw new TooLarge();
43
+ }
44
+ chunks.push(read.value);
45
+ }
46
+ return joined(chunks, total);
47
+ }
48
+ /** The tags a delivery expires: the site's live tag on `all`, else one tag per listed path. */
49
+ export function deliveryTags(payload, liveTag) {
50
+ if (payload.all)
51
+ return [liveTag()];
52
+ return (payload.pages ?? []).map((path) => liveTag(path));
53
+ }
54
+ /** The pages read again after a delivery: none on `all`, page paths only, at most WARM_LIMIT. */
55
+ export function warmPaths(payload) {
56
+ if (payload.all)
57
+ return [];
58
+ return (payload.pages ?? []).filter(isFoliwakePagePath).slice(0, WARM_LIMIT);
59
+ }
60
+ function scheduleWarm(deps, payload) {
61
+ const paths = warmPaths(payload);
62
+ if (!deps.warmPages || paths.length === 0)
63
+ return;
64
+ deps.schedule(async () => {
65
+ const results = await Promise.allSettled(paths.map((path) => deps.warm(path)));
66
+ const failed = results.filter((r) => r.status === 'rejected').length;
67
+ if (failed > 0)
68
+ deps.log.warn(`[foliwake] hook: ${failed} of ${paths.length} pages were not read again`);
69
+ });
70
+ }
71
+ async function deliver(deps, payload) {
72
+ const tags = deliveryTags(payload, deps.liveTag);
73
+ for (const tag of tags)
74
+ deps.expire(tag);
75
+ try {
76
+ await deps.onDelivery?.(payload);
77
+ }
78
+ catch (error) {
79
+ deps.log.error('[foliwake] hook: onDelivery failed; the server will send the delivery again', error);
80
+ return refuse(500, 'on_delivery_failed');
81
+ }
82
+ scheduleWarm(deps, payload);
83
+ return answer(200, { ok: true, revalidated: tags });
84
+ }
85
+ function verified(deps, body, request) {
86
+ const check = verifyFoliwakeSignature(body, request.headers.get('foliwake-signature'), deps.secrets(), {
87
+ now: deps.now?.(),
88
+ toleranceS: deps.toleranceS,
89
+ });
90
+ if (check.ok)
91
+ return null;
92
+ if (check.reason !== 'no_secret')
93
+ return refuse(401, `signature_${check.reason}`);
94
+ deps.log.error('[foliwake] hook: no secret is set; every delivery is refused');
95
+ return refuse(500, 'no_secret');
96
+ }
97
+ function payloadOf(body) {
98
+ try {
99
+ return parseFoliwakeHook(body);
100
+ }
101
+ catch (error) {
102
+ if (error instanceof FoliwakeHookError)
103
+ return refuse(400, error.message);
104
+ throw error;
105
+ }
106
+ }
107
+ function eventMismatch(request, payload) {
108
+ const event = request.headers.get('foliwake-event');
109
+ return event !== null && event !== payload.event;
110
+ }
111
+ async function handle(deps, request) {
112
+ if (request.method !== 'POST')
113
+ return refuse(405, 'method_not_allowed');
114
+ const body = await readBody(request);
115
+ const refused = verified(deps, body, request);
116
+ if (refused)
117
+ return refused;
118
+ const payload = payloadOf(body);
119
+ if (payload instanceof Response)
120
+ return payload;
121
+ if (eventMismatch(request, payload))
122
+ return refuse(400, 'Foliwake-Event does not match the body');
123
+ if (payload.site !== deps.site)
124
+ return refuse(400, `this app serves the site ${deps.site}`);
125
+ if (payload.event === 'ping')
126
+ return answer(200, { ok: true, site: deps.site, sdk: SDK });
127
+ return deliver(deps, payload);
128
+ }
129
+ /**
130
+ * The hook endpoint as a function of a Request: 413 over 64 KiB, 401 on a bad or expired signature, 400 on a
131
+ * body that is not a payload or names another site, 200 otherwise.
132
+ */
133
+ export function createRevalidateHandler(deps) {
134
+ return async (request) => {
135
+ try {
136
+ return await handle(deps, request);
137
+ }
138
+ catch (error) {
139
+ if (error instanceof TooLarge)
140
+ return refuse(413, 'body_too_large');
141
+ throw error;
142
+ }
143
+ };
144
+ }
@@ -0,0 +1,41 @@
1
+ import 'server-only';
2
+ import type { FoliwakeDeliveryPayload } from '@foliwake/server/hook';
3
+ export type { FoliwakeDeliveryPayload, FoliwakeHookPayload, FoliwakeOperationKind } from '@foliwake/server/hook';
4
+ /** Options of `foliwakeRevalidateHandler`. */
5
+ export interface FoliwakeRevalidateOptions {
6
+ /** The environment variable holding the shared secret (the one the Foliwake server signs with). */
7
+ secretEnv: string;
8
+ /** While the secret is rotated: the variable holding the previous secret, also accepted. */
9
+ previousSecretEnv?: string;
10
+ /**
11
+ * `expire` (default): `revalidateTag(tag, { expire: 0 })`, the next request waits for a fresh read and never
12
+ * sees the old page; the server sends the hook only after its caches serve the new page. `max`:
13
+ * `revalidateTag(tag, 'max')`, the next request gets the old page once while it is read again in the background.
14
+ */
15
+ mode?: 'expire' | 'max';
16
+ /**
17
+ * Read the changed pages again right after the response (at most 20, never when every page changed), so the
18
+ * first visitor of this region finds them cached. Default true.
19
+ */
20
+ warm?: boolean;
21
+ /** Called for every delivery after its tags are expired (a log, a metric, the generation floor); a throw
22
+ * answers 500 and the server sends the delivery again. */
23
+ onDelivery?: (payload: FoliwakeDeliveryPayload) => void | Promise<void>;
24
+ /** The allowed clock distance of the signature, in seconds. Default 300. */
25
+ toleranceS?: number;
26
+ }
27
+ /** The route module exports of the hook: `export const { POST } = foliwakeRevalidateHandler(…)`. */
28
+ export interface FoliwakeHookRoute {
29
+ POST: (request: Request) => Promise<Response>;
30
+ }
31
+ /**
32
+ * The route handler of the Foliwake hook, for `app/api/webhooks/foliwake/route.ts`:
33
+ * `export const { POST } = foliwakeRevalidateHandler({ secretEnv: 'FOLIWAKE_HOOK_SECRET' })`.
34
+ * A delivery expires `foliwake:<site>:live:page:<path>` of every listed path (pages and other files alike, such
35
+ * as an index), or `foliwake:<site>:live` when every page changed, and answers `{ ok: true, revalidated }`.
36
+ * A `ping` answers `{ ok: true, site, sdk }` and expires nothing. 401: bad or expired signature; 400: not a
37
+ * payload, or another site; 413: over 64 KiB.
38
+ *
39
+ * @param opts - `secretEnv` (required), `previousSecretEnv`, `mode`, `warm`, `onDelivery`, `toleranceS`.
40
+ */
41
+ export declare function foliwakeRevalidateHandler(opts: FoliwakeRevalidateOptions): FoliwakeHookRoute;
@@ -0,0 +1,59 @@
1
+ // @foliwake/next/revalidate: the route handler a Foliwake server calls once a change is live and its caches are
2
+ // refreshed. It checks the signature, expires the live tags of the changed pages (or of the whole site) and
3
+ // answers; the next request of each page reads it again.
4
+ import 'server-only';
5
+ import { revalidateTag } from 'next/cache.js';
6
+ import { after } from 'next/server.js';
7
+ import { checkEnvName } from '@foliwake/server/config';
8
+ import { readEnvelopeCachedEntry } from './cache.js';
9
+ import { createRevalidateHandler } from './revalidate-core.js';
10
+ import { foliwakeConfig, foliwakeTags } from './server.js';
11
+ function checkOptions(opts) {
12
+ if (!opts || typeof opts.secretEnv !== 'string') {
13
+ throw new TypeError("Pass { secretEnv: '<the variable holding the hook secret>' }.");
14
+ }
15
+ checkEnvName(opts.secretEnv, 'secretEnv');
16
+ if (opts.previousSecretEnv !== undefined)
17
+ checkEnvName(opts.previousSecretEnv, 'previousSecretEnv');
18
+ if (opts.mode !== undefined && opts.mode !== 'expire' && opts.mode !== 'max') {
19
+ throw new TypeError("mode is 'expire' or 'max'.");
20
+ }
21
+ }
22
+ function expireWith(mode) {
23
+ if (mode === 'max')
24
+ return (tag) => revalidateTag(tag, 'max');
25
+ return (tag) => revalidateTag(tag, { expire: 0 });
26
+ }
27
+ function liveTag(path) {
28
+ return foliwakeTags('live', path).at(-1);
29
+ }
30
+ /**
31
+ * The route handler of the Foliwake hook, for `app/api/webhooks/foliwake/route.ts`:
32
+ * `export const { POST } = foliwakeRevalidateHandler({ secretEnv: 'FOLIWAKE_HOOK_SECRET' })`.
33
+ * A delivery expires `foliwake:<site>:live:page:<path>` of every listed path (pages and other files alike, such
34
+ * as an index), or `foliwake:<site>:live` when every page changed, and answers `{ ok: true, revalidated }`.
35
+ * A `ping` answers `{ ok: true, site, sdk }` and expires nothing. 401: bad or expired signature; 400: not a
36
+ * payload, or another site; 413: over 64 KiB.
37
+ *
38
+ * @param opts - `secretEnv` (required), `previousSecretEnv`, `mode`, `warm`, `onDelivery`, `toleranceS`.
39
+ */
40
+ export function foliwakeRevalidateHandler(opts) {
41
+ checkOptions(opts);
42
+ let handler = null;
43
+ const POST = (request) => {
44
+ handler ??= createRevalidateHandler({
45
+ site: foliwakeConfig().site,
46
+ secrets: () => [process.env[opts.secretEnv], opts.previousSecretEnv && process.env[opts.previousSecretEnv]],
47
+ liveTag,
48
+ expire: expireWith(opts.mode ?? 'expire'),
49
+ warm: (path) => readEnvelopeCachedEntry(path),
50
+ schedule: (task) => after(task),
51
+ warmPages: opts.warm ?? true,
52
+ onDelivery: opts.onDelivery,
53
+ toleranceS: opts.toleranceS,
54
+ log: console,
55
+ });
56
+ return handler(request);
57
+ };
58
+ return { POST };
59
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foliwake/next",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
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
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -57,13 +57,17 @@
57
57
  "types": "./dist/cache.d.ts",
58
58
  "default": "./dist/cache.js"
59
59
  },
60
+ "./revalidate": {
61
+ "types": "./dist/revalidate.d.ts",
62
+ "default": "./dist/revalidate.js"
63
+ },
60
64
  "./package.json": "./package.json"
61
65
  },
62
66
  "dependencies": {
63
67
  "server-only": "0.0.1",
64
- "@foliwake/blocks-contract": "0.7.0",
65
- "@foliwake/react": "0.7.0",
66
- "@foliwake/server": "0.7.0"
68
+ "@foliwake/blocks-contract": "0.9.0",
69
+ "@foliwake/react": "0.9.0",
70
+ "@foliwake/server": "0.9.0"
67
71
  },
68
72
  "peerDependencies": {
69
73
  "next": ">=16.2.0 <17",