@foliwake/next 0.9.0 → 0.10.2

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,98 @@ 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.10.2
11
+
12
+ ### Patch Changes
13
+
14
+ - 964b5e5: Links point to the public documentation on foliwake.org (`docs.foliwake.org`, `sdk.foliwake.org`); the config
15
+ schemas' `$id` is under `https://foliwake.org/schemas/`.
16
+ - Updated dependencies [964b5e5]
17
+ - @foliwake/blocks-contract@0.10.2
18
+ - @foliwake/react@0.10.2
19
+ - @foliwake/server@0.10.2
20
+
21
+ ## 0.10.1
22
+
23
+ ### Patch Changes
24
+
25
+ - 44822ad: The hook trims leading and trailing whitespace and newlines from the secret read from `secretEnv` and
26
+ `previousSecretEnv` (a secret pasted with a trailing newline used to fail every signature), warns once naming the
27
+ variable (never the value), and treats an all-whitespace value as unset. New: `hookSecretsFrom` in
28
+ `@foliwake/server/hook-endpoint`. The docs make the secret with `openssl rand -hex 32 | tr -d '\n'`.
29
+ - e81a756: `npx @foliwake/next init` turns on `cacheComponents: true` in `next.config.(ts|mjs|js)` for the same forms it
30
+ wraps in `withFoliwake` (`export default { … }` and `export default <name>` of a `const` object literal, wrapped or
31
+ not), including the file `create-next-app` writes. A second run changes nothing; `--dry-run` and `--json` report it
32
+ as its own step. Any other form (a config built elsewhere, `cacheComponents: false`) is left alone and the line to
33
+ add, `cacheComponents: true,`, is printed.
34
+ - Updated dependencies [55ffb45]
35
+ - Updated dependencies [44822ad]
36
+ - @foliwake/server@0.10.1
37
+ - @foliwake/blocks-contract@0.10.1
38
+ - @foliwake/react@0.10.1
39
+
40
+ ## 0.10.0
41
+
42
+ ### Minor Changes
43
+
44
+ - 69caab7: Configure an app by one address. `@foliwake/server/discovery` reads a site's `/.well-known/foliwake.json`
45
+ (no redirects, 5 s, one retry, at most 16 KiB; `live.url` must be the origin it was read from; the discovery format
46
+ and the plain contract are checked). `@foliwake/server/resolve` builds the app config from `FOLIWAKE_URL` and the
47
+ optional `foliwake.remote.json` version 3 (overrides only: pages, revalidate, proxies, media, blocks, auth by
48
+ variable name; schema `schemas/remote-3.schema.json`, also shipped in `@foliwake/next`). Defaults: pages `/**`
49
+ (required explicitly when live uses a service token), proxies `/foliwake/code` and `/foliwake/media`, preview
50
+ read with Basic `preview` and `FOLIWAKE_PREVIEW_TOKEN`. A version 2 file without `FOLIWAKE_URL` works unchanged.
51
+ `FoliwakeAppConfig.version` is now `2 | 3` and `app.blocks` has `fromRelease`. The compatibility metadata is
52
+ `remoteConfig: 3, discovery: 1`.
53
+ - d53aa34: `npx @foliwake/next init` (bin `foliwake-next`, no extra dependencies) sets up a Next app: checks the site
54
+ (discovery, `X-Code-Release` on `/index.plain.html`), writes `FOLIWAKE_URL` to `.env.local`, wraps `next.config` in
55
+ `withFoliwake()` (two ES module forms; otherwise it prints the steps), and adds `app/foliwake/[...path]/route.ts`
56
+ and `app/[...path]/page.tsx`. `--preview` adds a preview route behind a development-only `isAuthor()` and an empty
57
+ `FOLIWAKE_PREVIEW_TOKEN=`; `--hook`, `--mount /pages`, `--dry-run`, `--json`, `--force` (only files it generated),
58
+ `--yes` (or `CI=1`; needs `--url`), `--ignore-git-changes`, and `--check` to check an existing setup. Exit codes 0,
59
+ 1 (error) and 2 (input needed); env equivalents `FOLIWAKE_INIT_*`. It never writes or prints a secret value.
60
+ `foliwake next init` in `@foliwake/cli` runs the same wizard.
61
+ - 6b53207: `@foliwake/next/handler`: one route file, `app/foliwake/[...path]/route.ts` with
62
+ `export { GET, HEAD, POST } from '@foliwake/next/handler'`, serves the code and media proxies, the hook (secret in
63
+ `FOLIWAKE_HOOK_SECRET`, Next cache tags expired as by `foliwakeRevalidateHandler`) and `/foliwake/health`.
64
+ Preview is off; `createFoliwakeHandler({ authorizePreview, hook, base })` customises it. It wraps
65
+ `createFoliwakeHandler` of `@foliwake/server/handler`. `codeRoute`, `mediaRoute` and `foliwakeRevalidateHandler`
66
+ stay for the manual setup.
67
+ - 676ecdb: `@foliwake/next/page`: a ready page route. `app/[...path]/page.tsx` with
68
+ `export { default, generateMetadata } from '@foliwake/next/page'` shows live site pages at the app's root (the
69
+ app's own routes win; `/` stays the app's): Suspense, the page read and prepared, preload hints and import map,
70
+ `<FoliwakePage as="article">`, `notFound()` for a missing page. `generateMetadata` gives the title (the first `<h1>`)
71
+ and `noindex` for preview. `createFoliwakePage({ render, prepare, channel, authorize, mount, fallback })`
72
+ customises it; a preview route requires `authorize`.
73
+ - ebc65c2: `withFoliwake` reads `FOLIWAKE_URL`: when it is set, the site's discovery document is read as Next loads
74
+ next.config (with the optional `foliwake.remote.json` version 3 merged), validated, and inlined as a snapshot for
75
+ the server modules; the CSP `img-src` gets the site's media CDN. Nothing is fetched at run time. A failure fails the
76
+ build with the address and the reason. In that case `withFoliwake` returns a promise of the config, which Next
77
+ accepts (type `FoliwakeNextConfig = NextConfig | Promise<NextConfig>`; code that annotated the result as
78
+ `NextConfig` needs the new type). Without `FOLIWAKE_URL` the version 2 file is read as before.
79
+ `foliwakeCspHeader` takes an already read `config`. Without `withFoliwake`, `FOLIWAKE_URL` alone is refused at run
80
+ time with a message that says to wrap next.config.
81
+
82
+ ### Patch Changes
83
+
84
+ - eff516d: `@foliwake/next` ships the config schema as `schemas/remote-2.schema.json`, so `"$schema"` in
85
+ `foliwake.remote.json` resolves when `@foliwake/next` is the only direct dependency (pnpm). The guide installs one
86
+ package, its preview example uses the user name `preview` with the site's preview token, and it explains
87
+ `app.proxies.pages: null`.
88
+ - df85d39: `@foliwake/server/handler`: `createFoliwakeHandler()` serves every Foliwake route of an app as one
89
+ `(request: Request) => Promise<Response>` on the Web Fetch API, for any framework: the code and media proxies under
90
+ the config's prefixes (`/foliwake/code`, `/foliwake/media` by default), `POST /foliwake/hook` (secret in
91
+ `FOLIWAKE_HOOK_SECRET`, `onDelivery` for the app's caches) and `GET /foliwake/health`. Preview is off unless
92
+ `authorizePreview` is given. The config is read on the first request (`FOLIWAKE_URL`), or passed as `config`.
93
+ The hook endpoint core moved from `@foliwake/next` to `@foliwake/server/hook-endpoint` (`createHookEndpoint`);
94
+ a ping of the Next route still answers `@foliwake/next/<version>`. New guide: "Any framework: one handler".
95
+ - Updated dependencies [339fb47]
96
+ - Updated dependencies [69caab7]
97
+ - Updated dependencies [df85d39]
98
+ - @foliwake/blocks-contract@0.10.0
99
+ - @foliwake/server@0.10.0
100
+ - @foliwake/react@0.10.0
101
+
10
102
  ## 0.9.0
