@extantape/payload-plugin-cache-refresh 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 EXTANT APE
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,95 @@
1
- # Temporary Holding Version
1
+ # payload-plugin-cache-refresh
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
+ Cache refresh for Payload: a dashboard button that refreshes your Next.js site's cache tags, for the people you choose, after a confirmation.
4
+
5
+ **Status:** early. Version 0.2.0, a security release, is on npm; see the changelog. The plugin is covered by 110 unit tests with `next/cache.js` mocked: who may refresh, the same-site check and the allowed origins, the lock and cooldown, the confirmation step, a failing tag list, a tag that fails to refresh, a logger or hook that throws something other than an error, the audit hook, stale or expire, changed tags or everything, warming, and the words the button shows for each reply. It has not been run against a real Next.js app yet, the button has not been rendered in a browser, and the screen reader behavior is untested.
6
+
7
+ ## What it does
8
+
9
+ - Adds a **Refresh site cache** button to the admin dashboard, shown only to users your `canRefresh` function allows.
10
+ - Asks to confirm. The endpoint refuses to do anything until it is sent `confirm: true`, so the confirmation holds for API calls too.
11
+ - Calls `revalidateTag` for each tag you give it. It knows nothing about your tag names, routes or roles.
12
+ - Refreshes in stale-while-revalidate mode by default: pages keep showing while they rebuild. An option expires them at once instead.
13
+ - If you give it `changedTags`, the button refreshes only those by default. The admin can choose Everything.
14
+ - Can fetch a list of pages once after a refresh, one at a time, each with a timeout and all inside one deadline, so they are rebuilt before a visitor arrives. The reply says how many pages warmed, failed, timed out or were skipped. A failed fetch never fails the refresh.
15
+ - Calls `onRefresh` with who, when and how many, for your audit trail.
16
+
17
+ Signed-out requests get 401. A signed-in user your rule refuses gets 403, and a rule that throws counts as a no. Payload's own auth applies to the endpoint.
18
+
19
+ Payload's CSRF check does not cover this endpoint: a form on another site can post `text/plain` with the admin's cookie and no preflight. So the plugin checks the request itself. The refresh needs `Content-Type: application/json` (415 otherwise), and the browser must show it came from this site: `Sec-Fetch-Site` must be `same-origin` if sent, and `Origin` must match the allowed origins if sent. A request with neither header gets 403. An `Origin` of `null` is always refused.
20
+
21
+ When the browser sends `Origin`, it is checked against the allowed origins. Those are `allowedOrigins` when you set it, and then only that list, never the request's own origin. It must hold at least one entry, and every entry must be an http or https address such as `https://admin.example.org`, or the plugin refuses to start with an error saying which entry to fix. Leave it unset to use Payload's `serverURL`, or the origin of the request URL when `serverURL` is empty (Payload's default) or isn't an http or https address. Set one of the two if a proxy changes the request URL.
22
+
23
+ A second press while a refresh runs, or within `cooldownMs` after one, gets 429.
24
+
25
+ If the tag list can't be read (a function throws, or a tag is empty or longer than 256 characters), nothing is refreshed.
26
+
27
+ If Next.js fails to refresh a tag, the plugin still tries the rest, so as much of the site as possible is fresh. The reply is then a 500 with `refreshed: false`, `count` (the tags that refreshed) and `failed` (the ones that didn't). Each failure is written to Payload's log. The reply never carries the error text. `onRefresh` gets only the tags that refreshed, with the `failed` count, so if you clear recorded tags there you clear only those. Nothing is warmed after a failure. The button says how many tags refreshed and how many didn't, and suggests trying again.
28
+
29
+ ## On its own, and with others
30
+
31
+ **On its own:** Cache Refresh needs only Payload and Next.js. It adds one endpoint and a dashboard button, and refreshes the tags your site records. It doesn't depend on any other plugin.
32
+
33
+ **Needs:** Payload `^3.80.0` and Next.js `>=16.0.0` as peer dependencies, with React `^19.0.0` optional. No other EXTANT APE plugin is required.
34
+
35
+ **Works with:**
36
+ - **Audit Trail:** your `onRefresh` can call Audit Trail's `recordEvent`, so each refresh is kept with who ran it and how many tags it refreshed. That's your own code, and neither plugin imports the other.
37
+
38
+ **Color Theory:** no direct link. The dashboard button uses its own `--cache-refresh-*` variables, which fall back to Payload's `--theme-*` colors, so it follows Color Theory's admin colors when its `applyToAdmin` option is on. Its focus ring falls back to a fixed orange.
39
+
40
+ ## Install
41
+
42
+ ```sh
43
+ npm install @extantape/payload-plugin-cache-refresh
44
+ ```
45
+
46
+ Needs Payload 3.80 or later and Next.js 16 or later, which has the two-argument `revalidateTag`.
47
+
48
+ ```ts
49
+ import { cacheRefreshPlugin } from '@extantape/payload-plugin-cache-refresh'
50
+
51
+ export default buildConfig({
52
+ plugins: [
53
+ cacheRefreshPlugin({
54
+ canRefresh: (req) => req.user?.role === 'admin',
55
+ tags: ['pages', 'posts', 'menu'],
56
+ }),
57
+ ],
58
+ })
59
+ ```
60
+
61
+ Regenerate Payload's import map after adding it, so the button is found.
62
+
63
+ ## Options
64
+
65
+ | Option | What it does |
66
+ | --- | --- |
67
+ | `canRefresh(req)` | Required. Returns true for users who may refresh. |
68
+ | `tags` | Required. A list, or an async function returning one. What Everything refreshes. |
69
+ | `changedTags({ req })` | Tags changed since the last refresh, for example ones your scripts recorded. When given, the button offers Only what changed (the default) and Everything. |
70
+ | `mode` | `'stale'` (default) or `'expire'`. Stale calls `revalidateTag(tag, profile)`. Expire calls `revalidateTag(tag, { expire: 0 })`, so the next visit waits for a fresh page. |
71
+ | `profile` | The profile for stale mode. Default `'max'`. |
72
+ | `warmPaths` | A list of paths, or a function returning one, fetched after a refresh. A path starts with a single `/` and has no backslash. Anything else, such as `//host` or `/\host`, is refused and counted as failed. The URL is built on `warmBaseUrl` and its origin is checked again before the fetch. Redirects are not followed. |
73
+ | `warmBaseUrl` | The site's address, such as `https://example.org`. Warming is off without it. |
74
+ | `warmTimeoutMs` | Time for each warming fetch. Default 5000. |
75
+ | `warmDeadlineMs` | Total time for all warming. Pages left when it passes are skipped and reported. Default 15000. |
76
+ | `cooldownMs` | Time after a refresh before the next is accepted. Default 5000. |
77
+ | `allowedOrigins` | Origins a refresh may come from, checked when the browser sends `Origin`. When set, only this list is used, and it needs at least one entry, each an http or https address, or the plugin refuses to start. Default Payload's `serverURL`, else the request's origin. |
78
+ | `onRefresh(report)` | Gets `who` (id, collection, email), `at`, `count`, `failed`, `scope`, `mode` and `tags`. `tags` holds only the tags that refreshed, and `failed` counts the ones that didn't. If it throws, the refresh stays and the response says `audited: false`. It isn't called when zero tags were refreshed. |
79
+ | `endpointPath` | Default `/cache-refresh`. |
80
+ | `adminButton` | Default true. Set false and import `CacheRefreshButton` from `@extantape/payload-plugin-cache-refresh/client` to place it yourself. |
81
+
82
+ The plugin never clears your recorded changed tags. Do that in `onRefresh`, which receives the tags it refreshed.
83
+
84
+ The button's words can be replaced with the `text` prop (its `partial`, `noneRefreshed` and `partialNotAudited` entries cover a refresh that only partly went through), and its colors with `--cache-refresh-ink`, `--cache-refresh-paper`, `--cache-refresh-line` and `--cache-refresh-focus`.
85
+
86
+ ## Limits
87
+
88
+ - A refresh is a request to Next.js, and in stale mode the rebuild happens when a page is next visited. Warming is how you bring that forward.
89
+ - Expiry is not undone if a later step fails. The tag list is checked first for that reason.
90
+ - The lock and cooldown live in one server process. Several instances each keep their own.
91
+ - It refreshes the cache of the Next.js process serving the request. Other servers or a CDN in front need their own handling.
92
+
93
+ ## License
94
+
95
+ MIT. Copyright (c) 2026 EXTANT APE.
@@ -0,0 +1,40 @@
1
+ export type CacheRefreshText = {
2
+ button: string;
3
+ title: string;
4
+ explainStale: string;
5
+ explainExpire: string;
6
+ changed: (count: number | null) => string;
7
+ everything: string;
8
+ confirm: string;
9
+ cancel: string;
10
+ working: string;
11
+ done: (count: number) => string;
12
+ nothing: string;
13
+ warmFailed: (failed: number) => string;
14
+ warmTimedOut: (n: number) => string;
15
+ warmSkipped: (n: number) => string;
16
+ busy: string;
17
+ notAudited: string;
18
+ partial: (refreshed: number, failed: number) => string;
19
+ noneRefreshed: string;
20
+ partialNotAudited: string;
21
+ failed: string;
22
+ };
23
+ export declare const defaultText: CacheRefreshText;
24
+ /**
25
+ * What the button says about a refresh reply. `done` is true only for a full refresh, which closes the panel; after
26
+ * a partial or failed refresh the panel stays open so the admin can try again.
27
+ */
28
+ export declare function replyMessage(status: number, body: unknown, text?: CacheRefreshText): {
29
+ message: string;
30
+ done: boolean;
31
+ };
32
+ /**
33
+ * The dashboard button. Renders nothing for anyone the host does not allow. Pressing it opens a confirmation
34
+ * panel; nothing is refreshed until "Refresh now". Escape or Cancel closes the panel and returns focus.
35
+ */
36
+ export declare function CacheRefreshButton({ apiRoute, endpointPath, text }: {
37
+ apiRoute?: string;
38
+ endpointPath?: string;
39
+ text?: Partial<CacheRefreshText>;
40
+ }): import("react").JSX.Element | null;
@@ -0,0 +1,128 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useCallback, useEffect, useId, useRef, useState } from 'react';
4
+ export const defaultText = {
5
+ button: 'Refresh site cache',
6
+ title: 'Refresh the site cache?',
7
+ explainStale: 'Visitors keep seeing the current pages while they are rebuilt.',
8
+ explainExpire: 'The next visitor to each page waits while it is rebuilt.',
9
+ changed: (n) => (n === null ? 'Only what changed' : `Only what changed (${n})`),
10
+ everything: 'Everything',
11
+ confirm: 'Refresh now',
12
+ cancel: 'Cancel',
13
+ working: 'Refreshing...',
14
+ done: (n) => `Refreshed ${n} ${n === 1 ? 'tag' : 'tags'}.`,
15
+ nothing: 'Nothing had changed, so nothing was refreshed.',
16
+ warmFailed: (n) => `${n} ${n === 1 ? 'page' : 'pages'} could not be warmed. The refresh itself went through.`,
17
+ warmTimedOut: (n) => `${n} ${n === 1 ? 'page' : 'pages'} took too long to warm.`,
18
+ warmSkipped: (n) => `${n} ${n === 1 ? 'page was' : 'pages were'} not warmed.`,
19
+ busy: 'A refresh is running or just finished. Try again in a few seconds.',
20
+ notAudited: 'The refresh went through, but the record of it could not be saved.',
21
+ partial: (n, f) => `Only part of the refresh went through: ${n} ${n === 1 ? 'tag was' : 'tags were'} refreshed and ${f} ${f === 1 ? 'was' : 'were'} not. Try again in a few seconds.`,
22
+ noneRefreshed: 'The refresh did not go through. No tags were refreshed. Try again in a few seconds.',
23
+ partialNotAudited: 'The record of the tags that were refreshed could not be saved.',
24
+ failed: 'The refresh did not happen. Nothing was changed.',
25
+ };
26
+ /**
27
+ * What the button says about a refresh reply. `done` is true only for a full refresh, which closes the panel; after
28
+ * a partial or failed refresh the panel stays open so the admin can try again.
29
+ */
30
+ export function replyMessage(status, body, text = defaultText) {
31
+ const t = text;
32
+ const out = (body && typeof body === 'object' ? body : {});
33
+ if (status === 429)
34
+ return { message: t.busy, done: false };
35
+ if (status < 200 || status >= 300) {
36
+ if (out.reason !== 'revalidate' || typeof out.count !== 'number' || typeof out.failed !== 'number')
37
+ return { message: t.failed, done: false };
38
+ const parts = [out.count > 0 ? t.partial(out.count, out.failed) : t.noneRefreshed];
39
+ if (out.count > 0 && out.audited === false)
40
+ parts.push(t.partialNotAudited);
41
+ return { message: parts.join(' '), done: false };
42
+ }
43
+ if (typeof out.count !== 'number')
44
+ return { message: t.failed, done: false };
45
+ const parts = [out.count === 0 ? t.nothing : t.done(out.count)];
46
+ const w = out.warmed;
47
+ if (w?.failed)
48
+ parts.push(t.warmFailed(w.failed));
49
+ if (w?.timedOut)
50
+ parts.push(t.warmTimedOut(w.timedOut));
51
+ if (w?.skipped)
52
+ parts.push(t.warmSkipped(w.skipped));
53
+ if (out.audited === false)
54
+ parts.push(t.notAudited);
55
+ return { message: parts.join(' '), done: true };
56
+ }
57
+ const v = (name, fallback) => `var(--cache-refresh-${name}, ${fallback})`;
58
+ const ink = v('ink', 'currentColor');
59
+ const paper = v('paper', 'var(--theme-elevation-0, Canvas)');
60
+ const line = v('line', 'color-mix(in srgb, currentColor 45%, transparent)');
61
+ const focus = v('focus', '#b85c00');
62
+ const s = {
63
+ wrap: { font: 'inherit', color: ink, margin: '0 0 1.5rem' },
64
+ button: { font: 'inherit', color: ink, background: paper, border: `1px solid ${line}`, borderRadius: 6, minHeight: 36, padding: '6px 14px', cursor: 'pointer' },
65
+ panel: { marginTop: 8, maxWidth: 440, background: paper, color: ink, border: `1px solid ${line}`, borderRadius: 8, padding: 14 },
66
+ fieldset: { border: 0, margin: '8px 0', padding: 0 },
67
+ row: { display: 'flex', gap: 8, alignItems: 'center', minHeight: 32 },
68
+ actions: { display: 'flex', gap: 8, marginTop: 12 },
69
+ note: { margin: '8px 0 0' },
70
+ };
71
+ const css = `.cache-refresh :focus-visible{outline:3px solid ${focus};outline-offset:2px}.cache-refresh button:disabled{cursor:progress;opacity:.7}`;
72
+ /**
73
+ * The dashboard button. Renders nothing for anyone the host does not allow. Pressing it opens a confirmation
74
+ * panel; nothing is refreshed until "Refresh now". Escape or Cancel closes the panel and returns focus.
75
+ */
76
+ export function CacheRefreshButton({ apiRoute = '/api', endpointPath = '/cache-refresh', text }) {
77
+ const t = { ...defaultText, ...text };
78
+ const url = `${apiRoute}${endpointPath}`;
79
+ const [status, setStatus] = useState(null);
80
+ const [open, setOpen] = useState(false);
81
+ const [scope, setScope] = useState('changed');
82
+ const [busy, setBusy] = useState(false);
83
+ const [message, setMessage] = useState('');
84
+ const trigger = useRef(null);
85
+ const heading = useRef(null);
86
+ const id = useId();
87
+ useEffect(() => {
88
+ let live = true;
89
+ fetch(url, { credentials: 'include' })
90
+ .then((r) => (r.ok ? r.json() : null))
91
+ .then((s2) => live && setStatus(s2))
92
+ .catch(() => live && setStatus(null));
93
+ return () => {
94
+ live = false;
95
+ };
96
+ }, [url]);
97
+ useEffect(() => {
98
+ if (open)
99
+ heading.current?.focus();
100
+ }, [open]);
101
+ const close = useCallback(() => {
102
+ setOpen(false);
103
+ trigger.current?.focus();
104
+ }, []);
105
+ const run = async () => {
106
+ setBusy(true);
107
+ setMessage(t.working);
108
+ try {
109
+ const res = await fetch(url, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ confirm: true, scope: status?.hasChanged ? scope : 'all' }) });
110
+ const body = await res.json().catch(() => null);
111
+ const said = replyMessage(res.status, body, t);
112
+ setMessage(said.message);
113
+ if (said.done) {
114
+ setOpen(false);
115
+ trigger.current?.focus();
116
+ }
117
+ }
118
+ catch {
119
+ setMessage(t.failed);
120
+ }
121
+ finally {
122
+ setBusy(false);
123
+ }
124
+ };
125
+ if (!status?.allowed)
126
+ return null;
127
+ return (_jsxs("div", { className: "cache-refresh", style: s.wrap, onKeyDown: (e) => e.key === 'Escape' && open && !busy && close(), children: [_jsx("style", { children: css }), _jsx("button", { ref: trigger, type: "button", style: s.button, "aria-expanded": open, "aria-controls": id, onClick: () => (open ? close() : setOpen(true)), children: t.button }), open && (_jsxs("div", { id: id, role: "group", "aria-labelledby": `${id}-h`, style: s.panel, children: [_jsx("h3", { id: `${id}-h`, ref: heading, tabIndex: -1, style: { margin: 0, fontSize: '1em' }, children: t.title }), _jsx("p", { style: s.note, children: status.mode === 'expire' ? t.explainExpire : t.explainStale }), status.hasChanged && (_jsxs("fieldset", { style: s.fieldset, children: [_jsx("legend", { className: "visually-hidden", style: { position: 'absolute', width: 1, height: 1, overflow: 'hidden', clip: 'rect(0 0 0 0)' }, children: t.title }), _jsxs("label", { style: s.row, children: [_jsx("input", { type: "radio", name: `${id}-scope`, checked: scope === 'changed', onChange: () => setScope('changed') }), " ", t.changed(status.changedCount)] }), _jsxs("label", { style: s.row, children: [_jsx("input", { type: "radio", name: `${id}-scope`, checked: scope === 'all', onChange: () => setScope('all') }), " ", t.everything] })] })), _jsxs("div", { style: s.actions, children: [_jsx("button", { type: "button", style: s.button, disabled: busy, onClick: () => void run(), children: t.confirm }), _jsx("button", { type: "button", style: s.button, disabled: busy, onClick: close, children: t.cancel })] })] })), _jsx("p", { role: "status", "aria-live": "polite", style: s.note, children: message })] }));
128
+ }
@@ -0,0 +1 @@
1
+ export { CacheRefreshButton, defaultText, replyMessage, type CacheRefreshText } from './CacheRefreshButton.js';
@@ -0,0 +1,2 @@
1
+ 'use client';
2
+ export { CacheRefreshButton, defaultText, replyMessage } from './CacheRefreshButton.js';
@@ -0,0 +1,13 @@
1
+ import { type Endpoint, type Plugin } from 'payload';
2
+ import type { CacheRefreshOptions } from './types.js';
3
+ export type * from './types.js';
4
+ /**
5
+ * Cache refresh for Payload: an endpoint and a dashboard button that refresh a Next.js site's cache tags for
6
+ * the people the host allows. Knows nothing about any app's tag names, routes or roles.
7
+ */
8
+ export declare const MAX_TAG_LENGTH = 256;
9
+ /** The path rule: one leading slash, no backslash, no control characters. Anything else could leave the site. */
10
+ export declare const isSafePath: (path: unknown) => path is string;
11
+ export declare function makeEndpoints(opts: CacheRefreshOptions, serverURL?: string): Endpoint[];
12
+ export declare const cacheRefreshPlugin: (opts: CacheRefreshOptions) => Plugin;
13
+ export default cacheRefreshPlugin;
package/dist/index.js ADDED
@@ -0,0 +1,331 @@
1
+ import { APIError } from 'payload';
2
+ /**
3
+ * Cache refresh for Payload: an endpoint and a dashboard button that refresh a Next.js site's cache tags for
4
+ * the people the host allows. Knows nothing about any app's tag names, routes or roles.
5
+ */
6
+ export const MAX_TAG_LENGTH = 256;
7
+ const DEFAULT_PATH = '/cache-refresh';
8
+ const BUTTON = '@extantape/payload-plugin-cache-refresh/client#CacheRefreshButton';
9
+ const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' } });
10
+ const refuse = (message, status, reason) => {
11
+ throw new APIError(message, status, { reason }, true);
12
+ };
13
+ /** Text for anything a catch receives, whatever was thrown. Never throws. */
14
+ const describeThrown = (err) => {
15
+ try {
16
+ if (typeof err === 'string')
17
+ return err;
18
+ const message = err !== null && typeof err === 'object' ? err.message : undefined;
19
+ if (typeof message === 'string')
20
+ return message;
21
+ return err === null || err === undefined ? String(err) : `a thrown ${typeof err}`;
22
+ }
23
+ catch {
24
+ return 'an unreadable error';
25
+ }
26
+ };
27
+ /** The name of a thrown value, such as `TimeoutError`, or an empty string. Never throws. */
28
+ const nameOf = (err) => {
29
+ try {
30
+ const name = err !== null && typeof err === 'object' ? err.name : undefined;
31
+ return typeof name === 'string' ? name : '';
32
+ }
33
+ catch {
34
+ return '';
35
+ }
36
+ };
37
+ /** Writes to Payload's logger. A missing or failing logger never changes what the plugin does. */
38
+ const log = (req, level, message) => {
39
+ try {
40
+ req.payload?.logger?.[level]?.(message);
41
+ }
42
+ catch {
43
+ // Logging is best effort.
44
+ }
45
+ };
46
+ /** Sign-in first (401), then the host's rule (403). A rule that throws is a no. */
47
+ async function guard(req, opts) {
48
+ const user = req.user;
49
+ if (!user)
50
+ return refuse('Sign in first.', 401, 'signIn');
51
+ let allowed = false;
52
+ try {
53
+ allowed = (await opts.canRefresh(req)) === true;
54
+ }
55
+ catch {
56
+ allowed = false;
57
+ }
58
+ if (!allowed)
59
+ return refuse('You are not allowed to refresh the site cache.', 403, 'forbidden');
60
+ return { id: user.id, collection: user.collection, ...(typeof user.email === 'string' ? { email: user.email } : {}) };
61
+ }
62
+ /** Checks a list from the host before anything is expired, so a bad list refuses the whole refresh. */
63
+ function cleanTags(list) {
64
+ if (!Array.isArray(list))
65
+ throw new Error('The tag list is not a list.');
66
+ const out = new Set();
67
+ for (const t of list) {
68
+ if (typeof t !== 'string' || t.length === 0)
69
+ throw new Error('A tag is empty or not text.');
70
+ if (t.length > MAX_TAG_LENGTH)
71
+ throw new Error(`A tag is longer than ${MAX_TAG_LENGTH} characters, so Next.js would ignore it.`);
72
+ out.add(t);
73
+ }
74
+ return [...out];
75
+ }
76
+ async function resolveTags(req, opts, scope) {
77
+ if (scope === 'changed' && opts.changedTags)
78
+ return cleanTags(await opts.changedTags({ req }));
79
+ return cleanTags(typeof opts.tags === 'function' ? await opts.tags({ req }) : opts.tags);
80
+ }
81
+ async function readBody(req) {
82
+ try {
83
+ const body = typeof req.json === 'function' ? await req.json() : req.data;
84
+ return body && typeof body === 'object' ? body : {};
85
+ }
86
+ catch {
87
+ return {};
88
+ }
89
+ }
90
+ /** The path rule: one leading slash, no backslash, no control characters. Anything else could leave the site. */
91
+ export const isSafePath = (path) => typeof path === 'string' && /^\/(?![/\\])/.test(path) && !path.includes('\\') && !/[\u0000-\u001f\u007f]/.test(path);
92
+ /** Fetches each path once, in order, inside one overall deadline. Never throws. */
93
+ async function warm(req, opts, tags, scope) {
94
+ const result = { attempted: 0, ok: 0, failed: 0, timedOut: 0, skipped: 0, deadlineReached: false };
95
+ if (!opts.warmPaths || !opts.warmBaseUrl)
96
+ return result;
97
+ let origin;
98
+ try {
99
+ origin = new URL(opts.warmBaseUrl).origin;
100
+ }
101
+ catch {
102
+ log(req, 'warn', 'cache-refresh: warmBaseUrl is not a valid address, so nothing was warmed.');
103
+ return result;
104
+ }
105
+ let paths;
106
+ try {
107
+ paths = typeof opts.warmPaths === 'function' ? await opts.warmPaths({ req, tags, scope }) : opts.warmPaths;
108
+ }
109
+ catch (err) {
110
+ log(req, 'warn', `cache-refresh: the warm path list failed: ${describeThrown(err)}`);
111
+ return result;
112
+ }
113
+ const each = opts.warmTimeoutMs ?? 5000;
114
+ const end = Date.now() + (opts.warmDeadlineMs ?? 15000);
115
+ const list = Array.isArray(paths) ? paths : [];
116
+ for (const [i, path] of list.entries()) {
117
+ const left = end - Date.now();
118
+ if (left <= 0) {
119
+ result.deadlineReached = true;
120
+ result.skipped += list.length - i;
121
+ break;
122
+ }
123
+ let url;
124
+ try {
125
+ if (!isSafePath(path))
126
+ throw new Error('not a path');
127
+ url = new URL(path, origin);
128
+ if (url.origin !== origin)
129
+ throw new Error('left the site');
130
+ }
131
+ catch {
132
+ result.failed += 1;
133
+ continue;
134
+ }
135
+ result.attempted += 1;
136
+ try {
137
+ const res = await fetch(url, { signal: AbortSignal.timeout(Math.min(each, left)), redirect: 'manual', headers: { 'User-Agent': 'payload-plugin-cache-refresh' } });
138
+ await res.body?.cancel();
139
+ if (res.ok)
140
+ result.ok += 1;
141
+ else
142
+ result.failed += 1;
143
+ }
144
+ catch (err) {
145
+ if (nameOf(err) === 'TimeoutError' || nameOf(err) === 'AbortError')
146
+ result.timedOut += 1;
147
+ else
148
+ result.failed += 1;
149
+ }
150
+ }
151
+ return result;
152
+ }
153
+ /**
154
+ * CSRF: a cross-site form can send text/plain without a preflight, so the body must say it is JSON, and the
155
+ * browser must say the request came from this site. No evidence either way means no.
156
+ */
157
+ function checkSameSite(req, allowed) {
158
+ const h = req.headers;
159
+ const type = (h?.get?.('content-type') ?? '').split(';')[0].trim().toLowerCase();
160
+ if (type !== 'application/json')
161
+ return refuse('Send the request as application/json.', 415, 'contentType');
162
+ const fetchSite = h?.get?.('sec-fetch-site');
163
+ const origin = h?.get?.('origin');
164
+ if (fetchSite && fetchSite !== 'same-origin')
165
+ return refuse('The request did not come from this site.', 403, 'crossSite');
166
+ if (origin) {
167
+ if (!allowed.includes(origin))
168
+ return refuse('The request did not come from this site.', 403, 'crossSite');
169
+ }
170
+ else if (fetchSite !== 'same-origin') {
171
+ return refuse('The request did not say where it came from.', 403, 'crossSite');
172
+ }
173
+ }
174
+ /** The origin of an http or https address, or null. Any other scheme has an opaque origin, which browsers send as `null`. */
175
+ const webOrigin = (u) => {
176
+ if (typeof u !== 'string' || u.length === 0)
177
+ return null;
178
+ try {
179
+ const url = new URL(u);
180
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
181
+ return null;
182
+ return url.origin === 'null' ? null : url.origin;
183
+ }
184
+ catch {
185
+ return null;
186
+ }
187
+ };
188
+ /**
189
+ * The origins a refresh may come from. A list the host set is the only one that counts, and every entry must be an
190
+ * http or https address. Unset, it is Payload's `serverURL` when that is one, else null (the request's own origin).
191
+ */
192
+ function resolveAllowedOrigins(allowedOrigins, serverURL) {
193
+ if (allowedOrigins === undefined) {
194
+ const own = webOrigin(serverURL);
195
+ return own ? [own] : null;
196
+ }
197
+ const prefix = 'payload-plugin-cache-refresh: `allowedOrigins`';
198
+ if (!Array.isArray(allowedOrigins))
199
+ throw new Error(`${prefix} must be a list of addresses such as https://admin.example.org, or left unset.`);
200
+ if (allowedOrigins.length === 0)
201
+ throw new Error(`${prefix} is empty. List at least one address such as https://admin.example.org, or leave it unset.`);
202
+ const out = new Set();
203
+ for (const [i, entry] of allowedOrigins.entries()) {
204
+ const origin = webOrigin(entry);
205
+ if (!origin)
206
+ throw new Error(`${prefix} entry ${i + 1} is not an http or https address. List addresses such as https://admin.example.org, or leave it unset.`);
207
+ out.add(origin);
208
+ }
209
+ return [...out];
210
+ }
211
+ const NO_WARM = { attempted: 0, ok: 0, failed: 0, timedOut: 0, skipped: 0, deadlineReached: false };
212
+ const profileFor = (mode, profile) => (mode === 'expire' ? { expire: 0 } : (profile ?? 'max'));
213
+ export function makeEndpoints(opts, serverURL) {
214
+ const path = opts.endpointPath ?? DEFAULT_PATH;
215
+ const mode = opts.mode === 'expire' ? 'expire' : 'stale';
216
+ const cooldown = opts.cooldownMs ?? 5000;
217
+ let running = false;
218
+ let lastEnd = 0;
219
+ const configured = resolveAllowedOrigins(opts.allowedOrigins, serverURL);
220
+ /** GET: what the button shows. Same guard as the refresh. */
221
+ const status = {
222
+ path,
223
+ method: 'get',
224
+ handler: async (req) => {
225
+ await guard(req, opts);
226
+ let changedCount = null;
227
+ if (opts.changedTags) {
228
+ try {
229
+ changedCount = cleanTags(await opts.changedTags({ req })).length;
230
+ }
231
+ catch {
232
+ changedCount = null;
233
+ }
234
+ }
235
+ return json({ allowed: true, mode, hasChanged: Boolean(opts.changedTags), changedCount, warms: Boolean(opts.warmPaths && opts.warmBaseUrl) });
236
+ },
237
+ };
238
+ /** POST `{ confirm: true, scope?: 'changed' | 'all' }`: refresh. Without `confirm: true` nothing happens. */
239
+ const refresh = {
240
+ path,
241
+ method: 'post',
242
+ handler: async (req) => {
243
+ const who = await guard(req, opts);
244
+ const own = configured ? null : webOrigin(req.url);
245
+ checkSameSite(req, configured ?? (own ? [own] : []));
246
+ const body = await readBody(req);
247
+ if (body.confirm !== true)
248
+ return refuse('Confirm the refresh first.', 400, 'confirm');
249
+ const scope = body.scope === 'all' || !opts.changedTags ? 'all' : 'changed';
250
+ if (running)
251
+ return refuse('A refresh is already running.', 429, 'busy');
252
+ if (Date.now() - lastEnd < cooldown)
253
+ return refuse('A refresh just finished. Wait a few seconds.', 429, 'cooldown');
254
+ running = true;
255
+ try {
256
+ let tags;
257
+ try {
258
+ tags = await resolveTags(req, opts, scope);
259
+ }
260
+ catch (err) {
261
+ log(req, 'error', `cache-refresh: the tag list failed, nothing was refreshed: ${describeThrown(err)}`);
262
+ return refuse('The list of tags could not be read, so nothing was refreshed.', 500, 'tags');
263
+ }
264
+ // Every tag is tried, so one failure leaves as much of the site fresh as possible. Only the tags that
265
+ // refreshed go to onRefresh, so a host clearing what it recorded clears just those.
266
+ const done = [];
267
+ let failed = 0;
268
+ if (tags.length > 0) {
269
+ let revalidateTag;
270
+ try {
271
+ ;
272
+ ({ revalidateTag } = await import('next/cache.js'));
273
+ }
274
+ catch (err) {
275
+ log(req, 'error', `cache-refresh: next/cache could not be loaded, nothing was refreshed: ${describeThrown(err)}`);
276
+ return refuse('The site cache could not be reached, so nothing was refreshed.', 500, 'revalidate');
277
+ }
278
+ const profile = profileFor(mode, opts.profile);
279
+ for (const tag of tags) {
280
+ try {
281
+ await revalidateTag(tag, profile);
282
+ done.push(tag);
283
+ }
284
+ catch (err) {
285
+ failed += 1;
286
+ log(req, 'error', `cache-refresh: refreshing the tag ${JSON.stringify(tag)} failed: ${describeThrown(err)}`);
287
+ }
288
+ }
289
+ }
290
+ const at = new Date().toISOString();
291
+ let audited = true;
292
+ if (done.length > 0 && opts.onRefresh) {
293
+ try {
294
+ await opts.onRefresh({ who, at, count: done.length, failed, scope, mode, tags: done });
295
+ }
296
+ catch (err) {
297
+ audited = false;
298
+ log(req, 'error', `cache-refresh: onRefresh failed after the refresh: ${describeThrown(err)}`);
299
+ }
300
+ }
301
+ if (failed > 0) {
302
+ // Warming is skipped: a page list can't say which pages belong to the tags that failed.
303
+ const message = done.length > 0 ? `${done.length} of ${tags.length} tags were refreshed and ${failed} failed.` : 'No tags could be refreshed.';
304
+ return json({ refreshed: false, error: message, reason: 'revalidate', count: done.length, failed, scope, mode, at, audited, warmed: { ...NO_WARM } }, 500);
305
+ }
306
+ const warmed = done.length > 0 ? await warm(req, opts, done, scope) : { ...NO_WARM };
307
+ return json({ refreshed: true, count: done.length, failed: 0, scope, mode, at, audited, warmed });
308
+ }
309
+ finally {
310
+ running = false;
311
+ lastEnd = Date.now();
312
+ }
313
+ },
314
+ };
315
+ return [status, refresh];
316
+ }
317
+ export const cacheRefreshPlugin = (opts) => (incoming) => {
318
+ if (typeof opts?.canRefresh !== 'function')
319
+ throw new Error('payload-plugin-cache-refresh: `canRefresh` is required. Nobody may refresh until the host says who.');
320
+ if (!opts.tags)
321
+ throw new Error('payload-plugin-cache-refresh: `tags` is required.');
322
+ const components = incoming.admin?.components;
323
+ return {
324
+ ...incoming,
325
+ endpoints: [...(incoming.endpoints ?? []), ...makeEndpoints(opts, incoming.serverURL)],
326
+ admin: opts.adminButton === false
327
+ ? incoming.admin
328
+ : { ...incoming.admin, components: { ...components, beforeDashboard: [...(components?.beforeDashboard ?? []), BUTTON] } },
329
+ };
330
+ };
331
+ export default cacheRefreshPlugin;
@@ -0,0 +1,92 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ /** What `revalidateTag` takes as its second argument: a cacheLife profile name (`'max'`) or `{ expire }` in seconds. */
3
+ export type TagProfile = string | {
4
+ expire?: number;
5
+ };
6
+ /** A list of tags, or a function that returns one. Called per request, so it can read the database. */
7
+ export type TagSource = string[] | ((args: {
8
+ req: PayloadRequest;
9
+ }) => string[] | Promise<string[]>);
10
+ /** A list of paths, or a function that returns one. Paths start with `/` and are fetched from `warmBaseUrl`. */
11
+ export type PathSource = string[] | ((args: {
12
+ req: PayloadRequest;
13
+ tags: string[];
14
+ scope: Scope;
15
+ }) => string[] | Promise<string[]>);
16
+ /** `changed`: only what `changedTags` returns. `all`: everything `tags` returns. */
17
+ export type Scope = 'changed' | 'all';
18
+ /**
19
+ * `stale` (default): pages keep showing while they rebuild, `revalidateTag(tag, profile)`.
20
+ * `expire`: the next visit waits for a fresh page, `revalidateTag(tag, { expire: 0 })`.
21
+ */
22
+ export type RefreshMode = 'stale' | 'expire';
23
+ export type RefreshWho = {
24
+ id: string | number;
25
+ collection?: string;
26
+ email?: string;
27
+ };
28
+ export type RefreshReport = {
29
+ /** Who pressed the button. */
30
+ who: RefreshWho;
31
+ /** When the refresh ran, as an ISO time. */
32
+ at: string;
33
+ /** How many tags were refreshed. */
34
+ count: number;
35
+ /** How many tags failed to refresh. 0 for a full refresh. The failed tags are not in `tags`. */
36
+ failed: number;
37
+ scope: Scope;
38
+ mode: RefreshMode;
39
+ /** The tags that were refreshed, and only those, so the host can clear what it recorded for `changedTags`. */
40
+ tags: string[];
41
+ };
42
+ export type WarmResult = {
43
+ /** Fetches started. */
44
+ attempted: number;
45
+ ok: number;
46
+ /** Bad status, network error, or a path that was refused. */
47
+ failed: number;
48
+ /** Fetches that hit their time limit. */
49
+ timedOut: number;
50
+ /** Paths never fetched: refused, or left when the deadline passed. */
51
+ skipped: number;
52
+ deadlineReached: boolean;
53
+ };
54
+ export type CacheRefreshOptions = {
55
+ /** Who may refresh. Called with the request after sign-in is checked. Throwing counts as no. Required. */
56
+ canRefresh: (req: PayloadRequest) => boolean | Promise<boolean>;
57
+ /** Every tag that "Everything" refreshes. A list, or a function that returns one. Required. */
58
+ tags: TagSource;
59
+ /** Tags changed since the last refresh (for example, ones scripts recorded). Refreshed by default when given; the admin can pick Everything. */
60
+ changedTags?: (args: {
61
+ req: PayloadRequest;
62
+ }) => string[] | Promise<string[]>;
63
+ /** `stale` (default) or `expire`. */
64
+ mode?: RefreshMode;
65
+ /** The profile for `stale` mode. Default `'max'`. Ignored in `expire` mode. */
66
+ profile?: TagProfile;
67
+ /** Pages to fetch once after a refresh, to rebuild them before a visitor does. Best effort. */
68
+ warmPaths?: PathSource;
69
+ /** The site's address for warming, such as `https://example.org`. Warming is skipped without it. */
70
+ warmBaseUrl?: string;
71
+ /** Time allowed for each warming fetch, in milliseconds. Default 5000. */
72
+ warmTimeoutMs?: number;
73
+ /** Total time allowed for all warming, in milliseconds. Paths left when it passes are skipped. Default 15000. */
74
+ warmDeadlineMs?: number;
75
+ /** Minimum time between refreshes, in milliseconds. A second press during a refresh or this wait gets 429. Default 5000. */
76
+ cooldownMs?: number;
77
+ /**
78
+ * Origins a refresh may come from, such as `https://admin.example.org`, checked when the browser sends `Origin`. When set, only this list is used: it must hold
79
+ * at least one entry and every entry must be an http or https address, or the plugin refuses to start.
80
+ * Unset: Payload's `serverURL`, else the request's own origin.
81
+ */
82
+ allowedOrigins?: string[];
83
+ /**
84
+ * Called after a refresh with who, when, how many and which tags. After a partial failure it gets only the tags
85
+ * that refreshed. It isn't called when no tag refreshed. A failure here is logged and reported, and never undoes the refresh.
86
+ */
87
+ onRefresh?: (report: RefreshReport) => void | Promise<void>;
88
+ /** The endpoint's path under Payload's API route. Default `/cache-refresh`. */
89
+ endpointPath?: string;
90
+ /** Put the button on the dashboard. Default true. Set false to place `CacheRefreshButton` yourself. */
91
+ adminButton?: boolean;
92
+ };
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,74 @@
1
1
  {
2
2
  "name": "@extantape/payload-plugin-cache-refresh",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Cache refresh for Payload: an admin button that refreshes the host's Next.js cache tags for the people the host allows, with a confirmation step, stale-while-revalidate by default, a targeted or full refresh, optional page warming and an audit hook.",
5
+ "keywords": [
6
+ "payload",
7
+ "payload-plugin",
8
+ "payloadcms",
9
+ "nextjs",
10
+ "cache",
11
+ "revalidate",
12
+ "revalidatetag",
13
+ "stale-while-revalidate",
14
+ "admin"
15
+ ],
16
+ "license": "MIT",
17
+ "homepage": "https://github.com/ExtantApe/payload-plugin-cache-refresh#readme",
18
+ "bugs": {
19
+ "url": "https://github.com/ExtantApe/payload-plugin-cache-refresh/issues"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/ExtantApe/payload-plugin-cache-refresh.git"
24
+ },
25
+ "type": "module",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "import": "./dist/index.js"
30
+ },
31
+ "./client": {
32
+ "types": "./dist/client/index.d.ts",
33
+ "import": "./dist/client/index.js"
34
+ }
35
+ },
36
+ "main": "./dist/index.js",
37
+ "types": "./dist/index.d.ts",
38
+ "files": [
39
+ "dist",
40
+ "README.md",
41
+ "LICENSE"
42
+ ],
43
+ "engines": {
44
+ "node": ">=22"
45
+ },
46
+ "scripts": {
47
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
48
+ "typecheck": "tsc --noEmit",
49
+ "test": "vitest run",
50
+ "prepack": "npm run build",
51
+ "prepublishOnly": "npm run typecheck && npm test"
52
+ },
53
+ "peerDependencies": {
54
+ "next": ">=16.0.0",
55
+ "payload": "^3.80.0",
56
+ "react": "^19.0.0"
57
+ },
58
+ "peerDependenciesMeta": {
59
+ "react": {
60
+ "optional": true
61
+ }
62
+ },
63
+ "devDependencies": {
64
+ "@types/node": "^24.0.0",
65
+ "@types/react": "^19.3.0",
66
+ "graphql": "^16.14.2",
67
+ "next": "16.4.4",
68
+ "payload": "3.92.1",
69
+ "react": "^19.3.1",
70
+ "react-dom": "^19.3.1",
71
+ "typescript": "^5.9.0",
72
+ "vitest": "^5.1.0"
73
+ }
74
+ }