@extantape/payload-plugin-docs 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 Captive Origins
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,88 @@
1
- # Temporary Holding Version
1
+ # payload-plugin-docs
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
+ Docs for Payload: a docs page for every feature your site lists, made and kept up to date by hook, with hand-written pages beside them, a publish-time lint for internals, and a check that nothing is missing.
4
+
5
+ **Status:** 0.1.0, not on npm yet. 21 tests pass against Payload 3.92 with an in-memory MongoDB replica set and a fake generator (no AI is called). They cover pages following features, the lint, reviews, publishing rules, public access, the check and the tree. No site uses it yet.
6
+
7
+ ## What it does
8
+
9
+ - **Sources that fail or come back empty** leave their pages alone, and the check reports them. A failed draft is tried again at the next sync.
10
+ - **A page for every feature.** Features come from one or more sources: a few lines each, from a roadmap plugin's catalog or your own list.
11
+ - A source calls `onFeatureChange` from its own hook. `syncDocs(payload)`, nightly, reads every source and catches anything a hook missed.
12
+ - A new feature gets a draft page.
13
+ - When a feature's words change, its page is marked out of date. A fresh draft waits beside the published words until it's reviewed and published.
14
+ - A removed feature's page is archived, never deleted. Nobody can delete a page.
15
+ - A planned feature gets a short page that starts "**Planned.** This is what we intend to build. There's nothing to use yet."
16
+ - **Drafts come from your generator** (`generate`), given the feature's own fields and, if you give `uiTextFor`, the user-facing text of its pages.
17
+ - Docs never reads source code, config or the schema, and never calls an AI itself.
18
+ - If the generator fails, the page is still made and marked out of date.
19
+ - Without a generator, the feature's summary and details are used.
20
+ - **Hand-written pages** (`kind: 'extra'`) sit in the same sections.
21
+ - **Nothing internal goes public.** Publishing is refused if a page's title, summary or body has any of these:
22
+ - environment variable names or file paths;
23
+ - IP addresses or internal hosts;
24
+ - key-like strings;
25
+ - your collection names written like code;
26
+ - your private terms.
27
+
28
+ `allow` lets public names through (YouTube, Stripe).
29
+ - **Reviews:**
30
+ - Only reviewers (`access.review`) review, and a page is approved only when the reviewer ticks `approved`. A note alone approves nothing.
31
+ - An approval holds only for the words it saw: the section, path, title, summary and body. Editing any of them clears it.
32
+ - Publishing an approved page clears its out-of-date flag.
33
+ - A page can't be published unreviewed, so editing a published page's words means a draft and a new review.
34
+ - **`checkDocs(payload)`**, for a nightly job and your pre-release step, lists:
35
+ - features with no page;
36
+ - out-of-date pages;
37
+ - features whose page isn't published, planned ones included, so /docs always holds at least everything in Features;
38
+ - two pages for one feature, or two pages on one path;
39
+ - a source that failed, or returned nothing while it has pages;
40
+ - `/docs` links that go nowhere;
41
+ - lint hits on published pages.
42
+
43
+ - **Reading:**
44
+ - `docsTree(payload)` gives the published sections and pages, for your `/docs` routes.
45
+ - `docsPage(payload, '/docs/section/slug')` gives one page.
46
+ - The public sees only published pages that aren't archived, without review details or the plugin's own fields. Drafts and old versions are for editors (`access.edit`) only.
47
+ - **Bodies are Markdown**, so your site renders them its own way.
48
+
49
+ ## Install
50
+
51
+ ```sh
52
+ npm install @extantape/payload-plugin-docs
53
+ ```
54
+
55
+ ```ts
56
+ import { docsPlugin, onFeatureChange } from '@extantape/payload-plugin-docs'
57
+
58
+ docsPlugin({
59
+ sources: [{ name: 'catalog', list: async ({ payload }) => myFeatures(payload) }],
60
+ generate: async ({ feature, uiText }) => myModelCall(feature, uiText), // { summary, body } in Markdown
61
+ access: { edit: isEditor, review: isReviewer }, // both required
62
+ privateTerms: myPrivateTerms,
63
+ allow: ['YouTube', 'Stripe'],
64
+ })
65
+
66
+ // In your feature source's own hook:
67
+ await onFeatureChange(payload, { source: 'catalog', feature, req }) // or { source, removedId, req }
68
+ ```
69
+
70
+ Run `syncDocs` and `checkDocs` nightly. Another plugin can be a feature source with no import: it adds `{ name, list }` to `config.custom.docsSources` (in any plugin order) and calls `payload.config.custom.docs?.onFeatureChange` from its own hook when that's there.
71
+
72
+ ## Limits
73
+
74
+ - The lint is a pattern check, not an understanding. It catches the common ways internals leak. A person still reviews every page before it's published.
75
+ - Collection names are refused when they look like code (with a hyphen or underscore, mixed case, or in backticks), so ordinary words that happen to be a collection's name don't trip it.
76
+ - MongoDB only for now.
77
+
78
+ ## Commands
79
+
80
+ ```sh
81
+ npm test # integration tests, in-memory MongoDB
82
+ npm run typecheck
83
+ npm run build
84
+ ```
85
+
86
+ ## License
87
+
88
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,5 @@
1
+ import type { CollectionConfig } from 'payload';
2
+ import type { Resolved } from './types.js';
3
+ /** Everything a reader sees on a page, for the review hash and the lint: section, path, title, summary and body. */
4
+ export declare const pageText: (p: Record<string, any>) => string;
5
+ export declare const docsCollection: (o: Resolved) => CollectionConfig;
@@ -0,0 +1,86 @@
1
+ import { lint, textOf } from './lint.js';
2
+ import { bodyHash, DocsError } from './util.js';
3
+ const yes = async (a, args) => (await a(args)) === true;
4
+ /** Everything a reader sees on a page, for the review hash and the lint: section, path, title, summary and body. */
5
+ export const pageText = (p) => [p.section, p.sectionKey, p.slug, p.title, p.summary, textOf(p.body)].map((v) => String(v ?? '')).join('\n'); // eslint-disable-line @typescript-eslint/no-explicit-any
6
+ const EMPTY = { approved: false, by: null, at: null, notes: null, hash: null };
7
+ /**
8
+ * Before a page is saved:
9
+ * - only reviewers change the review, and a review approves only when `approved` is true;
10
+ * - an approval holds only for the words it saw: changing any of them clears it;
11
+ * - a published page must be approved for its words, as they are now, and pass the lint;
12
+ * - publishing an approved page clears its out-of-date flag.
13
+ */
14
+ const beforeChange = (o) => async ({ data, originalDoc, req }) => {
15
+ const next = { ...originalDoc, ...data };
16
+ const hash = bodyHash(pageText(next));
17
+ const reviewChanged = data.review !== undefined && JSON.stringify(data.review ?? null) !== JSON.stringify(originalDoc?.review ?? null);
18
+ if (reviewChanged && !(await yes(o.review, { req, data })))
19
+ throw new DocsError('notReviewer', 'Only a reviewer can review a page.', 403);
20
+ if (reviewChanged && data.review) {
21
+ // The hash is the plugin's, never the caller's: an approval is stamped with the words it approves.
22
+ data.review = data.review.approved === true ? { ...data.review, hash, at: new Date().toISOString() } : { ...data.review, approved: false, hash: null };
23
+ }
24
+ else if (next.review?.hash && next.review.hash !== hash)
25
+ data.review = EMPTY;
26
+ if (next._status === 'published') {
27
+ const hits = lint(o, pageText(next));
28
+ if (hits.length)
29
+ throw new DocsError('lint', `This page mentions something internal (${[...new Set(hits.map((h) => h.kind))].join(', ')}). Rewrite it before publishing.`);
30
+ const review = data.review === undefined ? originalDoc?.review : data.review;
31
+ if (review?.approved !== true || !review.hash || review.hash !== hash)
32
+ throw new DocsError('unreviewed', 'A page has to be approved by a reviewer, as it is now, before it’s published.');
33
+ data.outOfDate = false;
34
+ }
35
+ return data;
36
+ };
37
+ export const docsCollection = (o) => {
38
+ const editor = async (args) => yes(o.edit, args);
39
+ const editorField = { read: async (args) => yes(o.edit, args) };
40
+ return {
41
+ slug: o.slug,
42
+ labels: { singular: 'Docs page', plural: 'Docs pages' },
43
+ admin: { group: o.adminGroup, useAsTitle: 'title', defaultColumns: ['title', 'section', 'kind', 'outOfDate', '_status'] },
44
+ versions: { drafts: true, maxPerDoc: 20 },
45
+ access: {
46
+ // The public sees published pages that aren't archived; editors see everything.
47
+ read: async (args) => ((await yes(o.edit, args)) ? true : { and: [{ _status: { equals: 'published' } }, { archived: { not_equals: true } }] }),
48
+ create: editor,
49
+ update: editor,
50
+ // Pages are archived, never deleted, so /docs never loses a feature's page by accident.
51
+ delete: () => false,
52
+ // Drafts and old versions are for editors: unreviewed words never reach anyone else.
53
+ readVersions: editor,
54
+ },
55
+ hooks: { beforeChange: [beforeChange(o)] },
56
+ indexes: [{ fields: ['source', 'featureId'] }],
57
+ fields: [
58
+ { name: 'kind', type: 'select', options: ['feature', 'extra'], required: true, defaultValue: 'extra' },
59
+ { name: 'source', type: 'text', admin: { readOnly: true }, access: editorField },
60
+ { name: 'featureId', type: 'text', admin: { readOnly: true }, access: editorField },
61
+ { name: 'sectionKey', type: 'text', required: true, index: true },
62
+ { name: 'section', type: 'text', required: true },
63
+ { name: 'slug', type: 'text', required: true, index: true },
64
+ { name: 'title', type: 'text', required: true },
65
+ { name: 'summary', type: 'textarea' },
66
+ { name: 'body', type: 'textarea', admin: { description: 'Markdown.' } },
67
+ { name: 'stage', type: 'select', options: ['available', 'members', 'in-progress', 'planned'] },
68
+ { name: 'order', type: 'number' },
69
+ { name: 'generatedFrom', type: 'text', admin: { readOnly: true, description: 'The feature version this page was written from.' }, access: editorField },
70
+ { name: 'outOfDate', type: 'checkbox', admin: { readOnly: true }, access: editorField },
71
+ { name: 'archived', type: 'checkbox', admin: { readOnly: true } },
72
+ {
73
+ name: 'review',
74
+ type: 'group',
75
+ access: editorField,
76
+ fields: [
77
+ { name: 'approved', type: 'checkbox', admin: { description: 'Tick to approve these words. A note alone doesn’t approve.' } },
78
+ { name: 'by', type: 'text' },
79
+ { name: 'at', type: 'date' },
80
+ { name: 'notes', type: 'textarea' },
81
+ { name: 'hash', type: 'text', admin: { readOnly: true } },
82
+ ],
83
+ },
84
+ ],
85
+ };
86
+ };
@@ -0,0 +1,5 @@
1
+ export { docsPlugin } from './plugin.js';
2
+ export { checkDocs, docsPage, docsTree, onFeatureChange, sourcesOf, syncDocs, type DocsProblem } from './sync.js';
3
+ export { lint, textOf, type LintHit } from './lint.js';
4
+ export { DocsError } from './util.js';
5
+ export type { DocsOptions, Feature, FeatureSource, Generate, Stage } from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { docsPlugin } from './plugin.js';
2
+ export { checkDocs, docsPage, docsTree, onFeatureChange, sourcesOf, syncDocs } from './sync.js';
3
+ export { lint, textOf } from './lint.js';
4
+ export { DocsError } from './util.js';
package/dist/lint.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import type { Resolved } from './types.js';
2
+ export type LintHit = {
3
+ kind: string;
4
+ text: string;
5
+ };
6
+ /** Plain text of a rich-text value (Lexical JSON) or a string. */
7
+ export declare function textOf(body: unknown): string;
8
+ /**
9
+ * Text as a reader sees it, so escaping can't hide a leak: Markdown backslash escapes removed, HTML comments and
10
+ * tags' wrappers dropped, entities decoded, invisible characters removed, look-alike hyphens and spaces made plain.
11
+ */
12
+ export declare function asRead(text: string): string;
13
+ /** Everything on a page that looks internal. Empty means clean. */
14
+ export declare function lint(o: Resolved, raw: string): LintHit[];
package/dist/lint.js ADDED
@@ -0,0 +1,74 @@
1
+ const RULES = [
2
+ { kind: 'environment variable', re: /\b[A-Z][A-Z0-9]*_[A-Z0-9_]{2,}\b/g },
3
+ { kind: 'file path', re: /(?:\b(?:src|app|lib|scripts|node_modules)\/[\w./-]+|\b[\w-]+\.(?:ts|tsx|js|mjs|json|env|yml|yaml)\b)/g },
4
+ { kind: 'IP address', re: /\b(?:\d{1,3}\.){3}\d{1,3}\b/g },
5
+ { kind: 'internal host', re: /\b[\w-]+\.(?:internal|local|lan|vercel\.app|mongodb\.net)\b|\blocalhost\b/gi },
6
+ { kind: 'key-like string', re: /\b(?:sk|pk|rk|whsec|ghp|xox[bp])[-_][A-Za-z0-9_-]{12,}\b|\b[A-Za-z0-9]{32,}\b/g },
7
+ ];
8
+ /** Plain text of a rich-text value (Lexical JSON) or a string. */
9
+ export function textOf(body) {
10
+ if (typeof body === 'string')
11
+ return body;
12
+ const out = [];
13
+ const walk = (n) => {
14
+ if (!n || typeof n !== 'object')
15
+ return;
16
+ const node = n;
17
+ if (typeof node.text === 'string')
18
+ out.push(node.text);
19
+ if (typeof node.url === 'string')
20
+ out.push(node.url);
21
+ if (typeof node.fields?.url === 'string')
22
+ out.push(node.fields.url);
23
+ if (node.root)
24
+ walk(node.root);
25
+ if (Array.isArray(node.children))
26
+ node.children.forEach(walk);
27
+ };
28
+ walk(body);
29
+ return out.join('\n');
30
+ }
31
+ /**
32
+ * Text as a reader sees it, so escaping can't hide a leak: Markdown backslash escapes removed, HTML comments and
33
+ * tags' wrappers dropped, entities decoded, invisible characters removed, look-alike hyphens and spaces made plain.
34
+ */
35
+ export function asRead(text) {
36
+ return text
37
+ .normalize('NFKC')
38
+ .replace(/<!--[\s\S]*?-->/g, '')
39
+ .replace(/<\/?[a-zA-Z][^>]*>/g, '')
40
+ .replace(/&#x([0-9a-f]+);?/gi, (_, h) => String.fromCodePoint(parseInt(h, 16)))
41
+ .replace(/&#(\d+);?/g, (_, d) => String.fromCodePoint(Number(d)))
42
+ .replace(/&(lowbar|UnderBar);/g, '_')
43
+ .replace(/&(hyphen|dash|minus);/g, '-')
44
+ .replace(/&(nbsp|ensp|emsp|thinsp);/g, ' ')
45
+ .replace(/\\([\\`*_{}[\]()#+\-.!|<>~])/g, '$1')
46
+ .replace(/[\u200B-\u200D\u2060\uFEFF\u00AD]/g, '')
47
+ .replace(/[\u2010-\u2015\u2212\uFE58\uFE63\uFF0D]/g, '-')
48
+ .replace(/[\u00A0\u2007\u202F]/g, ' ');
49
+ }
50
+ /** Everything on a page that looks internal. Empty means clean. */
51
+ export function lint(o, raw) {
52
+ const text = asRead(raw);
53
+ const hits = [];
54
+ const allowed = (s) => o.allow.some((a) => a.toLowerCase() === s.toLowerCase());
55
+ for (const { kind, re } of RULES)
56
+ for (const m of text.matchAll(re))
57
+ if (!allowed(m[0]))
58
+ hits.push({ kind, text: m[0] });
59
+ const lower = text.toLowerCase();
60
+ for (const t of o.privateTerms)
61
+ if (t && lower.includes(t.toLowerCase()))
62
+ hits.push({ kind: 'private term', text: '(a private term)' });
63
+ // Slugs only as whole words written like code (with a hyphen or as `code`), so ordinary words don't trip it.
64
+ for (const s of o.slugs) {
65
+ if (allowed(s))
66
+ continue;
67
+ const re = new RegExp(`(^|[^\\w-])${s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')}(?=$|[^\\w-])`, 'i');
68
+ if ((s.includes('-') || s.includes('_') || /[a-z][A-Z]/.test(s)) && re.test(text))
69
+ hits.push({ kind: 'collection or field name', text: s });
70
+ else if (new RegExp('`' + s + '`').test(text))
71
+ hits.push({ kind: 'collection or field name', text: s });
72
+ }
73
+ return hits;
74
+ }
@@ -0,0 +1,8 @@
1
+ import type { Plugin } from 'payload';
2
+ import type { DocsOptions } from './types.js';
3
+ /**
4
+ * Docs: a page for every feature, kept in step by the source's hook and a nightly sync, with hand-written pages
5
+ * beside them; a lint that refuses publishing internals; reviews that hold only for the words reviewed; and a check
6
+ * that nothing is missing. Feature sources and the generator are adapters; Docs depends on no other plugin.
7
+ */
8
+ export declare const docsPlugin: (options: DocsOptions) => Plugin;
package/dist/plugin.js ADDED
@@ -0,0 +1,31 @@
1
+ import { docsCollection } from './collection.js';
2
+ import { onFeatureChange } from './sync.js';
3
+ /**
4
+ * Docs: a page for every feature, kept in step by the source's hook and a nightly sync, with hand-written pages
5
+ * beside them; a lint that refuses publishing internals; reviews that hold only for the words reviewed; and a check
6
+ * that nothing is missing. Feature sources and the generator are adapters; Docs depends on no other plugin.
7
+ */
8
+ export const docsPlugin = (options) => (config) => {
9
+ const o = {
10
+ slug: options.collectionSlug ?? 'docs-pages',
11
+ sources: options.sources ?? [],
12
+ generate: options.generate,
13
+ uiTextFor: options.uiTextFor,
14
+ edit: options?.access?.edit,
15
+ review: options?.access?.review,
16
+ privateTerms: (options.privateTerms ?? []).filter((t) => typeof t === 'string' && t.trim()),
17
+ allow: options.allow ?? [],
18
+ slugs: options.slugs ?? (config.collections ?? []).map((c) => c.slug),
19
+ basePath: (options.basePath ?? '/docs').replace(/\/$/, ''),
20
+ adminGroup: options.adminGroup ?? 'Docs',
21
+ };
22
+ if (typeof o.edit !== 'function' || typeof o.review !== 'function')
23
+ throw new Error('Docs: give `access.edit` and `access.review`.');
24
+ return {
25
+ ...config,
26
+ // Other plugins register sources at `config.custom.docsSources` and call `config.custom.docs.onFeatureChange`,
27
+ // so neither side imports the other, in any plugin order.
28
+ custom: { ...config.custom, docs: { ...o, onFeatureChange } },
29
+ collections: [...(config.collections ?? []), docsCollection(o)],
30
+ };
31
+ };
package/dist/sync.d.ts ADDED
@@ -0,0 +1,61 @@
1
+ import type { Payload } from 'payload';
2
+ import type { Feature, FeatureSource, Req } from './types.js';
3
+ type Doc = Record<string, any>;
4
+ /** Every source: the plugin's own and those other plugins registered at `config.custom.docsSources`. Names are unique. */
5
+ export declare function sourcesOf(payload: Payload): FeatureSource[];
6
+ /**
7
+ * Keeps one feature's page in step. A new feature gets a draft page. Changed words mark the page out of date and
8
+ * put a fresh draft beside it, while the published words stay until a reviewer publishes the new ones. A removed
9
+ * feature's page is archived, never deleted. A source calls this from its own hook; never throws.
10
+ */
11
+ export declare function onFeatureChange(payload: Payload, args: {
12
+ source: string;
13
+ feature?: Feature;
14
+ removedId?: string;
15
+ req?: Req;
16
+ }): Promise<'made' | 'outOfDate' | 'same' | 'archived' | 'error'>;
17
+ /** Reads every source and brings every page in step: pages made, flagged or archived. For the nightly job. */
18
+ export declare function syncDocs(payload: Payload, req?: Req): Promise<{
19
+ failedSources: string[];
20
+ made: number;
21
+ outOfDate: number;
22
+ same: number;
23
+ archived: number;
24
+ error: number;
25
+ }>;
26
+ export type DocsProblem = {
27
+ kind: 'missing' | 'outOfDate' | 'unpublished' | 'brokenLink' | 'lint' | 'duplicate' | 'sourceFailed' | 'emptySource';
28
+ ref: string;
29
+ detail?: string;
30
+ };
31
+ /**
32
+ * Everything wrong, for the nightly job and the pre-release step. It doesn't fix anything: it reports.
33
+ * - every feature from every source has a page (so /docs is never smaller than Features);
34
+ * - no page is out of date;
35
+ * - every feature's page is published, planned ones included (the owner: /docs always holds at least everything in Features);
36
+ * - no feature has two pages, and no two pages share a path;
37
+ * - every source answered, with something;
38
+ * - every /docs link on a published page resolves;
39
+ * - no published page trips the lint.
40
+ */
41
+ export declare function checkDocs(payload: Payload, req?: Req): Promise<{
42
+ ok: boolean;
43
+ problems: DocsProblem[];
44
+ }>;
45
+ /** The published tree for the site's /docs routes: sections, each with its pages in order. */
46
+ export declare function docsTree(payload: Payload, args?: {
47
+ locale?: string;
48
+ }): Promise<{
49
+ key: string;
50
+ title: string;
51
+ pages: {
52
+ title: string;
53
+ summary: string;
54
+ path: string;
55
+ stage: string | null;
56
+ kind: string;
57
+ }[];
58
+ }[]>;
59
+ /** One published page by its path, or null. */
60
+ export declare function docsPage(payload: Payload, path: string): Promise<Doc | null>;
61
+ export {};
package/dist/sync.js ADDED
@@ -0,0 +1,207 @@
1
+ import { pageText } from './collection.js';
2
+ import { lint } from './lint.js';
3
+ import { configOf, slugOf } from './util.js';
4
+ const sys = { overrideAccess: true, depth: 0 };
5
+ const PLANNED = (f) => `**Planned.** This is what we intend to build. There's nothing to use yet.\n\n${f.summary ?? ''}`.trim();
6
+ async function pageFor(payload, source, featureId) {
7
+ const o = configOf(payload);
8
+ const where = { and: [{ source: { equals: source } }, { featureId: { equals: featureId } }] };
9
+ // The latest version, draft or not: a fresh draft's version mark is what tells the next sync whether to try again.
10
+ return (await payload.find({ collection: o.slug, where, limit: 1, pagination: false, draft: true, ...sys })).docs[0] ?? null;
11
+ }
12
+ /** Every source: the plugin's own and those other plugins registered at `config.custom.docsSources`. Names are unique. */
13
+ export function sourcesOf(payload) {
14
+ const o = configOf(payload);
15
+ const extra = (payload.config.custom?.docsSources ?? []);
16
+ const all = [...o.sources, ...(Array.isArray(extra) ? extra : [])];
17
+ const names = all.map((x) => x.name);
18
+ if (new Set(names).size !== names.length)
19
+ throw new Error('Docs: two feature sources have the same name.');
20
+ return all;
21
+ }
22
+ /** A slug not yet used in this section, and not one of the site's collection names: `name`, `name-2`, `name-page`. */
23
+ async function freeSlug(payload, sectionKey, slug) {
24
+ const o = configOf(payload);
25
+ // A slug that matches one of the site's collection names would be refused by the lint: give it a suffix.
26
+ if (o.slugs.some((s) => s.toLowerCase() === slug.toLowerCase()))
27
+ slug = `${slug}-page`;
28
+ const taken = new Set((await payload.find({ collection: o.slug, where: { sectionKey: { equals: sectionKey } }, pagination: false, draft: false, select: { slug: true }, ...sys })).docs.map((d) => d.slug));
29
+ if (!taken.has(slug))
30
+ return slug;
31
+ for (let i = 2;; i++)
32
+ if (!taken.has(`${slug}-${i}`))
33
+ return `${slug}-${i}`;
34
+ }
35
+ /** The words for a page: the site's generator when there is one, else the feature's own summary. Never throws. */
36
+ async function words(payload, f, req) {
37
+ const o = configOf(payload);
38
+ if (f.stage === 'planned')
39
+ return { summary: f.summary ?? '', body: PLANNED(f), ok: true };
40
+ if (!o.generate)
41
+ return { summary: f.summary ?? '', body: [f.summary, f.details].filter(Boolean).join('\n\n'), ok: true };
42
+ try {
43
+ // Only the feature's own known fields reach the generator, whatever else a source returns.
44
+ const feature = { id: f.id, section: { key: f.section.key, title: f.section.title }, title: f.title, summary: f.summary, details: f.details, stage: f.stage, audience: f.audience, links: f.links, notesForDocs: f.notesForDocs, version: f.version };
45
+ const uiText = await o.uiTextFor?.(feature, { payload });
46
+ const out = await o.generate({ feature, uiText, payload, req });
47
+ return { summary: String(out.summary ?? ''), body: String(out.body ?? ''), ok: true };
48
+ }
49
+ catch (error) {
50
+ payload.logger.error({ err: { name: error?.name }, feature: f.id, msg: 'docs: a page draft could not be generated; the page is marked out of date' });
51
+ return { summary: f.summary ?? '', body: f.summary ?? '', ok: false };
52
+ }
53
+ }
54
+ /**
55
+ * Keeps one feature's page in step. A new feature gets a draft page. Changed words mark the page out of date and
56
+ * put a fresh draft beside it, while the published words stay until a reviewer publishes the new ones. A removed
57
+ * feature's page is archived, never deleted. A source calls this from its own hook; never throws.
58
+ */
59
+ export async function onFeatureChange(payload, args) {
60
+ const o = configOf(payload);
61
+ try {
62
+ const id = args.feature?.id ?? args.removedId;
63
+ if (!id)
64
+ return 'error';
65
+ const page = await pageFor(payload, args.source, String(id));
66
+ if (!args.feature) {
67
+ if (page && !page.archived) {
68
+ // On the live page and as its latest version, so no read (published or draft) shows it to the public.
69
+ await payload.db.updateOne({ collection: o.slug, where: { id: { equals: page.id } }, data: { archived: true } });
70
+ await payload.update({ collection: o.slug, id: page.id, data: { archived: true, _status: 'draft' }, draft: true, ...sys });
71
+ }
72
+ return 'archived';
73
+ }
74
+ const f = args.feature;
75
+ const base = { kind: 'feature', source: args.source, featureId: String(f.id), sectionKey: f.section.key, section: f.section.title, title: f.title, stage: f.stage };
76
+ if (!page) {
77
+ const w = await words(payload, f, args.req);
78
+ // A failed draft keeps no version mark, so the next sync tries again.
79
+ await payload.create({ collection: o.slug, data: { ...base, generatedFrom: w.ok ? f.version : null, slug: await freeSlug(payload, f.section.key, slugOf(f.title)), summary: w.summary, body: w.body, outOfDate: !w.ok, archived: false, _status: 'draft' }, draft: true, ...sys });
80
+ return 'made';
81
+ }
82
+ if (page.generatedFrom === f.version && !page.archived)
83
+ return 'same';
84
+ const w = await words(payload, f, args.req);
85
+ // The live page keeps its words; it's flagged, and the fresh draft waits for review.
86
+ await payload.db.updateOne({ collection: o.slug, where: { id: { equals: page.id } }, data: { outOfDate: true, archived: false } });
87
+ await payload.update({ collection: o.slug, id: page.id, data: { ...base, generatedFrom: w.ok ? f.version : null, summary: w.summary, body: w.body, outOfDate: true, archived: false, _status: 'draft' }, draft: true, ...sys });
88
+ return 'outOfDate';
89
+ }
90
+ catch (error) {
91
+ payload.logger.error({ err: { name: error?.name }, msg: 'docs: a feature change was not applied to its page' });
92
+ return 'error';
93
+ }
94
+ }
95
+ /** Reads every source and brings every page in step: pages made, flagged or archived. For the nightly job. */
96
+ export async function syncDocs(payload, req) {
97
+ const o = configOf(payload);
98
+ const tally = { made: 0, outOfDate: 0, same: 0, archived: 0, error: 0 };
99
+ const failed = [];
100
+ for (const source of sourcesOf(payload)) {
101
+ let features;
102
+ try {
103
+ features = await source.list({ payload, req });
104
+ }
105
+ catch (error) {
106
+ payload.logger.error({ err: { name: error?.name }, source: source.name, msg: 'docs: a feature source failed; its pages were left as they are' });
107
+ failed.push(source.name);
108
+ continue;
109
+ }
110
+ // An empty list from a source that had features is more likely a fault than every feature going at once.
111
+ if (!features.length) {
112
+ payload.logger.warn({ source: source.name, msg: 'docs: a feature source returned nothing; its pages were left as they are' });
113
+ continue;
114
+ }
115
+ const ids = new Set(features.map((f) => String(f.id)));
116
+ for (const f of features)
117
+ tally[await onFeatureChange(payload, { source: source.name, feature: f, req })]++;
118
+ const pages = (await payload.find({ collection: o.slug, where: { and: [{ source: { equals: source.name } }, { archived: { not_equals: true } }] }, pagination: false, draft: false, ...sys })).docs;
119
+ for (const p of pages)
120
+ if (!ids.has(String(p.featureId)))
121
+ tally[await onFeatureChange(payload, { source: source.name, removedId: String(p.featureId), req })]++;
122
+ }
123
+ return { ...tally, failedSources: failed };
124
+ }
125
+ /**
126
+ * Everything wrong, for the nightly job and the pre-release step. It doesn't fix anything: it reports.
127
+ * - every feature from every source has a page (so /docs is never smaller than Features);
128
+ * - no page is out of date;
129
+ * - every feature's page is published, planned ones included (the owner: /docs always holds at least everything in Features);
130
+ * - no feature has two pages, and no two pages share a path;
131
+ * - every source answered, with something;
132
+ * - every /docs link on a published page resolves;
133
+ * - no published page trips the lint.
134
+ */
135
+ export async function checkDocs(payload, req) {
136
+ const o = configOf(payload);
137
+ const problems = [];
138
+ const all = (await payload.find({ collection: o.slug, pagination: false, draft: false, ...sys })).docs;
139
+ const live = all.filter((p) => p._status === 'published' && !p.archived);
140
+ for (const source of sourcesOf(payload)) {
141
+ let features;
142
+ try {
143
+ features = await source.list({ payload, req });
144
+ }
145
+ catch {
146
+ problems.push({ kind: 'sourceFailed', ref: source.name });
147
+ continue;
148
+ }
149
+ // Nothing from a source that has pages looks like a fault, not every feature going at once.
150
+ if (!features.length && all.some((p) => p.source === source.name && !p.archived))
151
+ problems.push({ kind: 'emptySource', ref: source.name });
152
+ for (const f of features) {
153
+ const pagesOf = all.filter((p) => p.source === source.name && String(p.featureId) === String(f.id) && !p.archived);
154
+ const page = pagesOf[0];
155
+ if (pagesOf.length > 1)
156
+ problems.push({ kind: 'duplicate', ref: `${source.name}:${f.id}` });
157
+ if (!page)
158
+ problems.push({ kind: 'missing', ref: `${source.name}:${f.id}` });
159
+ else {
160
+ if (page.outOfDate || page.generatedFrom !== f.version)
161
+ problems.push({ kind: 'outOfDate', ref: `${source.name}:${f.id}` });
162
+ if (page._status !== 'published')
163
+ problems.push({ kind: 'unpublished', ref: `${source.name}:${f.id}` });
164
+ }
165
+ }
166
+ }
167
+ const seen = new Map();
168
+ for (const p of all.filter((x) => !x.archived)) {
169
+ const path = `${p.sectionKey}/${p.slug}`;
170
+ if (seen.has(path))
171
+ problems.push({ kind: 'duplicate', ref: String(p.id), detail: `${o.basePath}/${path}` });
172
+ else
173
+ seen.set(path, String(p.id));
174
+ }
175
+ const paths = new Set(live.map((p) => `${o.basePath}/${p.sectionKey}/${p.slug}`));
176
+ const sections = new Set(live.map((p) => `${o.basePath}/${p.sectionKey}`));
177
+ for (const p of live) {
178
+ for (const h of lint(o, pageText(p)))
179
+ problems.push({ kind: 'lint', ref: String(p.id), detail: h.kind });
180
+ for (const m of String(p.body ?? '').matchAll(/\]\((\/[^)\s#?]*)/g)) {
181
+ const link = m[1].replace(/\/$/, '');
182
+ if (link.startsWith(o.basePath) && link !== o.basePath && !paths.has(link) && !sections.has(link))
183
+ problems.push({ kind: 'brokenLink', ref: String(p.id), detail: link });
184
+ }
185
+ }
186
+ return { ok: problems.length === 0, problems };
187
+ }
188
+ /** The published tree for the site's /docs routes: sections, each with its pages in order. */
189
+ export async function docsTree(payload, args = {}) {
190
+ const o = configOf(payload);
191
+ const pages = (await payload.find({ collection: o.slug, where: { and: [{ _status: { equals: 'published' } }, { archived: { not_equals: true } }] }, sort: ['sectionKey', 'order', 'title'], pagination: false, ...sys, ...(args.locale ? { locale: args.locale } : {}) })).docs;
192
+ const sections = new Map();
193
+ for (const p of pages) {
194
+ const s = sections.get(p.sectionKey) ?? { key: String(p.sectionKey), title: String(p.section), pages: [] };
195
+ s.pages.push({ title: p.title, summary: p.summary ?? '', path: `${o.basePath}/${p.sectionKey}/${p.slug}`, stage: p.stage ?? null, kind: p.kind });
196
+ sections.set(p.sectionKey, s);
197
+ }
198
+ return [...sections.values()];
199
+ }
200
+ /** One published page by its path, or null. */
201
+ export async function docsPage(payload, path) {
202
+ const o = configOf(payload);
203
+ const [section, slug] = path.replace(new RegExp(`^${o.basePath}/?`), '').split('/');
204
+ if (!section || !slug)
205
+ return null;
206
+ return ((await payload.find({ collection: o.slug, where: { and: [{ sectionKey: { equals: section } }, { slug: { equals: slug } }, { _status: { equals: 'published' } }, { archived: { not_equals: true } }] }, limit: 1, pagination: false, ...sys })).docs[0] ?? null);
207
+ }
@@ -0,0 +1,74 @@
1
+ import type { Access, Payload, PayloadRequest } from 'payload';
2
+ export type Req = Partial<PayloadRequest>;
3
+ export type Stage = 'available' | 'members' | 'in-progress' | 'planned';
4
+ /** One feature, from whatever lists them (a roadmap plugin's catalog, the site's own list). */
5
+ export type Feature = {
6
+ id: string;
7
+ section: {
8
+ key: string;
9
+ title: string;
10
+ };
11
+ title: string;
12
+ summary?: string;
13
+ details?: string;
14
+ stage: Stage;
15
+ audience?: string;
16
+ /** Site paths the feature's pages live at, for the generator's UI text and for link checks. */
17
+ links?: string[];
18
+ notesForDocs?: string;
19
+ /** Changes whenever the feature's words change: a hash or an updatedAt. */
20
+ version: string;
21
+ };
22
+ export type FeatureSource = {
23
+ name: string;
24
+ list: (args: {
25
+ payload: Payload;
26
+ req?: Req;
27
+ }) => Promise<Feature[]>;
28
+ };
29
+ /** The site's own model call. Gets the feature's fields and the user-facing text only: never code or schema. */
30
+ export type Generate = (args: {
31
+ feature: Feature;
32
+ uiText?: string;
33
+ payload: Payload;
34
+ req?: Req;
35
+ }) => Promise<{
36
+ summary: string;
37
+ body: string;
38
+ }>;
39
+ export type DocsOptions = {
40
+ sources?: FeatureSource[];
41
+ generate?: Generate;
42
+ /** The user-facing text of a feature's pages, for the generator (optional). */
43
+ uiTextFor?: (feature: Feature, args: {
44
+ payload: Payload;
45
+ }) => Promise<string | undefined>;
46
+ /** Who edits pages and sees drafts. Required. */
47
+ access: {
48
+ edit: Access;
49
+ review: Access;
50
+ };
51
+ /** Words that must never appear on a page (private names, internal hosts). Read at start-up. */
52
+ privateTerms?: string[];
53
+ /** Public names the lint lets through (Payload, Stripe, YouTube). */
54
+ allow?: string[];
55
+ /** The site's own collection and field slugs, which the lint refuses. Default: every collection slug in the config. */
56
+ slugs?: string[];
57
+ /** Where pages live: `${basePath}/${section}/${slug}`. Default '/docs'. */
58
+ basePath?: string;
59
+ collectionSlug?: string;
60
+ adminGroup?: string;
61
+ };
62
+ export type Resolved = {
63
+ slug: string;
64
+ sources: FeatureSource[];
65
+ generate?: Generate;
66
+ uiTextFor?: DocsOptions['uiTextFor'];
67
+ edit: Access;
68
+ review: Access;
69
+ privateTerms: string[];
70
+ allow: string[];
71
+ slugs: string[];
72
+ basePath: string;
73
+ adminGroup: string;
74
+ };
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/util.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { APIError, type Payload } from 'payload';
2
+ import type { Resolved } from './types.js';
3
+ export declare class DocsError extends APIError<{
4
+ code: string;
5
+ }> {
6
+ code: string;
7
+ constructor(code: string, message: string, status?: number);
8
+ }
9
+ export declare const configOf: (payload: Payload) => Resolved;
10
+ export declare const bodyHash: (text: string) => string;
11
+ export declare const slugOf: (s: string) => string;
package/dist/util.js ADDED
@@ -0,0 +1,17 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { APIError } from 'payload';
3
+ export class DocsError extends APIError {
4
+ code;
5
+ constructor(code, message, status = 400) {
6
+ super(message, status, { code }, true);
7
+ this.code = code;
8
+ }
9
+ }
10
+ export const configOf = (payload) => {
11
+ const o = payload.config.custom?.docs;
12
+ if (!o)
13
+ throw new Error('Docs: the plugin is not configured on this site.');
14
+ return o;
15
+ };
16
+ export const bodyHash = (text) => createHash('sha256').update(text).digest('hex').slice(0, 32);
17
+ export const slugOf = (s) => s.toLowerCase().normalize('NFKD').replace(/[^\w\s-]/g, '').trim().replace(/[\s_]+/g, '-').replace(/-+/g, '-').slice(0, 80) || 'page';
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@extantape/payload-plugin-docs",
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": "Docs for Payload: a docs page for every feature your site lists, made and kept up to date by hook, with hand-written pages beside them, a publish-time lint for internals, and a check that nothing is missing.",
5
+ "homepage": "https://github.com/ExtantApe/payload-plugin-docs#readme",
6
+ "bugs": {
7
+ "url": "https://github.com/ExtantApe/payload-plugin-docs/issues"
8
+ },
9
+ "keywords": [
10
+ "payload",
11
+ "payload-plugin",
12
+ "payloadcms",
13
+ "content",
14
+ "documentation",
15
+ "docs",
16
+ "help-center",
17
+ "knowledge-base",
18
+ "feature-docs",
19
+ "wiki"
20
+ ],
21
+ "license": "MIT",
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/ExtantApe/payload-plugin-docs.git"
25
+ },
26
+ "type": "module",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/index.d.ts",
30
+ "import": "./dist/index.js"
31
+ }
32
+ },
33
+ "main": "./dist/index.js",
34
+ "types": "./dist/index.d.ts",
35
+ "files": [
36
+ "dist",
37
+ "README.md",
38
+ "LICENSE"
39
+ ],
40
+ "engines": {
41
+ "node": ">=22"
42
+ },
43
+ "scripts": {
44
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
45
+ "typecheck": "tsc --noEmit",
46
+ "test": "vitest run",
47
+ "leak-check": "bash scripts/leak-check.sh",
48
+ "prepack": "npm run build",
49
+ "prepublishOnly": "npm run typecheck && npm test"
50
+ },
51
+ "peerDependencies": {
52
+ "payload": "^3.80.0"
53
+ },
54
+ "devDependencies": {
55
+ "@payloadcms/db-mongodb": "3.92.1",
56
+ "@types/node": "^24.0.0",
57
+ "graphql": "^16.14.2",
58
+ "mongodb-memory-server": "^11.3.0",
59
+ "payload": "3.92.1",
60
+ "typescript": "^5.9.0",
61
+ "vitest": "^3.2.0"
62
+ }
63
+ }