11
103
 
12
104
  ### Minor Changes
package/README.md CHANGED
@@ -14,23 +14,39 @@ another React app use `@foliwake/react` with `@foliwake/server`.
14
14
  | --- | --- |
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
+ | `@foliwake/next/page` | `default`, `generateMetadata`, `createFoliwakePage`: a ready page route (`app/[...path]/page.tsx`) |
18
+ | `@foliwake/next/handler` | `GET`, `HEAD`, `POST`, `createFoliwakeHandler`: every Foliwake route (code, media, hook, health) in one route file |
17
19
  | `@foliwake/next/routes` | `codeRoute`, `mediaRoute`: the code and media proxies |
18
20
  | `@foliwake/next/cache` | `readEnvelopeCached`: the cached live read alone; `setGenerationFloor` |
19
21
  | `@foliwake/next/revalidate` | `foliwakeRevalidateHandler`: the route of the hook a Foliwake server calls after a change |
20
22
  | `@foliwake/next/client` | `'use client'`: everything of `@foliwake/react` |
21
23
 
24
+ ## Quick start
25
+
26
+ ```bash
27
+ npm install @foliwake/next
28
+ npx @foliwake/next init --url https://my-site.example.org
29
+ npm run dev
30
+ ```
31
+
32
+ `init` writes `FOLIWAKE_URL` to `.env.local`, wraps `next.config` in `withFoliwake()`, and adds
33
+ `app/foliwake/[...path]/route.ts` (code, media, hook) and `app/[...path]/page.tsx` (site pages). It is idempotent,
34
+ never overwrites your files, writes no secret values, and takes `--preview`, `--hook`, `--mount /pages`, `--dry-run`,
35
+ `--json`, `--check` and `--yes` (`npx @foliwake/next init --help`).
36
+
22
37
  ## Install
