@extantape/payload-plugin-cache-refresh 0.0.0-stage → 0.1.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,80 @@
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.1.0, not published. The endpoint is covered by 61 unit tests with `next/cache.js` mocked: who may refresh, the same-site check, the lock and cooldown, the confirmation step, a failing tag list, the audit hook, stale or expire, changed tags or everything, and warming. 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. The allowed origins are `allowedOrigins`, else Payload's `serverURL`, else the origin of the request URL. Set one of the first two if a proxy changes the request URL.
20
+
21
+ A second press while a refresh runs, or within `cooldownMs` after one, gets 429.
22
+
23
+ If the tag list can't be read (a function throws, or a tag is empty or longer than 256 characters), nothing is refreshed.
24
+
25
+ ## Install
26
+
27
+ ```sh
28
+ npm install @extantape/payload-plugin-cache-refresh
29
+ ```
30
+
31
+ Needs Payload 3.80 or later and Next.js 16 or later, which has the two-argument `revalidateTag`.
32
+
33
+ ```ts
34
+ import { cacheRefreshPlugin } from '@extantape/payload-plugin-cache-refresh'
35
+
36
+ export default buildConfig({
37
+ plugins: [
38
+ cacheRefreshPlugin({
39
+ canRefresh: (req) => req.user?.role === 'admin',
40
+ tags: ['pages', 'posts', 'menu'],
41
+ }),
42
+ ],
43
+ })
44
+ ```
45
+
46
+ Regenerate Payload's import map after adding it, so the button is found.
47
+
48
+ ## Options
49
+
50
+ | Option | What it does |
51
+ | --- | --- |
52
+ | `canRefresh(req)` | Required. Returns true for users who may refresh. |
53
+ | `tags` | Required. A list, or an async function returning one. What Everything refreshes. |
54
+ | `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. |
55
+ | `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. |
56
+ | `profile` | The profile for stale mode. Default `'max'`. |
57
+ | `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. |
58
+ | `warmBaseUrl` | The site's address, such as `https://example.org`. Warming is off without it. |
59
+ | `warmTimeoutMs` | Time for each warming fetch. Default 5000. |
60
+ | `warmDeadlineMs` | Total time for all warming. Pages left when it passes are skipped and reported. Default 15000. |
61
+ | `cooldownMs` | Time after a refresh before the next is accepted. Default 5000. |
62
+ | `allowedOrigins` | Origins a refresh may come from. Default Payload's `serverURL`, else the request's origin. |
63
+ | `onRefresh(report)` | Gets `who` (id, collection, email), `at`, `count`, `scope`, `mode` and `tags`. If it throws, the refresh stays and the response says `audited: false`. It isn't called when zero tags were refreshed. |
64
+ | `endpointPath` | Default `/cache-refresh`. |
65
+ | `adminButton` | Default true. Set false and import `CacheRefreshButton` from `@extantape/payload-plugin-cache-refresh/client` to place it yourself. |
66
+
67
+ The plugin never clears your recorded changed tags. Do that in `onRefresh`, which receives the tags it refreshed.
68
+
69
+ The button's words can be replaced with the `text` prop, and its colors with `--cache-refresh-ink`, `--cache-refresh-paper`, `--cache-refresh-line` and `--cache-refresh-focus`.
70
+
71
+ ## Limits
72
+
73
+ - 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.
74
+ - Expiry is not undone if a later step fails. The tag list is checked first for that reason.
75
+ - The lock and cooldown live in one server process. Several instances each keep their own.
76
+ - It refreshes the cache of the Next.js process serving the request. Other servers or a CDN in front need their own handling.
77
+
78
+ ## License
79
+
80
+ MIT. Copyright (c) 2026 EXTANT APE.
@@ -0,0 +1,29 @@
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
+ failed: string;
19
+ };
20
+ export declare const defaultText: CacheRefreshText;
21
+ /**
22
+ * The dashboard button. Renders nothing for anyone the host does not allow. Pressing it opens a confirmation
23
+ * panel; nothing is refreshed until "Refresh now". Escape or Cancel closes the panel and returns focus.
24
+ */
25
+ export declare function CacheRefreshButton({ apiRoute, endpointPath, text }: {
26
+ apiRoute?: string;
27
+ endpointPath?: string;
28
+ text?: Partial<CacheRefreshText>;
29
+ }): import("react").JSX.Element | null;
@@ -0,0 +1,107 @@
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
+ failed: 'The refresh did not happen. Nothing was changed.',
22
+ };
23
+ const v = (name, fallback) => `var(--cache-refresh-${name}, ${fallback})`;
24
+ const ink = v('ink', 'currentColor');
25
+ const paper = v('paper', 'var(--theme-elevation-0, Canvas)');
26
+ const line = v('line', 'color-mix(in srgb, currentColor 45%, transparent)');
27
+ const focus = v('focus', '#b85c00');
28
+ const s = {
29
+ wrap: { font: 'inherit', color: ink, margin: '0 0 1.5rem' },
30
+ button: { font: 'inherit', color: ink, background: paper, border: `1px solid ${line}`, borderRadius: 6, minHeight: 36, padding: '6px 14px', cursor: 'pointer' },
31
+ panel: { marginTop: 8, maxWidth: 440, background: paper, color: ink, border: `1px solid ${line}`, borderRadius: 8, padding: 14 },
32
+ fieldset: { border: 0, margin: '8px 0', padding: 0 },
33
+ row: { display: 'flex', gap: 8, alignItems: 'center', minHeight: 32 },
34
+ actions: { display: 'flex', gap: 8, marginTop: 12 },
35
+ note: { margin: '8px 0 0' },
36
+ };
37
+ const css = `.cache-refresh :focus-visible{outline:3px solid ${focus};outline-offset:2px}.cache-refresh button:disabled{cursor:progress;opacity:.7}`;
38
+ /**
39
+ * The dashboard button. Renders nothing for anyone the host does not allow. Pressing it opens a confirmation
40
+ * panel; nothing is refreshed until "Refresh now". Escape or Cancel closes the panel and returns focus.
41
+ */
42
+ export function CacheRefreshButton({ apiRoute = '/api', endpointPath = '/cache-refresh', text }) {
43
+ const t = { ...defaultText, ...text };
44
+ const url = `${apiRoute}${endpointPath}`;
45
+ const [status, setStatus] = useState(null);
46
+ const [open, setOpen] = useState(false);
47
+ const [scope, setScope] = useState('changed');
48
+ const [busy, setBusy] = useState(false);
49
+ const [message, setMessage] = useState('');
50
+ const trigger = useRef(null);
51
+ const heading = useRef(null);
52
+ const id = useId();
53
+ useEffect(() => {
54
+ let live = true;
55
+ fetch(url, { credentials: 'include' })
56
+ .then((r) => (r.ok ? r.json() : null))
57
+ .then((s2) => live && setStatus(s2))
58
+ .catch(() => live && setStatus(null));
59
+ return () => {
60
+ live = false;
61
+ };
62
+ }, [url]);
63
+ useEffect(() => {
64
+ if (open)
65
+ heading.current?.focus();
66
+ }, [open]);
67
+ const close = useCallback(() => {
68
+ setOpen(false);
69
+ trigger.current?.focus();
70
+ }, []);
71
+ const run = async () => {
72
+ setBusy(true);
73
+ setMessage(t.working);
74
+ try {
75
+ const res = await fetch(url, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ confirm: true, scope: status?.hasChanged ? scope : 'all' }) });
76
+ if (res.status === 429) {
77
+ setMessage(t.busy);
78
+ return;
79
+ }
80
+ if (!res.ok)
81
+ throw new Error('refused');
82
+ const out = (await res.json());
83
+ const parts = [out.count === 0 ? t.nothing : t.done(out.count)];
84
+ const w = out.warmed;
85
+ if (w && w.failed > 0)
86
+ parts.push(t.warmFailed(w.failed));
87
+ if (w?.timedOut)
88
+ parts.push(t.warmTimedOut(w.timedOut));
89
+ if (w?.skipped)
90
+ parts.push(t.warmSkipped(w.skipped));
91
+ if (out.audited === false)
92
+ parts.push(t.notAudited);
93
+ setMessage(parts.join(' '));
94
+ setOpen(false);
95
+ trigger.current?.focus();
96
+ }
97
+ catch {
98
+ setMessage(t.failed);
99
+ }
100
+ finally {
101
+ setBusy(false);
102
+ }
103
+ };
104
+ if (!status?.allowed)
105
+ return null;
106
+ 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 })] }));
107
+ }
@@ -0,0 +1 @@
1
+ export { CacheRefreshButton, defaultText, type CacheRefreshText } from './CacheRefreshButton.js';
@@ -0,0 +1,2 @@
1
+ 'use client';
2
+ export { CacheRefreshButton, defaultText } 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,242 @@
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
+ /** Sign-in first (401), then the host's rule (403). A rule that throws is a no. */
14
+ async function guard(req, opts) {
15
+ const user = req.user;
16
+ if (!user)
17
+ return refuse('Sign in first.', 401, 'signIn');
18
+ let allowed = false;
19
+ try {
20
+ allowed = (await opts.canRefresh(req)) === true;
21
+ }
22
+ catch {
23
+ allowed = false;
24
+ }
25
+ if (!allowed)
26
+ return refuse('You are not allowed to refresh the site cache.', 403, 'forbidden');
27
+ return { id: user.id, collection: user.collection, ...(typeof user.email === 'string' ? { email: user.email } : {}) };
28
+ }
29
+ /** Checks a list from the host before anything is expired, so a bad list refuses the whole refresh. */
30
+ function cleanTags(list) {
31
+ if (!Array.isArray(list))
32
+ throw new Error('The tag list is not a list.');
33
+ const out = new Set();
34
+ for (const t of list) {
35
+ if (typeof t !== 'string' || t.length === 0)
36
+ throw new Error('A tag is empty or not text.');
37
+ if (t.length > MAX_TAG_LENGTH)
38
+ throw new Error(`A tag is longer than ${MAX_TAG_LENGTH} characters, so Next.js would ignore it.`);
39
+ out.add(t);
40
+ }
41
+ return [...out];
42
+ }
43
+ async function resolveTags(req, opts, scope) {
44
+ if (scope === 'changed' && opts.changedTags)
45
+ return cleanTags(await opts.changedTags({ req }));
46
+ return cleanTags(typeof opts.tags === 'function' ? await opts.tags({ req }) : opts.tags);
47
+ }
48
+ async function readBody(req) {
49
+ try {
50
+ const body = typeof req.json === 'function' ? await req.json() : req.data;
51
+ return body && typeof body === 'object' ? body : {};
52
+ }
53
+ catch {
54
+ return {};
55
+ }
56
+ }
57
+ /** The path rule: one leading slash, no backslash, no control characters. Anything else could leave the site. */
58
+ export const isSafePath = (path) => typeof path === 'string' && /^\/(?![/\\])/.test(path) && !path.includes('\\') && !/[\u0000-\u001f\u007f]/.test(path);
59
+ /** Fetches each path once, in order, inside one overall deadline. Never throws. */
60
+ async function warm(req, opts, tags, scope) {
61
+ const result = { attempted: 0, ok: 0, failed: 0, timedOut: 0, skipped: 0, deadlineReached: false };
62
+ if (!opts.warmPaths || !opts.warmBaseUrl)
63
+ return result;
64
+ let origin;
65
+ try {
66
+ origin = new URL(opts.warmBaseUrl).origin;
67
+ }
68
+ catch {
69
+ req.payload?.logger?.warn?.('cache-refresh: warmBaseUrl is not a valid address, so nothing was warmed.');
70
+ return result;
71
+ }
72
+ let paths;
73
+ try {
74
+ paths = typeof opts.warmPaths === 'function' ? await opts.warmPaths({ req, tags, scope }) : opts.warmPaths;
75
+ }
76
+ catch (err) {
77
+ req.payload?.logger?.warn?.(`cache-refresh: the warm path list failed: ${err.message}`);
78
+ return result;
79
+ }
80
+ const each = opts.warmTimeoutMs ?? 5000;
81
+ const end = Date.now() + (opts.warmDeadlineMs ?? 15000);
82
+ const list = Array.isArray(paths) ? paths : [];
83
+ for (const [i, path] of list.entries()) {
84
+ const left = end - Date.now();
85
+ if (left <= 0) {
86
+ result.deadlineReached = true;
87
+ result.skipped += list.length - i;
88
+ break;
89
+ }
90
+ let url;
91
+ try {
92
+ if (!isSafePath(path))
93
+ throw new Error('not a path');
94
+ url = new URL(path, origin);
95
+ if (url.origin !== origin)
96
+ throw new Error('left the site');
97
+ }
98
+ catch {
99
+ result.failed += 1;
100
+ continue;
101
+ }
102
+ result.attempted += 1;
103
+ try {
104
+ const res = await fetch(url, { signal: AbortSignal.timeout(Math.min(each, left)), redirect: 'manual', headers: { 'User-Agent': 'payload-plugin-cache-refresh' } });
105
+ await res.body?.cancel();
106
+ if (res.ok)
107
+ result.ok += 1;
108
+ else
109
+ result.failed += 1;
110
+ }
111
+ catch (err) {
112
+ if (err?.name === 'TimeoutError' || err?.name === 'AbortError')
113
+ result.timedOut += 1;
114
+ else
115
+ result.failed += 1;
116
+ }
117
+ }
118
+ return result;
119
+ }
120
+ /**
121
+ * CSRF: a cross-site form can send text/plain without a preflight, so the body must say it is JSON, and the
122
+ * browser must say the request came from this site. No evidence either way means no.
123
+ */
124
+ function checkSameSite(req, allowed) {
125
+ const h = req.headers;
126
+ const type = (h?.get?.('content-type') ?? '').split(';')[0].trim().toLowerCase();
127
+ if (type !== 'application/json')
128
+ return refuse('Send the request as application/json.', 415, 'contentType');
129
+ const fetchSite = h?.get?.('sec-fetch-site');
130
+ const origin = h?.get?.('origin');
131
+ if (fetchSite && fetchSite !== 'same-origin')
132
+ return refuse('The request did not come from this site.', 403, 'crossSite');
133
+ if (origin) {
134
+ if (!allowed.includes(origin))
135
+ return refuse('The request did not come from this site.', 403, 'crossSite');
136
+ }
137
+ else if (fetchSite !== 'same-origin') {
138
+ return refuse('The request did not say where it came from.', 403, 'crossSite');
139
+ }
140
+ }
141
+ const originOf = (u) => {
142
+ try {
143
+ return u ? new URL(u).origin : null;
144
+ }
145
+ catch {
146
+ return null;
147
+ }
148
+ };
149
+ const profileFor = (mode, profile) => (mode === 'expire' ? { expire: 0 } : (profile ?? 'max'));
150
+ export function makeEndpoints(opts, serverURL) {
151
+ const path = opts.endpointPath ?? DEFAULT_PATH;
152
+ const mode = opts.mode === 'expire' ? 'expire' : 'stale';
153
+ const cooldown = opts.cooldownMs ?? 5000;
154
+ let running = false;
155
+ let lastEnd = 0;
156
+ const configured = (opts.allowedOrigins ?? [serverURL]).map(originOf).filter((o) => Boolean(o));
157
+ /** GET: what the button shows. Same guard as the refresh. */
158
+ const status = {
159
+ path,
160
+ method: 'get',
161
+ handler: async (req) => {
162
+ await guard(req, opts);
163
+ let changedCount = null;
164
+ if (opts.changedTags) {
165
+ try {
166
+ changedCount = cleanTags(await opts.changedTags({ req })).length;
167
+ }
168
+ catch {
169
+ changedCount = null;
170
+ }
171
+ }
172
+ return json({ allowed: true, mode, hasChanged: Boolean(opts.changedTags), changedCount, warms: Boolean(opts.warmPaths && opts.warmBaseUrl) });
173
+ },
174
+ };
175
+ /** POST `{ confirm: true, scope?: 'changed' | 'all' }`: refresh. Without `confirm: true` nothing happens. */
176
+ const refresh = {
177
+ path,
178
+ method: 'post',
179
+ handler: async (req) => {
180
+ const who = await guard(req, opts);
181
+ checkSameSite(req, configured.length > 0 ? configured : [originOf(req.url)].filter((o) => Boolean(o)));
182
+ const body = await readBody(req);
183
+ if (body.confirm !== true)
184
+ return refuse('Confirm the refresh first.', 400, 'confirm');
185
+ const scope = body.scope === 'all' || !opts.changedTags ? 'all' : 'changed';
186
+ if (running)
187
+ return refuse('A refresh is already running.', 429, 'busy');
188
+ if (Date.now() - lastEnd < cooldown)
189
+ return refuse('A refresh just finished. Wait a few seconds.', 429, 'cooldown');
190
+ running = true;
191
+ try {
192
+ let tags;
193
+ try {
194
+ tags = await resolveTags(req, opts, scope);
195
+ }
196
+ catch (err) {
197
+ req.payload?.logger?.error?.(`cache-refresh: the tag list failed, nothing was refreshed: ${err.message}`);
198
+ return refuse('The list of tags could not be read, so nothing was refreshed.', 500, 'tags');
199
+ }
200
+ if (tags.length > 0) {
201
+ const { revalidateTag } = await import('next/cache.js');
202
+ const profile = profileFor(mode, opts.profile);
203
+ for (const tag of tags)
204
+ revalidateTag(tag, profile);
205
+ }
206
+ const at = new Date().toISOString();
207
+ let audited = true;
208
+ if (tags.length > 0 && opts.onRefresh) {
209
+ try {
210
+ await opts.onRefresh({ who, at, count: tags.length, scope, mode, tags });
211
+ }
212
+ catch (err) {
213
+ audited = false;
214
+ req.payload?.logger?.error?.(`cache-refresh: onRefresh failed after the refresh: ${err.message}`);
215
+ }
216
+ }
217
+ const warmed = tags.length > 0 ? await warm(req, opts, tags, scope) : { attempted: 0, ok: 0, failed: 0, timedOut: 0, skipped: 0, deadlineReached: false };
218
+ return json({ refreshed: true, count: tags.length, scope, mode, at, audited, warmed });
219
+ }
220
+ finally {
221
+ running = false;
222
+ lastEnd = Date.now();
223
+ }
224
+ },
225
+ };
226
+ return [status, refresh];
227
+ }
228
+ export const cacheRefreshPlugin = (opts) => (incoming) => {
229
+ if (typeof opts?.canRefresh !== 'function')
230
+ throw new Error('payload-plugin-cache-refresh: `canRefresh` is required. Nobody may refresh until the host says who.');
231
+ if (!opts.tags)
232
+ throw new Error('payload-plugin-cache-refresh: `tags` is required.');
233
+ const components = incoming.admin?.components;
234
+ return {
235
+ ...incoming,
236
+ endpoints: [...(incoming.endpoints ?? []), ...makeEndpoints(opts, incoming.serverURL)],
237
+ admin: opts.adminButton === false
238
+ ? incoming.admin
239
+ : { ...incoming.admin, components: { ...components, beforeDashboard: [...(components?.beforeDashboard ?? []), BUTTON] } },
240
+ };
241
+ };
242
+ export default cacheRefreshPlugin;
@@ -0,0 +1,83 @@
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
+ scope: Scope;
36
+ mode: RefreshMode;
37
+ /** The tags themselves, so the host can clear what it recorded for `changedTags`. */
38
+ tags: string[];
39
+ };
40
+ export type WarmResult = {
41
+ /** Fetches started. */
42
+ attempted: number;
43
+ ok: number;
44
+ /** Bad status, network error, or a path that was refused. */
45
+ failed: number;
46
+ /** Fetches that hit their time limit. */
47
+ timedOut: number;
48
+ /** Paths never fetched: refused, or left when the deadline passed. */
49
+ skipped: number;
50
+ deadlineReached: boolean;
51
+ };
52
+ export type CacheRefreshOptions = {
53
+ /** Who may refresh. Called with the request after sign-in is checked. Throwing counts as no. Required. */
54
+ canRefresh: (req: PayloadRequest) => boolean | Promise<boolean>;
55
+ /** Every tag that "Everything" refreshes. A list, or a function that returns one. Required. */
56
+ tags: TagSource;
57
+ /** Tags changed since the last refresh (for example, ones scripts recorded). Refreshed by default when given; the admin can pick Everything. */
58
+ changedTags?: (args: {
59
+ req: PayloadRequest;
60
+ }) => string[] | Promise<string[]>;
61
+ /** `stale` (default) or `expire`. */
62
+ mode?: RefreshMode;
63
+ /** The profile for `stale` mode. Default `'max'`. Ignored in `expire` mode. */
64
+ profile?: TagProfile;
65
+ /** Pages to fetch once after a refresh, to rebuild them before a visitor does. Best effort. */
66
+ warmPaths?: PathSource;
67
+ /** The site's address for warming, such as `https://example.org`. Warming is skipped without it. */
68
+ warmBaseUrl?: string;
69
+ /** Time allowed for each warming fetch, in milliseconds. Default 5000. */
70
+ warmTimeoutMs?: number;
71
+ /** Total time allowed for all warming, in milliseconds. Paths left when it passes are skipped. Default 15000. */
72
+ warmDeadlineMs?: number;
73
+ /** Minimum time between refreshes, in milliseconds. A second press during a refresh or this wait gets 429. Default 5000. */
74
+ cooldownMs?: number;
75
+ /** Origins a refresh may come from, such as `https://admin.example.org`. Default: Payload's `serverURL`, else the request's own origin. */
76
+ allowedOrigins?: string[];
77
+ /** Called after a refresh with who, when and how many. A failure here is logged and reported, and never undoes the refresh. */
78
+ onRefresh?: (report: RefreshReport) => void | Promise<void>;
79
+ /** The endpoint's path under Payload's API route. Default `/cache-refresh`. */
80
+ endpointPath?: string;
81
+ /** Put the button on the dashboard. Default true. Set false to place `CacheRefreshButton` yourself. */
82
+ adminButton?: boolean;
83
+ };
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.1.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
+ }