Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,5 @@ All notable changes are listed here. The format follows [Keep a Changelog](https
- API tokens with scopes, routes, expiry and rotation (`wp headless token`).
- Preview of drafts, scheduled and private posts from the front end: one-time link token, session, `GET /wp-json/headless/v1/preview/posts/{id}` (autosave, live or revision).
- Revalidation: signed notifications of changes (posts, terms, menus, site options, files) to the front end, merged, off the request (Action Scheduler or WP-Cron), with retries; `wp headless revalidate ping`.
- Site manifest: `GET /wp-json/headless/v1/site` (site, languages, menus as trees, locations, front page, content types and taxonomies).
- mu-plugin loader (`stubs/pollora-headless.php`) and a Pollora service provider discovered by Composer.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ It works on a classic WordPress, on Bedrock and inside a [Pollora](https://pollo
| API tokens | `wp headless token create <user> --scopes=read --routes=/wp/v2/posts --expires=90d`: `Authorization: Bearer hl.…`, as the user, limited to read or write and to route prefixes. Only a hash is stored; a wrong token answers 401, a request outside the scopes 403. `rotate` keeps the old token alive for a grace period. |
| Preview | The editor's Preview button opens your front end with a one-time token; the front end trades it for a session and reads the draft, scheduled or private post, with the editor's latest autosave laid over it. See [Preview](#preview-from-your-front-end). |
| Revalidation | When a post is published, updated, unpublished or deleted, or a term, a menu, a site option or a file changes, the front end is told: one signed POST, merged with the other changes of the last seconds, sent off the request, tried again if it fails. See [Revalidation](#telling-your-front-end-what-changed). |
| Site manifest | `GET /wp-json/headless/v1/site`: the site and its languages, the menus as trees with front-end paths, the menu locations, the front page and the content types with their REST routes, in one public, cacheable answer. |
| URL mapper | `UrlMapper::toFront()` turns a URL of the WordPress site into the URL of the same page on the front end. It is the one place every URL the package hands out goes through. |

Nothing changes on the public site until you set the front-end URL: a site that is not told where its front end lives is never locked.
Expand Down Expand Up @@ -139,6 +140,17 @@ export async function POST(request) {

Nuxt, Astro, SvelteKit or Express work the same way: verify, then purge whatever your framework caches by tag or by path.

## Reading the site once

```js
const site = await (await fetch('https://cms.example.com/wp-json/headless/v1/site')).json();
site.menus.find((m) => m.slug === 'main').items; // [{ id, title, url, path: '/about/', target, classes, type, object, object_id, children: [...] }]
site.locations; // [{ location: 'primary', description: 'Primary Menu', menu: 'main' }]
site.post_types; // [{ name: 'post', rest_base: 'posts', rest_namespace: 'wp/v2', has_archive, rewrite_slug, ... }]
```

`path` is the address on your front end (`null` for a link to another site). The answer is the same until the site changes, so it carries an `ETag`; revalidate it on the `menus`, `options` and `site:<id>` tags of the [notifications](#telling-your-front-end-what-changed).

## Roadmap

`0.1` core · `0.2` CORS, REST security and speed, URL mapping, Polylang and WPML, API tokens · `0.3` content preview · `0.4` revalidation webhooks (this release) · `0.5` site manifest, media, blocks as JSON, redirects · `0.6` SEO (Yoast, Rank Math, AIOSEO, SEOPress, The SEO Framework) · `0.7` optional WPGraphQL, schema snapshots, forms and search · `0.8` doctor, end-to-end tests · `1.0` frozen contract.
Expand Down
6 changes: 6 additions & 0 deletions config/headless.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,10 @@
// More options whose change is announced, on top of the title, the permalinks, the front page and a few more.
'options' => [],
],

// GET /wp-json/headless/v1/site: the site, its languages, its menus as trees (with front-end paths), the front page and the
// content types in one answer, public and cacheable. Only active once a front-end URL is set.
'manifest' => [
'enabled' => true,
],
];
2 changes: 1 addition & 1 deletion src/Domain/Cache/RestCachePolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public function __construct(
private int $maxAge = 60,
private int $sharedMaxAge = 300,
private int $staleWhileRevalidate = 60,
private array $namespaces = ['/wp/v2'],
private array $namespaces = ['/wp/v2', '/headless/v1/site', '/headless/v1/redirects', '/headless/v1/media'],
private array $neverRoutes = ['/wp/v2/users/me', '/wp/v2/settings', '/wp/v2/block-renderer', '/wp/v2/search'],
) {}

Expand Down
87 changes: 87 additions & 0 deletions src/Domain/Manifest/MenuTree.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Domain\Manifest;

/**
* Turns the flat list of a menu's items into the tree a front end renders.
*
* WordPress gives every item its parent's ID and its position; the tree keeps the order of the editor, puts an
* item whose parent is not in the list (a parent that was deleted) at the top, and cannot loop on a bad parent.
*/
final class MenuTree
{
/**
* @param list<array{id: int, parent: int, order: int}&array<string, mixed>> $items
* @return list<array<string, mixed>>
*/
public static function build(array $items): array
{
usort($items, static fn (array $a, array $b): int => [$a['order'], $a['id']] <=> [$b['order'], $b['id']]);

$ids = array_column($items, 'id');
$children = [];

foreach ($items as $item) {
$parent = $item['parent'] !== $item['id'] && in_array($item['parent'], $ids, true) ? $item['parent'] : 0;
$children[$parent][] = $item;
}

// Items that only point at each other (A under B under A) are reachable from no top: the first of them becomes one
while (($lost = array_values(array_diff($ids, self::reached($children)))) !== []) {
$first = array_values(array_filter($items, static fn (array $item): bool => $item['id'] === $lost[0]))[0];
$children[$first['parent']] = array_values(array_filter($children[$first['parent']] ?? [], static fn (array $item): bool => $item['id'] !== $first['id']));
$children[0][] = $first;
}

return self::level($children, 0, []);
}

/**
* @param array<int, list<array<string, mixed>>> $children
* @return list<int>
*/
private static function reached(array $children): array
{
$reached = [];
$queue = [0];

while ($queue !== []) {
$parent = array_shift($queue);

foreach ($children[$parent] ?? [] as $item) {
if (! in_array($item['id'], $reached, true)) {
$reached[] = (int) $item['id'];
$queue[] = (int) $item['id'];
}
}
}

return $reached;
}

/**
* @param array<int, list<array<string, mixed>>> $children
* @param list<int> $path the items above this level, so that a cycle (A under B under A) ends
* @return list<array<string, mixed>>
*/
private static function level(array $children, int $parent, array $path): array
{
$level = [];

foreach ($children[$parent] ?? [] as $item) {
$id = (int) $item['id'];

if (in_array($id, $path, true)) {
continue;
}

unset($item['parent'], $item['order']);
$item['children'] = self::level($children, $id, [...$path, $id]);
$level[] = $item;
}

return $level;
}
}
2 changes: 2 additions & 0 deletions src/Infrastructure/Config/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ private function __construct(
public int $revalidationDebounce,
public int $revalidationAttempts,
public array $revalidationOptions,
public bool $manifest,
) {}

/**
Expand Down Expand Up @@ -116,6 +117,7 @@ public static function fromArray(array $config, string $backendUrl): self
revalidationDebounce: max(0, self::int($revalidation, 'debounce', 3)),
revalidationAttempts: min(5, max(1, self::int($revalidation, 'max_attempts', 5))),
revalidationOptions: array_values(array_unique([...ChangeWatcher::defaultOptions(), ...self::strings($revalidation, 'options')])),
manifest: $front instanceof Origin && self::bool(is_array($config['manifest'] ?? null) ? $config['manifest'] : [], 'enabled', true),
);
}

Expand Down
8 changes: 8 additions & 0 deletions src/Infrastructure/WordPress/Bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Pollora\Headless\Domain\Front\Origin;
use Pollora\Headless\Domain\Front\UrlMapper;
use Pollora\Headless\Domain\Language\Languages;
use Pollora\Headless\Domain\Language\LanguageUrls;
use Pollora\Headless\Infrastructure\Config\Settings;
use Pollora\Headless\Infrastructure\Config\SettingsLoader;
use Pollora\Headless\Infrastructure\Language\LanguagesFactory;
Expand Down Expand Up @@ -90,6 +91,13 @@ public static function modules(Settings $settings, ?Languages $languages = null)
$modules[] = new RevalidationRunner($revalidator);
}

if ($settings->manifest && $settings->urls instanceof UrlMapper && $settings->front instanceof Origin) {
$urls = $languages->isActive()
? new LanguageUrls($settings->urls, $settings->backend, $settings->front, $settings->languageFronts, $languages)
: $settings->urls;
$modules[] = new ManifestRoutes(new SiteManifest($urls, $settings->front, $languages));
}

if ($settings->restCache instanceof RestCachePolicy || $settings->perPageMax !== null) {
$modules[] = new RestPerformance($settings->restCache, $settings->perPageMax);
}
Expand Down
35 changes: 35 additions & 0 deletions src/Infrastructure/WordPress/ManifestRoutes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Infrastructure\WordPress;

/**
* `GET /wp-json/headless/v1/site`: the manifest of the site (see SiteManifest).
*/
final readonly class ManifestRoutes implements Module
{
public const string NAMESPACE = 'headless/v1';

public function __construct(private SiteManifest $manifest) {}

public function register(HookRegistrar $hooks): void
{
$hooks->addAction('rest_api_init', [$this, 'routes']);
}

public function routes(): void
{
register_rest_route(self::NAMESPACE, '/site', [
'methods' => 'GET',
'callback' => [$this, 'show'],
// Public on purpose: it holds what a visitor sees (menus, languages, addresses), and the front end reads it at build time.
'permission_callback' => '__return_true',
]);
}

public function show(): \WP_REST_Response
{
return rest_ensure_response($this->manifest->build());
}
}
Loading
Loading