23
38
 
24
39
  The packages are published on npm (npmjs.com) under the `@foliwake` scope; no registry setup or token is
25
- needed. Install exact versions, the same for every `@foliwake/*` package:
40
+ needed. Install one package; it brings `@foliwake/react` and `@foliwake/server` at its own exact version:
26
41
 
27
42
  ```bash
28
- pnpm add @foliwake/next@0.3.0 @foliwake/react@0.3.0 @foliwake/server@0.3.0
43
+ pnpm add @foliwake/next
29
44
  ```
30
45
 
31
46
  The app also needs `foliwake.remote.json` in its root (or `FOLIWAKE_REMOTE` naming another file): the site,
32
47
  its live and preview origins, the names of the variables that hold passwords, and the app settings. The guide
33
- below describes every key; the schema ships in `@foliwake/server/schemas/remote-2.schema.json`.
48
+ below describes every key; the schema ships in this package as `schemas/remote-2.schema.json`
49
+ (`"$schema": "./node_modules/@foliwake/next/schemas/remote-2.schema.json"`).
34
50
 
35
51
  ## Minimal example
36
52
 
@@ -159,6 +175,9 @@ import { foliwakeRevalidateHandler } from '@foliwake/next/revalidate';
159
175
  export const { POST } = foliwakeRevalidateHandler({ secretEnv: 'FOLIWAKE_HOOK_SECRET' });
160
176
  ```
161
177
 
178
+ Make the secret with `openssl rand -hex 32 | tr -d '\n'`, and give the Foliwake server the same value. Surrounding
179
+ whitespace and newlines are trimmed from it (with one warning naming the variable); an all-whitespace value is unset.
180
+
162
181
  It checks the signature (within 300 s; `previousSecretEnv` names a second accepted secret while you rotate it)
163
182
  and expires `foliwake:<site>:live:page:<path>` of every changed path, or `foliwake:<site>:live` when every page
164
183
  changed (a code release, a large publication). Paths that are not pages, such as an index, get the same tag:
@@ -447,22 +466,17 @@ interface ReadPageOptions extends PrepareOptions
447
466
  The CSP value for this app's config (strategy A, media base included, 'unsafe-eval' in development).
448
467
 
449
468
  ```ts
450
- function foliwakeCspHeader(opts?: {
451
- configFile?: string;
452
- reportUri?: string;
453
- extra?: CspOptions['extra'];
454
- dev?: boolean;
455
- }): string
469
+ function foliwakeCspHeader(opts?: CspHeaderOptions): string
456
470
  ```
457
471
 
458
472
  **Returns** `string`
459
473
 
460
474
  #### `withFoliwake()`
461
475
 
462
- 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.
476
+ Reads and 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). With FOLIWAKE_URL, the site's discovery document is read now (and the optional version 3 file merged): the result is a promise, and a failure fails the build naming the address and the reason. Without it, the version 2 file is read as before. Nothing is fetched at run time.
463
477
 
464
478
  ```ts
465
- function withFoliwake(nextConfig?: NextConfig, opts?: WithFoliwakeOptions): NextConfig
479
+ function withFoliwake(nextConfig?: NextConfig, opts?: WithFoliwakeOptions): FoliwakeNextConfig
466
480
  ```
467
481
 
468
482
  | Parameter | Type | Description |
@@ -470,10 +484,26 @@ function withFoliwake(nextConfig?: NextConfig, opts?: WithFoliwakeOptions): Next
470
484
  | `nextConfig?` | `NextConfig` | The app's own Next config; its `transpilePackages`, `env` and `headers` are kept. |
471
485
  | `opts?` | `WithFoliwakeOptions` | |
472
486
 
473
- **Returns** `NextConfig`: The Next config to export from next.config.ts.
487
+ **Returns** `FoliwakeNextConfig`: The Next config (or a promise of it) to export from next.config.ts.
474
488
 
475
489
  **Interfaces**
476
490
 
491
+ #### `CspHeaderOptions`
492
+
493
+ Options of `foliwakeCspHeader`.
494
+
495
+ ```ts
496
+ interface CspHeaderOptions
497
+ ```
498
+
499
+ | Member | Type | Description |
500
+ | --- | --- | --- |
501
+ | `configFile?` | `string` | |
502
+ | `config?` | `FoliwakeAppConfig` | A config already read (withFoliwake passes it); default the version 2 file. |
503
+ | `reportUri?` | `string` | |
504
+ | `extra?` | `CspOptions['extra']` | |
505
+ | `dev?` | `boolean` | |
506
+
477
507
  #### `WithFoliwakeOptions`
478
508
 
479
509
  Options of `withFoliwake`.
@@ -487,6 +517,171 @@ interface WithFoliwakeOptions
487
517
  | `configFile?` | `string` | The config file (default FOLIWAKE_REMOTE, else ./foliwake.remote.json). |
488
518
  | `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. |
489
519
 
520
+ **Types**
521
+
522
+ #### `FoliwakeNextConfig`
523
+
524
+ What withFoliwake returns: the config itself, or (with FOLIWAKE_URL) a promise of it; Next accepts both.
525
+
526
+ ```ts
527
+ type FoliwakeNextConfig = NextConfig | Promise<NextConfig>
528
+ ```
529
+
530
+ ### `@foliwake/next/page`
531
+
532
+ **Functions and components**
533
+
534
+ #### `createFoliwakePage()`
535
+
536
+ A page route of Foliwake pages: reads the page of the route's path (live: cached; preview: per request, behind `authorize`), renders it in a Suspense boundary, emits the blocks' preload hints and the import map. A missing page, one outside `app.pages`, or a refused author check is `notFound()`. `generateMetadata` gives the title (the body's first `<h1>`) and `noindex` for preview.
537
+
538
+ ```ts
539
+ function createFoliwakePage(opts?: FoliwakePageOptions): FoliwakeRoute
540
+ ```
541
+
542
+ **Returns** `FoliwakeRoute`
543
+
544
+ **Constants**
545
+
546
+ #### `default`
547
+
548
+ ```ts
549
+ const route: FoliwakeRoute
550
+ ```
551
+
552
+ #### `generateMetadata`
553
+
554
+ The default route's metadata.
555
+
556
+ ```ts
557
+ const generateMetadata: (props: FoliwakeRouteProps) => Promise<PageMetadata>
558
+ ```
559
+
560
+ **Interfaces**
561
+
562
+ #### `FoliwakePageOptions`
563
+
564
+ Options of `createFoliwakePage`.
565
+
566
+ ```ts
567
+ interface FoliwakePageOptions
568
+ ```
569
+
570
+ | Member | Type | Description |
571
+ | --- | --- | --- |
572
+ | `render?` | `(page: FoliwakePageData) => ReactNode` | Returns the app's component for the page; default `<FoliwakePage page={page} as="article" />`. |
573
+ | `prepare?` | `PrepareOptions` | `preparePage` options; `rewriteLink` defaults to the mount's. |
574
+ | `channel?` | `ChannelName` | `live` (default, cached) or `preview` (per request; needs `authorize`). |
575
+ | `authorize?` | `() => boolean \| Promise<boolean>` | The app's author check (cookies(), headers(), its session); false → not found. Required for preview. |
576
+ | `mount?` | `string` | The app path the route is mounted at, such as `/pages`; default the root. |
577
+ | `fallback?` | `ReactNode` | The Suspense fallback while the page is read; default none. |
578
+
579
+ #### `FoliwakeRouteProps`
580
+
581
+ The route's props: Next's params of a catch-all segment `[...path]` or `[[...path]]`.
582
+
583
+ ```ts
584
+ interface FoliwakeRouteProps
585
+ ```
586
+
587
+ | Member | Type | Description |
588
+ | --- | --- | --- |
589
+ | `params` | `Promise<{ path?: string[]; }>` | |
590
+
591
+ **Types**
592
+
593
+ #### `FoliwakeRoute`
594
+
595
+ A page route component with its `generateMetadata`.
596
+
597
+ ```ts
598
+ type FoliwakeRoute = ((props: FoliwakeRouteProps) => ReactNode) & {
599
+ generateMetadata: (props: FoliwakeRouteProps) => Promise<PageMetadata>;
600
+ }
601
+ ```
602
+
603
+ ### `@foliwake/next/handler`
604
+
605
+ **Functions and components**
606
+
607
+ #### `createFoliwakeHandler()`
608
+
609
+ The Foliwake routes of a Next app (code and media proxies, hook, health) for `app/foliwake/[...path]/route.ts`. Preview is off unless `authorizePreview` is given.
610
+
611
+ ```ts
612
+ function createFoliwakeHandler(opts?: FoliwakeNextHandlerOptions): FoliwakeRoutes
613
+ ```
614
+
615
+ | Parameter | Type | Description |
616
+ | --- | --- | --- |
617
+ | `opts?` | `FoliwakeNextHandlerOptions` | `authorizePreview` (default false), `hook` (default on, secret in FOLIWAKE_HOOK_SECRET), `base`. |
618
+
619
+ **Returns** `FoliwakeRoutes`
620
+
621
+ **Constants**
622
+
623
+ #### `GET`
624
+
625
+ The default routes: preview off, hook on (FOLIWAKE_HOOK_SECRET).
626
+
627
+ ```ts
628
+ const GET: RouteHandler
629
+ ```
630
+
631
+ #### `HEAD`
632
+
633
+ ```ts
634
+ const HEAD: RouteHandler
635
+ ```
636
+
637
+ #### `POST`
638
+
639
+ ```ts
640
+ const POST: RouteHandler
641
+ ```
642
+
643
+ **Interfaces**
644
+
645
+ #### `FoliwakeNextHandlerOptions`
646
+
647
+ Options of `createFoliwakeHandler`.
648
+
649
+ ```ts
650
+ interface FoliwakeNextHandlerOptions
651
+ ```
652
+
653
+ | Member | Type | Description |
654
+ | --- | --- | --- |
655
+ | `authorizePreview?` | `AuthorizePreview` | The app's author check for preview files; default `false` (preview answers 404). |
656
+ | `hook?` | `false \| FoliwakeNextHookOptions` | The hook (default secret variable FOLIWAKE_HOOK_SECRET); `false` answers 404 on `/foliwake/hook`. |
657
+ | `base?` | `string` | The app path of the hook and health routes; default `/foliwake` (the route file's folder). |
658
+
659
+ #### `FoliwakeRoutes`
660
+
661
+ The route module exports: `export const { GET, HEAD, POST } = createFoliwakeHandler(…)`.
662
+
663
+ ```ts
664
+ interface FoliwakeRoutes
665
+ ```
666
+
667
+ | Member | Type | Description |
668
+ | --- | --- | --- |
669
+ | `GET` | `RouteHandler` | |
670
+ | `HEAD` | `RouteHandler` | |
671
+ | `POST` | `RouteHandler` | |
672
+
673
+ **Types**
674
+
675
+ #### `FoliwakeNextHookOptions`
676
+
677
+ The hook options of the Next handler: those of `foliwakeRevalidateHandler`, the secret variable optional.
678
+
679
+ ```ts
680
+ type FoliwakeNextHookOptions = Omit<FoliwakeRevalidateOptions, 'secretEnv'> & {
681
+ secretEnv?: string;
682
+ }
683
+ ```
684
+
490
685
  ### `@foliwake/next/routes`
491
686
 
492
687
  **Functions and components**
@@ -664,4 +859,12 @@ interface FoliwakeRevalidateOptions
664
859
 
665
860
  - from `@foliwake/server/hook`: `FoliwakeDeliveryPayload`, `FoliwakeHookPayload`, `FoliwakeOperationKind`
666
861
 
862
+ ### `@foliwake/next/schemas/remote-2.schema.json`
863
+
864
+ A file, not a module: `schemas/remote-2.schema.json` in the package.
865
+
866
+ ### `@foliwake/next/schemas/remote-3.schema.json`
867
+
868
+ A file, not a module: `schemas/remote-3.schema.json` in the package.
869
+
667
870
  <!-- apistop -->
package/dist/config.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { NextConfig } from 'next';
2
+ import { type FoliwakeAppConfig } from '@foliwake/server/config';
2
3
  import { type CspOptions } from '@foliwake/server/csp';
3
4
  /** Options of `withFoliwake`. */
4
5
  export interface WithFoliwakeOptions {
@@ -15,19 +16,27 @@ export interface WithFoliwakeOptions {
15
16
  source?: string;
16
17
  };
17
18
  }
18
- /** The CSP value for this app's config (strategy A, media base included, 'unsafe-eval' in development). */
19
- export declare function foliwakeCspHeader(opts?: {
19
+ /** What withFoliwake returns: the config itself, or (with FOLIWAKE_URL) a promise of it; Next accepts both. */
20
+ export type FoliwakeNextConfig = NextConfig | Promise<NextConfig>;
21
+ /** Options of `foliwakeCspHeader`. */
22
+ export interface CspHeaderOptions {
20
23
  configFile?: string;
24
+ /** A config already read (withFoliwake passes it); default the version 2 file. */
25
+ config?: FoliwakeAppConfig;
21
26
  reportUri?: string;
22
27
  extra?: CspOptions['extra'];
23
28
  dev?: boolean;
24
- }): string;
29
+ }
30
+ /** The CSP value for this app's config (strategy A, media base included, 'unsafe-eval' in development). */
31
+ export declare function foliwakeCspHeader(opts?: CspHeaderOptions): string;
25
32
  /**
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.
33
+ * Reads and validates the Foliwake config when Next loads next.config (build and start) and makes it available to
34
+ * the package's server-only modules (Next `env`, never to client code); adds the package to transpilePackages
35
+ * (its 'use cache' read). With FOLIWAKE_URL, the site's discovery document is read now (and the optional
36
+ * version 3 file merged): the result is a promise, and a failure fails the build naming the address and the
37
+ * reason. Without it, the version 2 file is read as before. Nothing is fetched at run time.
29
38
  *
30
39
  * @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.
40
+ * @returns The Next config (or a promise of it) to export from next.config.ts.
32
41
  */
33
- export declare function withFoliwake(nextConfig?: NextConfig, opts?: WithFoliwakeOptions): NextConfig;
42
+ export declare function withFoliwake(nextConfig?: NextConfig, opts?: WithFoliwakeOptions): FoliwakeNextConfig;
package/dist/config.js CHANGED
@@ -3,11 +3,15 @@ import { readFileSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { configFilePath, parseFoliwakeConfig } from '@foliwake/server/config';
5
5
  import { foliwakeCsp } from '@foliwake/server/csp';
6
+ import { configFromSnapshot, readConfigSnapshot, URL_ENV } from '@foliwake/server/resolve';
6
7
  import { CONFIG_ENV_KEY } from './settings.js';
8
+ function readVersion2(configFile) {
9
+ const file = configFilePath({ file: configFile });
10
+ return parseFoliwakeConfig(readFileSync(file, 'utf8'), { file: path.basename(file) });
11
+ }
7
12
  /** The CSP value for this app's config (strategy A, media base included, 'unsafe-eval' in development). */
8
13
  export function foliwakeCspHeader(opts = {}) {
9
- const file = configFilePath({ file: opts.configFile });
10
- const config = parseFoliwakeConfig(readFileSync(file, 'utf8'), { file: path.basename(file) });
14
+ const config = opts.config ?? readVersion2(opts.configFile);
11
15
  return foliwakeCsp({
12
16
  strategy: 'self-inline',
13
17
  mediaBase: config.app?.media?.base ?? null,
@@ -16,38 +20,58 @@ export function foliwakeCspHeader(opts = {}) {
16
20
  ...(opts.extra ? { extra: opts.extra } : {}),
17
21
  });
18
22
  }
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;
23
+ function readFileText(configFile) {
24
+ const file = configFilePath({ file: configFile });
30
25
  try {
31
- text = readFileSync(file, 'utf8');
26
+ return { file: path.basename(file), text: readFileSync(file, 'utf8') };
32
27
  }
33
28
  catch (error) {
34
- throw new Error(`withFoliwake: cannot read ${file} (${error.code ?? 'error'}). Create foliwake.remote.json or set FOLIWAKE_REMOTE.`);
29
+ const code = error.code ?? 'error';
30
+ throw new Error(`withFoliwake: cannot read ${file} (${code}). Set ${URL_ENV}, or create foliwake.remote.json.`);
35
31
  }
36
- parseFoliwakeConfig(text, { file: path.basename(file) }); // throws a FoliwakeConfigError naming the field
32
+ }
33
+ /** The Next config with the inlined config, transpilePackages and (optionally) the CSP header. */
34
+ function wrapped(nextConfig, opts, inlined, config) {
37
35
  const transpile = new Set([...(nextConfig.transpilePackages ?? []), '@foliwake/next']);
38
36
  const out = {
39
37
  ...nextConfig,
40
38
  transpilePackages: [...transpile],
41
- env: { ...(nextConfig.env ?? {}), [CONFIG_ENV_KEY]: JSON.stringify({ file: path.basename(file), text }) },
39
+ env: { ...(nextConfig.env ?? {}), [CONFIG_ENV_KEY]: JSON.stringify(inlined) },
40
+ };
41
+ if (!opts.csp)
42
+ return out;
43
+ const csp = opts.csp;
44
+ const previous = nextConfig.headers;
45
+ out.headers = async () => {
46
+ const own = previous ? await previous() : [];
47
+ const value = foliwakeCspHeader({ config, reportUri: csp.reportUri, extra: csp.extra });
48
+ return [...own, { source: csp.source ?? '/:path*', headers: [{ key: 'Content-Security-Policy', value }] }];
42
49
  };
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
50
  return out;
53
51
  }
52
+ async function withDiscovery(nextConfig, opts) {
53
+ try {
54
+ const snapshot = await readConfigSnapshot(opts.configFile ? { file: opts.configFile } : {});
55
+ return wrapped(nextConfig, opts, { snapshot }, configFromSnapshot(snapshot));
56
+ }
57
+ catch (error) {
58
+ throw new Error(`withFoliwake: ${error.message}`, { cause: error });
59
+ }
60
+ }
61
+ /**
62
+ * Reads and validates the Foliwake config when Next loads next.config (build and start) and makes it available to
63
+ * the package's server-only modules (Next `env`, never to client code); adds the package to transpilePackages
64
+ * (its 'use cache' read). With FOLIWAKE_URL, the site's discovery document is read now (and the optional
65
+ * version 3 file merged): the result is a promise, and a failure fails the build naming the address and the
66
+ * reason. Without it, the version 2 file is read as before. Nothing is fetched at run time.
67
+ *
68
+ * @param nextConfig - The app's own Next config; its `transpilePackages`, `env` and `headers` are kept.
69
+ * @returns The Next config (or a promise of it) to export from next.config.ts.
70
+ */
71
+ export function withFoliwake(nextConfig = {}, opts = {}) {
72
+ if (process.env[URL_ENV])
73
+ return withDiscovery(nextConfig, opts);
74
+ const { file, text } = readFileText(opts.configFile);
75
+ const config = parseFoliwakeConfig(text, { file }); // throws a FoliwakeConfigError naming the field
76
+ return wrapped(nextConfig, opts, { file, text }, config);
77
+ }
@@ -0,0 +1,33 @@
1
+ import 'server-only';
2
+ import type { AuthorizePreview } from '@foliwake/server/handlers';
3
+ import { type FoliwakeRevalidateOptions } from './revalidate.js';
4
+ /** The hook options of the Next handler: those of `foliwakeRevalidateHandler`, the secret variable optional. */
5
+ export type FoliwakeNextHookOptions = Omit<FoliwakeRevalidateOptions, 'secretEnv'> & {
6
+ secretEnv?: string;
7
+ };
8
+ /** Options of `createFoliwakeHandler`. */
9
+ export interface FoliwakeNextHandlerOptions {
10
+ /** The app's author check for preview files; default `false` (preview answers 404). */
11
+ authorizePreview?: AuthorizePreview;
12
+ /** The hook (default secret variable FOLIWAKE_HOOK_SECRET); `false` answers 404 on `/foliwake/hook`. */
13
+ hook?: false | FoliwakeNextHookOptions;
14
+ /** The app path of the hook and health routes; default `/foliwake` (the route file's folder). */
15
+ base?: string;
16
+ }
17
+ type RouteHandler = (request: Request, context?: unknown) => Promise<Response>;
18
+ /** The route module exports: `export const { GET, HEAD, POST } = createFoliwakeHandler(…)`. */
19
+ export interface FoliwakeRoutes {
20
+ GET: RouteHandler;
21
+ HEAD: RouteHandler;
22
+ POST: RouteHandler;
23
+ }
24
+ /**
25
+ * The Foliwake routes of a Next app (code and media proxies, hook, health) for
26
+ * `app/foliwake/[...path]/route.ts`. Preview is off unless `authorizePreview` is given.
27
+ *
28
+ * @param opts - `authorizePreview` (default false), `hook` (default on, secret in FOLIWAKE_HOOK_SECRET), `base`.
29
+ */
30
+ export declare function createFoliwakeHandler(opts?: FoliwakeNextHandlerOptions): FoliwakeRoutes;
31
+ /** The default routes: preview off, hook on (FOLIWAKE_HOOK_SECRET). */
32
+ export declare const GET: RouteHandler, HEAD: RouteHandler, POST: RouteHandler;
33
+ export {};
@@ -0,0 +1,32 @@
1
+ // @foliwake/next/handler: every Foliwake route of a Next app in one route file,
2
+ // `app/foliwake/[...path]/route.ts`:
3
+ //
4
+ // export { GET, HEAD, POST } from '@foliwake/next/handler';
5
+ //
6
+ // A thin wrapper of `createFoliwakeHandler` of `@foliwake/server/handler`: the config is the one withFoliwake()
7
+ // inlined at build time, and the hook expires Next's cache tags (`foliwakeRevalidateHandler`).
8
+ import 'server-only';
9
+ import { createFoliwakeHandler as createServerHandler, HOOK_SECRET_ENV } from '@foliwake/server/handler';
10
+ import { foliwakeRevalidateHandler } from './revalidate.js';
11
+ import { foliwakeConfig } from './server.js';
12
+ function nextHook(hook) {
13
+ return foliwakeRevalidateHandler({ ...hook, secretEnv: hook.secretEnv ?? HOOK_SECRET_ENV }).POST;
14
+ }
15
+ /**
16
+ * The Foliwake routes of a Next app (code and media proxies, hook, health) for
17
+ * `app/foliwake/[...path]/route.ts`. Preview is off unless `authorizePreview` is given.
18
+ *
19
+ * @param opts - `authorizePreview` (default false), `hook` (default on, secret in FOLIWAKE_HOOK_SECRET), `base`.
20
+ */
21
+ export function createFoliwakeHandler(opts = {}) {
22
+ const handler = createServerHandler({
23
+ config: foliwakeConfig,
24
+ authorizePreview: opts.authorizePreview ?? false,
25
+ hook: opts.hook === false ? false : { endpoint: nextHook(opts.hook ?? {}) },
26
+ ...(opts.base ? { base: opts.base } : {}),
27
+ });
28
+ const route = (request) => handler(request);
29
+ return { GET: route, HEAD: route, POST: route };
30
+ }
31
+ /** The default routes: preview off, hook on (FOLIWAKE_HOOK_SECRET). */
32
+ export const { GET, HEAD, POST } = createFoliwakeHandler();
@@ -0,0 +1,19 @@
1
+ import type { Step } from './plan.js';
2
+ /** What happened to one step. */
3
+ export type Outcome = 'created' | 'updated' | 'exists' | 'skipped' | 'manual';
4
+ /** One line of the report. */
5
+ export interface StepResult {
6
+ path: string;
7
+ outcome: Outcome;
8
+ what: string;
9
+ /** Why it was skipped or must be done by hand, or a warning. */
10
+ note?: string;
11
+ }
12
+ /** How to apply. */
13
+ export interface ApplyOptions {
14
+ cwd: string;
15
+ dryRun: boolean;
16
+ force: boolean;
17
+ }
18
+ /** Applies every step in order. */
19
+ export declare function applySteps(steps: readonly Step[], opts: ApplyOptions): StepResult[];