@aphexcms/plugin-seo 0.0.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/README.md ADDED
@@ -0,0 +1,200 @@
1
+ # @aphexcms/plugin-seo
2
+
3
+ SEO & social meta for AphexCMS — a reusable meta field group, length-metered
4
+ inputs, a live Google-style search preview, one-click auto-generation, and an
5
+ audit tool. Feature-comparable to `@payloadcms/plugin-seo`. SEO is a plugin, not a
6
+ built-in: the engine ships the primitives, SEO composes on top of them.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ pnpm add @aphexcms/plugin-seo
12
+ ```
13
+
14
+ Register it once in your client-safe plugin registry (`src/lib/plugins.ts`):
15
+
16
+ ```ts
17
+ import { seoPlugin } from '@aphexcms/plugin-seo';
18
+
19
+ export const plugins = [
20
+ seoPlugin({
21
+ collections: ['blog_post', 'author'] // auto-enable SEO on these document types
22
+ })
23
+ ];
24
+ ```
25
+
26
+ Because this plugin contributes an `aphex/schema/transform` part (when
27
+ `collections` is set), it must be registered on **both** planes — the client
28
+ registry above **and** `aphex.config.ts`, which both import `src/lib/plugins.ts`.
29
+ See the [Plugins guide](https://aphexcms.com/docs/plugins) for the two-plane rule.
30
+
31
+ ## What you get
32
+
33
+ Registering the plugin adds, per configured collection:
34
+
35
+ - A **SEO & Social** field group (`metaTitle`, `metaDescription`, `ogImage`,
36
+ `noIndex`) injected into the document — no hand-editing schemas.
37
+ - **Length-metered inputs** on the title/description (the `seo-length` widget)
38
+ that flag when you run past the ~60/~155 character sweet spots.
39
+ - A **live search preview** (the `seo-preview` widget) — a Google-style result
40
+ card that updates as you type.
41
+ - A **✨ Generate SEO** document action that auto-fills meta from the document.
42
+ - An **SEO** admin tool (audit) that scores documents on title, description, and
43
+ social image.
44
+
45
+ ## Enabling SEO on a document
46
+
47
+ The normal path is `collections` — the plugin injects the field group for you and
48
+ is idempotent (a schema that already has a `seo` field is left untouched):
49
+
50
+ ```ts
51
+ seoPlugin({ collections: ['blog_post', 'author', 'tag'] });
52
+ ```
53
+
54
+ By default the fields go in a `seo` group (rendered as an **SEO** tab). Change it:
55
+
56
+ ```ts
57
+ seoPlugin({ collections: ['blog_post'], group: 'metadata' });
58
+ ```
59
+
60
+ ### The `type: 'seo'` literal
61
+
62
+ To place SEO explicitly — e.g. to control field ordering — write the literal. No
63
+ import: registering the plugin augments core's `FieldTypeMap`, so `{ type: 'seo' }`
64
+ is fully type-safe (autocomplete, typos caught), and the plugin's schema-transform
65
+ desugars it into the `seo` object before the engine and codegen see it.
66
+
67
+ ```ts
68
+ // in a document schema's fields:
69
+ { name: 'seo', type: 'seo', title: 'SEO & Social', group: 'metadata' }
70
+ ```
71
+
72
+ Like `type: 'color'`, this is sugar over a built-in `object` — the stored data is
73
+ portable and interpretable by core even if the plugin is removed. It generates a
74
+ fully-typed nested interface in `generated-types.ts` (not `unknown`), provided the
75
+ type generator runs your plugins (see [Type generation](#type-generation)).
76
+
77
+ ### The `seoField()` builder
78
+
79
+ Equivalent to `type: 'seo'`, for when you'd rather import a builder than rely on
80
+ the ambient type. Import from the server-safe `/schema` entry:
81
+
82
+ ```ts
83
+ import { seoField } from '@aphexcms/plugin-seo/schema';
84
+
85
+ // in a document schema's fields:
86
+ seoField('seo'); // pass a group name, or omit for none
87
+ ```
88
+
89
+ `injectSeoField(schema, group?)` is the same transform the plugin applies — useful
90
+ if you compose your own schema pipeline:
91
+
92
+ ```ts
93
+ import { injectSeoField } from '@aphexcms/plugin-seo/schema';
94
+
95
+ const withSeo = injectSeoField(blogPostSchema, 'seo');
96
+ ```
97
+
98
+ ## Auto-generation
99
+
100
+ The **✨ Generate SEO** action and the audit tool derive meta from a document via
101
+ four generators. The defaults are **schema-aware** — they read each type's own
102
+ `preview` config plus conventional field names (`title`/`excerpt`/`coverImage`,
103
+ etc.), so a blog post, an author, and a tag all resolve correctly with zero config.
104
+
105
+ Override any of them at registration to change how meta is derived:
106
+
107
+ ```ts
108
+ seoPlugin({
109
+ collections: ['blog_post', 'author'],
110
+ generateTitle: (doc, { typeName }) => (typeName === 'author' ? `${doc.name} — Staff` : doc.title),
111
+ generateDescription: (doc) => doc.excerpt ?? '',
112
+ generateURL: (doc, { typeName }) =>
113
+ typeName === 'author' ? `/authors/${doc.slug}` : `/blog/${doc.slug}`,
114
+ generateImage: (doc) => doc.coverImage
115
+ });
116
+ ```
117
+
118
+ Each generator receives the document **and** a `SeoGenContext` (`{ schema, typeName }`),
119
+ so one function can serve many collections.
120
+
121
+ | Generator | Signature | Default |
122
+ | --------------------- | ----------------------- | ------------------------------------------------------ |
123
+ | `generateTitle` | `(doc, ctx) => string` | Preview title → `title`/`heading`/`name`/`label` |
124
+ | `generateDescription` | `(doc, ctx) => string` | `excerpt`/`description`/`summary`/… → preview subtitle |
125
+ | `generateURL` | `(doc, ctx) => string` | `/${doc.slug}` |
126
+ | `generateImage?` | `(doc, ctx) => unknown` | none (falls back to cover image) |
127
+
128
+ ## Stored shape
129
+
130
+ The `seo` field is a plain `object` — portable, interpretable by core even if the
131
+ plugin is removed. Everything is optional; the frontend falls back to the
132
+ document's own title / excerpt / cover image.
133
+
134
+ ```json
135
+ {
136
+ "metaTitle": "How we cut build times in half",
137
+ "metaDescription": "A walkthrough of the caching changes that…",
138
+ "ogImage": { "asset": { "…": "…" } },
139
+ "noIndex": false
140
+ }
141
+ ```
142
+
143
+ ## Reading it on the frontend
144
+
145
+ Resolve meta with the same precedence the plugin uses — explicit override first,
146
+ then a sensible fallback:
147
+
148
+ ```svelte
149
+ <script lang="ts">
150
+ let { doc } = $props();
151
+ const title = doc.seo?.metaTitle ?? doc.title;
152
+ const description = doc.seo?.metaDescription ?? doc.excerpt;
153
+ </script>
154
+
155
+ <svelte:head>
156
+ <title>{title}</title>
157
+ <meta name="description" content={description} />
158
+ {#if doc.seo?.noIndex}<meta name="robots" content="noindex" />{/if}
159
+ </svelte:head>
160
+ ```
161
+
162
+ The plugin reuses this same precedence internally (schema-aware `resolveTitle` /
163
+ `resolveDescription` / `hasSocialImage` fallbacks) to power auto-generation and the
164
+ audit tool.
165
+
166
+ ## Type generation
167
+
168
+ The `{ type: 'seo' }` literal (and the `collections` injection) only desugars into
169
+ its object shape during codegen if the type generator is told about your plugins.
170
+ Pass your plugin registry as the third argument:
171
+
172
+ ```jsonc
173
+ // package.json
174
+ "generate:types": "aphex generate:types ./src/lib/schemaTypes/index.ts ./src/lib/generated-types.ts ./src/lib/plugins.ts"
175
+ ```
176
+
177
+ The `aphex()` Vite plugin does this automatically in dev (it passes
178
+ `src/lib/plugins.ts` by default). Without the plugins argument, a `{ type: 'seo' }`
179
+ field generates as `unknown`.
180
+
181
+ ## Exports
182
+
183
+ | Import | From | What |
184
+ | -------------------------------- | ----------------------------- | ----------------------------------------- |
185
+ | `seoPlugin(options)` | `@aphexcms/plugin-seo` | The plugin (register in `plugins.ts`) |
186
+ | `SeoPluginOptions` | `@aphexcms/plugin-seo` | Options type |
187
+ | `seoField(group?)` | `@aphexcms/plugin-seo/schema` | The reusable SEO object field |
188
+ | `injectSeoField(schema, group?)` | `@aphexcms/plugin-seo/schema` | Idempotent injector transform |
189
+ | `SeoField` | `@aphexcms/plugin-seo/schema` | The authored `{ type: 'seo' }` field type |
190
+
191
+ ## Options
192
+
193
+ ```ts
194
+ interface SeoPluginOptions extends Partial<SeoGenerators> {
195
+ /** Document type names to auto-enable SEO on (injects the meta field group). */
196
+ collections?: string[];
197
+ /** Field group the SEO fields go in. Default `'seo'`. */
198
+ group?: string;
199
+ }
200
+ ```
@@ -0,0 +1,56 @@
1
+ <script lang="ts">
2
+ import { Button } from '@aphexcms/ui/shadcn/button';
3
+ import { Sparkles } from '@lucide/svelte';
4
+ import { toast } from 'svelte-sonner';
5
+ import type { DocumentActionProps } from '@aphexcms/cms-core';
6
+ import { seoGenerators } from './config';
7
+
8
+ // Every document-action component receives exactly this stable context —
9
+ // nothing from the editor's internals.
10
+ let { action }: { action: DocumentActionProps } = $props();
11
+
12
+ let busy = $state(false);
13
+
14
+ async function generate() {
15
+ if (busy) return;
16
+ busy = true;
17
+ try {
18
+ const data = action.data as Record<string, any>;
19
+ const existing = (data.seo as Record<string, unknown> | undefined) ?? {};
20
+ const gen = seoGenerators();
21
+
22
+ // Derive meta from the plugin's configured generators. The defaults read
23
+ // each type's own `preview` config, so this works across collections
24
+ // (blog→title/excerpt, author→name/bio, …); override via seoPlugin({ … }).
25
+ const ctx = { schema: action.schema, typeName: action.schema.name };
26
+ const seo: Record<string, unknown> = {
27
+ ...existing,
28
+ metaTitle: gen.generateTitle(data, ctx),
29
+ metaDescription: gen.generateDescription(data, ctx)
30
+ };
31
+ if (gen.generateImage) {
32
+ const img = gen.generateImage(data, ctx);
33
+ if (img) seo.ogImage = img;
34
+ }
35
+
36
+ action.updateData({ seo });
37
+ await action.save();
38
+ toast.success('SEO fields generated.');
39
+ } catch (err) {
40
+ toast.error(err instanceof Error ? err.message : 'Could not generate SEO.');
41
+ } finally {
42
+ busy = false;
43
+ }
44
+ }
45
+ </script>
46
+
47
+ <Button
48
+ variant="ghost"
49
+ size="icon"
50
+ onclick={generate}
51
+ disabled={busy}
52
+ class="h-8 w-8 hover:cursor-pointer"
53
+ title="Generate SEO meta"
54
+ >
55
+ <Sparkles class="h-4 w-4 {busy ? 'animate-pulse' : ''}" />
56
+ </Button>
@@ -0,0 +1,8 @@
1
+ import type { DocumentActionProps } from '@aphexcms/cms-core';
2
+ type $$ComponentProps = {
3
+ action: DocumentActionProps;
4
+ };
5
+ declare const GenerateSeoAction: import("svelte").Component<$$ComponentProps, {}, "">;
6
+ type GenerateSeoAction = ReturnType<typeof GenerateSeoAction>;
7
+ export default GenerateSeoAction;
8
+ //# sourceMappingURL=GenerateSeoAction.svelte.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GenerateSeoAction.svelte.d.ts","sourceRoot":"","sources":["../src/lib/GenerateSeoAction.svelte.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAG7D,KAAK,gBAAgB,GAAI;IAAE,MAAM,EAAE,mBAAmB,CAAA;CAAE,CAAC;AAqD1D,QAAA,MAAM,iBAAiB,sDAAwC,CAAC;AAChE,KAAK,iBAAiB,GAAG,UAAU,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAC9D,eAAe,iBAAiB,CAAC"}
@@ -0,0 +1,60 @@
1
+ <script lang="ts">
2
+ import { Input } from '@aphexcms/ui/shadcn/input';
3
+ import { Textarea } from '@aphexcms/ui/shadcn/textarea';
4
+ import type { FieldComponentProps } from '@aphexcms/cms-core';
5
+
6
+ // Same prop contract as the built-in field renderers — a drop-in replacement.
7
+ let {
8
+ field,
9
+ value,
10
+ onUpdate,
11
+ readonly = false,
12
+ validationClasses
13
+ }: FieldComponentProps = $props();
14
+
15
+ const text = $derived(typeof value === 'string' ? value : '');
16
+ const len = $derived(text.length);
17
+
18
+ // Title vs. meta-description guidance (chars): titles aim ~60, descriptions ~155.
19
+ const isDescription = $derived(field.type === 'text');
20
+ const ideal = $derived(isDescription ? 155 : 60);
21
+ const max = $derived(isDescription ? 165 : 70);
22
+ const tone = $derived(len === 0 ? 'idle' : len <= ideal ? 'good' : len <= max ? 'warn' : 'over');
23
+ const toneClass = $derived(
24
+ tone === 'good'
25
+ ? 'text-emerald-600 dark:text-emerald-500'
26
+ : tone === 'warn'
27
+ ? 'text-amber-600 dark:text-amber-500'
28
+ : tone === 'over'
29
+ ? 'text-destructive'
30
+ : 'text-muted-foreground'
31
+ );
32
+ </script>
33
+
34
+ <div class="relative">
35
+ {#if isDescription}
36
+ <Textarea
37
+ value={text}
38
+ oninput={(e) => onUpdate(e.currentTarget.value)}
39
+ disabled={readonly}
40
+ rows={3}
41
+ class="pr-14 {validationClasses ?? ''}"
42
+ />
43
+ {:else}
44
+ <Input
45
+ type="text"
46
+ value={text}
47
+ oninput={(e) => onUpdate(e.currentTarget.value)}
48
+ disabled={readonly}
49
+ class="pr-14 {validationClasses ?? ''}"
50
+ />
51
+ {/if}
52
+ <span
53
+ class="pointer-events-none absolute right-3 font-mono text-[11px] tabular-nums {toneClass} {isDescription
54
+ ? 'top-2.5'
55
+ : 'top-1/2 -translate-y-1/2'}"
56
+ title="Ideal ≤ {ideal} characters"
57
+ >
58
+ {len}/{ideal}
59
+ </span>
60
+ </div>
@@ -0,0 +1,5 @@
1
+ import type { FieldComponentProps } from '@aphexcms/cms-core';
2
+ declare const MetaLengthInput: import("svelte").Component<FieldComponentProps, {}, "">;
3
+ type MetaLengthInput = ReturnType<typeof MetaLengthInput>;
4
+ export default MetaLengthInput;
5
+ //# sourceMappingURL=MetaLengthInput.svelte.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MetaLengthInput.svelte.d.ts","sourceRoot":"","sources":["../src/lib/MetaLengthInput.svelte.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAkD9D,QAAA,MAAM,eAAe,yDAAwC,CAAC;AAC9D,KAAK,eAAe,GAAG,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC;AAC1D,eAAe,eAAe,CAAC"}
@@ -0,0 +1,36 @@
1
+ <script lang="ts">
2
+ import type { FieldComponentProps } from '@aphexcms/cms-core';
3
+ import { seoGenerators } from './config';
4
+
5
+ // UI-only widget: ignores its own value, renders a live Google-style snippet from
6
+ // the document's data + the plugin's configured generators.
7
+ let { documentData, schemaType }: FieldComponentProps = $props();
8
+
9
+ const doc = $derived((documentData ?? {}) as Record<string, any>);
10
+ const seo = $derived((doc.seo ?? {}) as Record<string, any>);
11
+ const gen = seoGenerators();
12
+ // No schema object here (field widgets only get the type name), so the generators
13
+ // fall back to conventional fields — enough for the preview. typeName lets a
14
+ // per-type generateURL pick the right route.
15
+ const ctx = $derived({ typeName: schemaType });
16
+
17
+ const title = $derived(seo.metaTitle || gen.generateTitle(doc, ctx) || 'Untitled');
18
+ const description = $derived(seo.metaDescription || gen.generateDescription(doc, ctx) || '');
19
+ const url = $derived(gen.generateURL(doc, ctx));
20
+ const displayUrl = $derived(url.replace(/^https?:\/\//, '').replace(/\/$/, '') || 'example.com');
21
+ </script>
22
+
23
+ <div class="border-border bg-card rounded-lg border p-4">
24
+ <div class="text-[11px] leading-none text-emerald-700 dark:text-emerald-500">
25
+ {displayUrl}
26
+ </div>
27
+ <div class="mt-1 truncate text-lg leading-snug text-[#1a0dab] dark:text-[#8ab4f8]">
28
+ {title}
29
+ </div>
30
+ <p class="text-muted-foreground mt-0.5 line-clamp-2 text-sm leading-snug">
31
+ {description || 'Add a meta description, or one is generated from the excerpt.'}
32
+ </p>
33
+ {#if seo.noIndex}
34
+ <div class="text-destructive mt-2 text-[11px] font-medium">Hidden from search engines</div>
35
+ {/if}
36
+ </div>
@@ -0,0 +1,5 @@
1
+ import type { FieldComponentProps } from '@aphexcms/cms-core';
2
+ declare const SeoPreview: import("svelte").Component<FieldComponentProps, {}, "">;
3
+ type SeoPreview = ReturnType<typeof SeoPreview>;
4
+ export default SeoPreview;
5
+ //# sourceMappingURL=SeoPreview.svelte.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SeoPreview.svelte.d.ts","sourceRoot":"","sources":["../src/lib/SeoPreview.svelte.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AA0C9D,QAAA,MAAM,UAAU,yDAAwC,CAAC;AACzD,KAAK,UAAU,GAAG,UAAU,CAAC,OAAO,UAAU,CAAC,CAAC;AAChD,eAAe,UAAU,CAAC"}
@@ -0,0 +1,214 @@
1
+ <script lang="ts">
2
+ import { onMount } from 'svelte';
3
+ import { documents } from '@aphexcms/cms-core';
4
+ import type { AdminToolProps, SchemaType } from '@aphexcms/cms-core';
5
+ import { resolveTitle, resolveDescription, hasSocialImage } from './config';
6
+ import { Button } from '@aphexcms/ui/shadcn/button';
7
+ import {
8
+ Sparkles,
9
+ CheckCircle2,
10
+ AlertTriangle,
11
+ XCircle,
12
+ ArrowRight,
13
+ RefreshCw
14
+ } from '@lucide/svelte';
15
+
16
+ // The stable context every admin tool receives (org, schemas, navigation, …).
17
+ let { tool }: { tool: AdminToolProps } = $props();
18
+
19
+ // Audit every SEO-enabled document type — i.e. any document schema that carries a
20
+ // `seo` field (added directly or injected by the plugin's collections transform).
21
+ const targetTypes = $derived(
22
+ tool.schemas.filter((s) => s.type === 'document' && s.fields.some((f) => f.name === 'seo'))
23
+ );
24
+
25
+ type Status = 'good' | 'warn' | 'missing';
26
+ interface Audit {
27
+ id: string;
28
+ type: string;
29
+ typeTitle: string;
30
+ title: string;
31
+ issues: string[];
32
+ status: Status;
33
+ }
34
+
35
+ let audits = $state<Audit[]>([]);
36
+ let loading = $state(true);
37
+ let error = $state<string | null>(null);
38
+
39
+ const str = (v: unknown): string => (typeof v === 'string' && v.trim() ? v.trim() : '');
40
+
41
+ /**
42
+ * Compute an SEO health check for one document. The schema comes from the query
43
+ * (we filtered `targetTypes` by it), so it's authoritative — the REST list row
44
+ * carries no reliable top-level `type`. Title / description / image are resolved
45
+ * the same way the Generate action fills them: the schema's own `preview` config
46
+ * first (so an author uses `name`/`bio`, not the blog's `title`/`excerpt`), then
47
+ * conventional fallbacks. Editors can always override via the `seo` fields.
48
+ */
49
+ function auditDoc(doc: Record<string, any>, schema: SchemaType): Audit {
50
+ // The REST list returns each document flattened (perspective applied) — the
51
+ // content fields sit at the top level, not under `draftData`.
52
+ const data = doc;
53
+ const seo = (data.seo ?? {}) as Record<string, any>;
54
+ const issues: string[] = [];
55
+
56
+ const metaTitle = str(seo.metaTitle) || resolveTitle(data, schema);
57
+ if (!metaTitle) issues.push('No title');
58
+
59
+ const metaDesc = str(seo.metaDescription) || resolveDescription(data, schema);
60
+ if (!metaDesc) issues.push('No meta description');
61
+ else if (metaDesc.length > 160) issues.push('Meta description too long');
62
+ else if (metaDesc.length < 50) issues.push('Meta description too short');
63
+
64
+ if (!hasSocialImage(data, schema)) issues.push('No social image');
65
+ if (seo.noIndex) issues.push('Hidden from search');
66
+
67
+ const critical = issues.includes('No title') || issues.includes('No meta description');
68
+ const status: Status = issues.length === 0 ? 'good' : critical ? 'missing' : 'warn';
69
+ return {
70
+ id: doc.id,
71
+ type: schema.name,
72
+ typeTitle: schema.title,
73
+ title: resolveTitle(data, schema) || 'Untitled',
74
+ issues,
75
+ status
76
+ };
77
+ }
78
+
79
+ async function load() {
80
+ loading = true;
81
+ error = null;
82
+ try {
83
+ const perType = await Promise.all(
84
+ targetTypes.map(async (t) => {
85
+ const res = await documents.list({ type: t.name, perspective: 'draft', pageSize: 100 });
86
+ const docs = res.success && res.data ? res.data : [];
87
+ return docs.map((d) => auditDoc(d, t));
88
+ })
89
+ );
90
+ audits = perType.flat();
91
+ } catch (e) {
92
+ error = e instanceof Error ? e.message : 'Failed to load documents.';
93
+ } finally {
94
+ loading = false;
95
+ }
96
+ }
97
+
98
+ onMount(load);
99
+
100
+ const stats = $derived({
101
+ total: audits.length,
102
+ good: audits.filter((a) => a.status === 'good').length,
103
+ warn: audits.filter((a) => a.status === 'warn').length,
104
+ missing: audits.filter((a) => a.status === 'missing').length
105
+ });
106
+ </script>
107
+
108
+ <div class="mx-auto max-w-4xl px-6 py-10">
109
+ <div class="flex items-start justify-between gap-4">
110
+ <div class="flex items-center gap-3">
111
+ <div class="bg-primary/10 text-primary flex h-10 w-10 items-center justify-center rounded-lg">
112
+ <Sparkles class="h-5 w-5" />
113
+ </div>
114
+ <div>
115
+ <h1 class="text-xl font-semibold tracking-tight">SEO Audit</h1>
116
+ <p class="text-muted-foreground text-sm">
117
+ {stats.total} item{stats.total === 1 ? '' : 's'} across {targetTypes.length} type{targetTypes.length ===
118
+ 1
119
+ ? ''
120
+ : 's'}
121
+ </p>
122
+ </div>
123
+ </div>
124
+ <Button variant="outline" size="sm" onclick={load} disabled={loading} class="gap-2">
125
+ <RefreshCw class="h-3.5 w-3.5 {loading ? 'animate-spin' : ''}" /> Refresh
126
+ </Button>
127
+ </div>
128
+
129
+ <!-- Summary -->
130
+ <div class="mt-6 grid grid-cols-3 gap-3">
131
+ <div class="border-border bg-card rounded-lg border p-4">
132
+ <div class="flex items-center gap-2 text-emerald-600 dark:text-emerald-500">
133
+ <CheckCircle2 class="h-4 w-4" />
134
+ <span class="text-2xl font-semibold tabular-nums">{stats.good}</span>
135
+ </div>
136
+ <p class="text-muted-foreground mt-1 text-xs">Optimized</p>
137
+ </div>
138
+ <div class="border-border bg-card rounded-lg border p-4">
139
+ <div class="flex items-center gap-2 text-amber-600 dark:text-amber-500">
140
+ <AlertTriangle class="h-4 w-4" />
141
+ <span class="text-2xl font-semibold tabular-nums">{stats.warn}</span>
142
+ </div>
143
+ <p class="text-muted-foreground mt-1 text-xs">Warnings</p>
144
+ </div>
145
+ <div class="border-border bg-card rounded-lg border p-4">
146
+ <div class="text-destructive flex items-center gap-2">
147
+ <XCircle class="h-4 w-4" />
148
+ <span class="text-2xl font-semibold tabular-nums">{stats.missing}</span>
149
+ </div>
150
+ <p class="text-muted-foreground mt-1 text-xs">Needs work</p>
151
+ </div>
152
+ </div>
153
+
154
+ <!-- List -->
155
+ <div class="border-border bg-card mt-6 overflow-hidden rounded-xl border">
156
+ {#if loading}
157
+ <div class="text-muted-foreground p-8 text-center text-sm">Auditing content…</div>
158
+ {:else if error}
159
+ <div class="text-destructive p-8 text-center text-sm">{error}</div>
160
+ {:else if audits.length === 0}
161
+ <div class="text-muted-foreground p-8 text-center text-sm">
162
+ No posts or pages to audit yet.
163
+ </div>
164
+ {:else}
165
+ <ul class="divide-border divide-y">
166
+ {#each audits as a (a.id)}
167
+ <li class="flex items-center gap-3 px-4 py-3">
168
+ {#if a.status === 'good'}
169
+ <CheckCircle2 class="h-4 w-4 shrink-0 text-emerald-600 dark:text-emerald-500" />
170
+ {:else if a.status === 'warn'}
171
+ <AlertTriangle class="h-4 w-4 shrink-0 text-amber-600 dark:text-amber-500" />
172
+ {:else}
173
+ <XCircle class="text-destructive h-4 w-4 shrink-0" />
174
+ {/if}
175
+
176
+ <div class="min-w-0 flex-1">
177
+ <div class="flex items-center gap-2">
178
+ <span class="truncate text-sm font-medium">{a.title}</span>
179
+ <span
180
+ class="bg-muted text-muted-foreground shrink-0 rounded px-1.5 py-0.5 text-[10px] font-medium tracking-wide uppercase"
181
+ >
182
+ {a.typeTitle}
183
+ </span>
184
+ </div>
185
+ {#if a.issues.length > 0}
186
+ <p class="text-muted-foreground mt-0.5 truncate text-xs">{a.issues.join(' · ')}</p>
187
+ {:else}
188
+ <p class="mt-0.5 text-xs text-emerald-600 dark:text-emerald-500">
189
+ All checks passed
190
+ </p>
191
+ {/if}
192
+ </div>
193
+
194
+ <Button
195
+ variant="ghost"
196
+ size="sm"
197
+ class="shrink-0 gap-1 hover:cursor-pointer"
198
+ onclick={() => tool.openDocument(a.type, a.id)}
199
+ >
200
+ Fix <ArrowRight class="h-3.5 w-3.5" />
201
+ </Button>
202
+ </li>
203
+ {/each}
204
+ </ul>
205
+ {/if}
206
+ </div>
207
+
208
+ <p class="text-muted-foreground mt-4 text-xs leading-relaxed">
209
+ This dashboard is a plugin admin tool (<code>aphex/admin/tool</code>). It fetches content
210
+ through the session-authenticated REST client, scores each item, and routes you into the editor
211
+ via
212
+ <code>tool.openDocument()</code> — no core files touched.
213
+ </p>
214
+ </div>
@@ -0,0 +1,8 @@
1
+ import type { AdminToolProps } from '@aphexcms/cms-core';
2
+ type $$ComponentProps = {
3
+ tool: AdminToolProps;
4
+ };
5
+ declare const SeoTool: import("svelte").Component<$$ComponentProps, {}, "">;
6
+ type SeoTool = ReturnType<typeof SeoTool>;
7
+ export default SeoTool;
8
+ //# sourceMappingURL=SeoTool.svelte.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SeoTool.svelte.d.ts","sourceRoot":"","sources":["../src/lib/SeoTool.svelte.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,cAAc,EAAc,MAAM,oBAAoB,CAAC;AAsBpE,KAAK,gBAAgB,GAAI;IAAE,IAAI,EAAE,cAAc,CAAA;CAAE,CAAC;AAoMnD,QAAA,MAAM,OAAO,sDAAwC,CAAC;AACtD,KAAK,OAAO,GAAG,UAAU,CAAC,OAAO,OAAO,CAAC,CAAC;AAC1C,eAAe,OAAO,CAAC"}
package/dist/app.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ // Aphex plugins consume `@aphexcms/cms-core` from source, so this package's
2
+ // `svelte-check` follows into cms-core's server files, which rely on the
3
+ // SvelteKit `App.Locals` augmentation a host app provides. Re-declare it here so
4
+ // the plugin type-checks standalone (in an app, the app's own app.d.ts wins).
5
+ import type { CMSInstances, Auth, PreviewPerspective } from '@aphexcms/cms-core/server';
6
+
7
+ declare global {
8
+ namespace App {
9
+ interface Locals {
10
+ aphexCMS: CMSInstances;
11
+ auth?: Auth;
12
+ previewPerspective?: PreviewPerspective;
13
+ }
14
+ }
15
+ }
16
+
17
+ export {};
@@ -0,0 +1,45 @@
1
+ /**
2
+ * SEO generator config — the functions the plugin uses to auto-fill meta from a
3
+ * document. `seoPlugin(options)` sets these once at registration; the Generate
4
+ * action, the audit tool, and the search preview read them. Provide your own to
5
+ * change how titles, descriptions, images, and URLs are derived (like Payload's
6
+ * `generateTitle` etc.).
7
+ *
8
+ * Each generator receives the document AND a context object carrying the schema
9
+ * and its type name, so one function can serve many collections — e.g.
10
+ * `generateURL: (doc, { typeName }) => typeName === 'author' ? ... : ...`. The
11
+ * defaults are schema-aware: they read each type's own `preview` config, so a
12
+ * blog post (title/excerpt), an author (name/bio), and a tag (title/description)
13
+ * all resolve correctly with zero config.
14
+ */
15
+ import type { SchemaType } from '@aphexcms/cms-core';
16
+ /** Context passed to every generator alongside the document data. */
17
+ export interface SeoGenContext {
18
+ /** The document's schema — lets defaults read its `preview` config. */
19
+ schema?: SchemaType;
20
+ /** The document type name (e.g. `'author'`) — for per-type branching. */
21
+ typeName?: string;
22
+ }
23
+ export interface SeoGenerators {
24
+ generateTitle: (doc: Record<string, any>, ctx: SeoGenContext) => string;
25
+ generateDescription: (doc: Record<string, any>, ctx: SeoGenContext) => string;
26
+ generateImage?: (doc: Record<string, any>, ctx: SeoGenContext) => unknown;
27
+ generateURL: (doc: Record<string, any>, ctx: SeoGenContext) => string;
28
+ }
29
+ /**
30
+ * Best-effort title for a document, honoring the schema's `preview` config first
31
+ * (the canonical "what represents this doc" declaration), then conventional field
32
+ * names. Returns `''` when nothing real is found — so callers can detect a
33
+ * genuinely missing title rather than a placeholder.
34
+ */
35
+ export declare function resolveTitle(doc: Record<string, any>, schema?: SchemaType): string;
36
+ /**
37
+ * Best-effort meta description: conventional description-ish fields, then the
38
+ * schema's preview subtitle as a last resort. Returns `''` when none apply.
39
+ */
40
+ export declare function resolveDescription(doc: Record<string, any>, schema?: SchemaType): string;
41
+ /** Whether the document has a usable social/preview image (uploaded asset). */
42
+ export declare function hasSocialImage(doc: Record<string, any>, schema?: SchemaType): boolean;
43
+ export declare function configureSeo(overrides: Partial<SeoGenerators>): void;
44
+ export declare function seoGenerators(): SeoGenerators;
45
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/lib/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAGrD,qEAAqE;AACrE,MAAM,WAAW,aAAa;IAC7B,uEAAuE;IACvE,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,yEAAyE;IACzE,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,aAAa;IAC7B,aAAa,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,GAAG,EAAE,aAAa,KAAK,MAAM,CAAC;IACxE,mBAAmB,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,GAAG,EAAE,aAAa,KAAK,MAAM,CAAC;IAC9E,aAAa,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,GAAG,EAAE,aAAa,KAAK,OAAO,CAAC;IAC1E,WAAW,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,GAAG,EAAE,aAAa,KAAK,MAAM,CAAC;CACtE;AAWD;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,CAAC,EAAE,UAAU,GAAG,MAAM,CAWlF;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,CAAC,EAAE,UAAU,GAAG,MAAM,CAOxF;AAED,+EAA+E;AAC/E,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,CAAC,EAAE,UAAU,GAAG,OAAO,CASrF;AAUD,wBAAgB,YAAY,CAAC,SAAS,EAAE,OAAO,CAAC,aAAa,CAAC,GAAG,IAAI,CAEpE;AAED,wBAAgB,aAAa,IAAI,aAAa,CAE7C"}
package/dist/config.js ADDED
@@ -0,0 +1,66 @@
1
+ import { readPath, resolvePreviewSubtitle } from '@aphexcms/cms-core';
2
+ /** Conventional field names to scan when a schema doesn't pin one down. */
3
+ const TITLE_FIELDS = ['title', 'heading', 'name', 'label'];
4
+ const DESCRIPTION_FIELDS = ['excerpt', 'description', 'summary', 'bio', 'tagline', 'abstract'];
5
+ const IMAGE_FIELDS = ['coverImage', 'mainImage', 'image', 'avatar', 'photo'];
6
+ function str(value) {
7
+ return typeof value === 'string' && value.trim() ? value.trim() : '';
8
+ }
9
+ /**
10
+ * Best-effort title for a document, honoring the schema's `preview` config first
11
+ * (the canonical "what represents this doc" declaration), then conventional field
12
+ * names. Returns `''` when nothing real is found — so callers can detect a
13
+ * genuinely missing title rather than a placeholder.
14
+ */
15
+ export function resolveTitle(doc, schema) {
16
+ const path = schema?.preview?.select?.title;
17
+ if (path) {
18
+ const fromPreview = str(readPath(doc, path));
19
+ if (fromPreview)
20
+ return fromPreview;
21
+ }
22
+ for (const name of TITLE_FIELDS) {
23
+ const value = str(doc[name]);
24
+ if (value)
25
+ return value;
26
+ }
27
+ return '';
28
+ }
29
+ /**
30
+ * Best-effort meta description: conventional description-ish fields, then the
31
+ * schema's preview subtitle as a last resort. Returns `''` when none apply.
32
+ */
33
+ export function resolveDescription(doc, schema) {
34
+ for (const name of DESCRIPTION_FIELDS) {
35
+ const value = str(doc[name]);
36
+ if (value)
37
+ return value;
38
+ }
39
+ const subtitle = schema ? resolvePreviewSubtitle(doc, schema) : null;
40
+ return subtitle ?? '';
41
+ }
42
+ /** Whether the document has a usable social/preview image (uploaded asset). */
43
+ export function hasSocialImage(doc, schema) {
44
+ const seo = (doc.seo ?? {});
45
+ if (seo.ogImage?.asset)
46
+ return true;
47
+ const path = schema?.preview?.select?.media;
48
+ if (path) {
49
+ const media = readPath(doc, path);
50
+ if (media?.asset)
51
+ return true;
52
+ }
53
+ return IMAGE_FIELDS.some((name) => doc[name]?.asset);
54
+ }
55
+ const defaults = {
56
+ generateTitle: (doc, ctx) => resolveTitle(doc, ctx?.schema),
57
+ generateDescription: (doc, ctx) => resolveDescription(doc, ctx?.schema),
58
+ generateURL: (doc) => (typeof doc.slug === 'string' ? `/${doc.slug}` : '/')
59
+ };
60
+ let current = defaults;
61
+ export function configureSeo(overrides) {
62
+ current = { ...defaults, ...overrides };
63
+ }
64
+ export function seoGenerators() {
65
+ return current;
66
+ }
@@ -0,0 +1,9 @@
1
+ import { type SeoGenerators } from './config';
2
+ export interface SeoPluginOptions extends Partial<SeoGenerators> {
3
+ /** Document type names to auto-enable SEO on (injects the meta field group). */
4
+ collections?: string[];
5
+ /** Field group the SEO fields go in. Default `'seo'`. */
6
+ group?: string;
7
+ }
8
+ export declare function seoPlugin(options?: SeoPluginOptions): import("@aphexcms/cms-core").CMSPlugin;
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/lib/index.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAgB,KAAK,aAAa,EAAE,MAAM,UAAU,CAAC;AAE5D,MAAM,WAAW,gBAAiB,SAAQ,OAAO,CAAC,aAAa,CAAC;IAC/D,gFAAgF;IAChF,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;IACvB,yDAAyD;IACzD,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAED,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,0CAmCvD"}
package/dist/index.js ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * First-party SEO plugin — feature-comparable to @payloadcms/plugin-seo.
3
+ *
4
+ * `seoPlugin({ collections, generateTitle, ... })`:
5
+ * - `collections` auto-injects the SEO meta field group into those document types
6
+ * (via an aphex/schema/transform part) — you don't add `seoField` by hand.
7
+ * - the `generate*` functions drive the ✨ Generate action and the live search
8
+ * preview.
9
+ *
10
+ * Contributes: a document action (Generate SEO), an admin tool (SEO audit), the
11
+ * length-metered inputs, the search-result preview, a schema transform that
12
+ * desugars the `{ type: 'seo' }` literal, and — when `collections` is set — a
13
+ * second transform that auto-injects SEO on those types. Everything is client-plane
14
+ * except the transforms, which are pure and run on both the engine and the admin.
15
+ */
16
+ import { definePlugin } from '@aphexcms/cms-core';
17
+ import { Sparkles } from '@lucide/svelte';
18
+ import GenerateSeoAction from './GenerateSeoAction.svelte';
19
+ import SeoTool from './SeoTool.svelte';
20
+ import MetaLengthInput from './MetaLengthInput.svelte';
21
+ import SeoPreview from './SeoPreview.svelte';
22
+ import { injectSeoField, expandSeoTypes } from './schema';
23
+ import { configureSeo } from './config';
24
+ export function seoPlugin(options = {}) {
25
+ const { collections, group = 'seo', ...generators } = options;
26
+ configureSeo(generators);
27
+ const parts = [
28
+ {
29
+ implements: 'aphex/document/action',
30
+ id: 'seo.generate',
31
+ title: 'Generate SEO',
32
+ component: GenerateSeoAction,
33
+ appliesTo: collections
34
+ },
35
+ {
36
+ implements: 'aphex/admin/tool',
37
+ id: 'seo',
38
+ title: 'SEO',
39
+ icon: Sparkles,
40
+ component: SeoTool,
41
+ placement: 'sidebar'
42
+ },
43
+ { implements: 'aphex/field/component', input: 'seo-length', component: MetaLengthInput },
44
+ { implements: 'aphex/field/component', input: 'seo-preview', component: SeoPreview },
45
+ // Desugar the `{ type: 'seo' }` literal into the SEO object, everywhere.
46
+ { implements: 'aphex/schema/transform', transform: expandSeoTypes }
47
+ ];
48
+ if (collections && collections.length > 0) {
49
+ parts.push({
50
+ implements: 'aphex/schema/transform',
51
+ transform: (schemas) => schemas.map((s) => (collections.includes(s.name) ? injectSeoField(s, group) : s))
52
+ });
53
+ }
54
+ return definePlugin({ name: '@aphexcms/plugin-seo', version: '0.1.0', parts });
55
+ }
@@ -0,0 +1,52 @@
1
+ import type { Field, SchemaType, BaseField } from '@aphexcms/cms-core';
2
+ /**
3
+ * The SEO plugin's schema contribution — a reusable "SEO & Social" object field.
4
+ *
5
+ * This module is SERVER-SAFE (plain TypeScript, no Svelte components), because it's
6
+ * imported into document schemas which are evaluated on both the server (engine)
7
+ * and the client (admin). The plugin's component parts live in ./index.ts, which
8
+ * must NOT be imported from here.
9
+ *
10
+ * Three ways to add it, all storing the same `seo` object:
11
+ * - `seoPlugin({ collections: ['blog_post'] })` — auto-inject on chosen types.
12
+ * - `{ type: 'seo' }` — the literal. Registering `seoPlugin()` augments core's
13
+ * `FieldTypeMap` (see below) so it's type-safe with no import, and the plugin's
14
+ * schema-transform desugars it into the object.
15
+ * - `seoField('seo')` — the builder, for when you'd rather import it than rely on
16
+ * the ambient type.
17
+ */
18
+ /** The `type` keyword this plugin desugars (authored as `{ type: 'seo' }`). */
19
+ export declare const SEO_TYPE = "seo";
20
+ /**
21
+ * The authored shape of a `{ type: 'seo' }` field. The plugin's schema-transform
22
+ * expands it into the SEO `object` before the engine/codegen see it. Extra props
23
+ * (`name`, `title`, `group`, …) come from `BaseField`.
24
+ */
25
+ export interface SeoField extends BaseField {
26
+ type: 'seo';
27
+ }
28
+ declare module '@aphexcms/cms-core' {
29
+ interface FieldTypeMap {
30
+ seo: SeoField;
31
+ }
32
+ }
33
+ /**
34
+ * The reusable "SEO & Social" object field. Embed it in any document with
35
+ * `seoField('seo')` (or pass a group name), or use the `{ type: 'seo' }` literal.
36
+ */
37
+ export declare function seoField(group?: string): Field;
38
+ /**
39
+ * Schema-transform: desugar every `{ type: 'seo' }` field into the SEO `object`,
40
+ * everywhere in the schema list. Registered as an `aphex/schema/transform` part so
41
+ * it runs in the engine, admin, and type generator alike — the engine never sees a
42
+ * `seo` primitive.
43
+ */
44
+ export declare function expandSeoTypes(schemas: SchemaType[]): SchemaType[];
45
+ /**
46
+ * Inject the SEO field group into a document schema (adds the `seo` field and a
47
+ * `SEO` group tab if absent). Idempotent — a schema that already has a `seo` field
48
+ * is returned untouched. Used by the plugin's schema-transform part to auto-enable
49
+ * SEO on chosen collections, like Payload's `collections: [...]`.
50
+ */
51
+ export declare function injectSeoField(schema: SchemaType, group?: string): SchemaType;
52
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../src/lib/schema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAGvE;;;;;;;;;;;;;;;GAeG;AAEH,+EAA+E;AAC/E,eAAO,MAAM,QAAQ,QAAQ,CAAC;AAE9B;;;;GAIG;AACH,MAAM,WAAW,QAAS,SAAQ,SAAS;IAC1C,IAAI,EAAE,KAAK,CAAC;CACZ;AAKD,OAAO,QAAQ,oBAAoB,CAAC;IACnC,UAAU,YAAY;QACrB,GAAG,EAAE,QAAQ,CAAC;KACd;CACD;AAuED;;;GAGG;AACH,wBAAgB,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,KAAK,CAE9C;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,UAAU,EAAE,GAAG,UAAU,EAAE,CAKlE;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,UAAU,EAAE,KAAK,SAAQ,GAAG,UAAU,CAQ5E"}
package/dist/schema.js ADDED
@@ -0,0 +1,107 @@
1
+ import { desugarFieldType } from '@aphexcms/cms-core';
2
+ /**
3
+ * The SEO plugin's schema contribution — a reusable "SEO & Social" object field.
4
+ *
5
+ * This module is SERVER-SAFE (plain TypeScript, no Svelte components), because it's
6
+ * imported into document schemas which are evaluated on both the server (engine)
7
+ * and the client (admin). The plugin's component parts live in ./index.ts, which
8
+ * must NOT be imported from here.
9
+ *
10
+ * Three ways to add it, all storing the same `seo` object:
11
+ * - `seoPlugin({ collections: ['blog_post'] })` — auto-inject on chosen types.
12
+ * - `{ type: 'seo' }` — the literal. Registering `seoPlugin()` augments core's
13
+ * `FieldTypeMap` (see below) so it's type-safe with no import, and the plugin's
14
+ * schema-transform desugars it into the object.
15
+ * - `seoField('seo')` — the builder, for when you'd rather import it than rely on
16
+ * the ambient type.
17
+ */
18
+ /** The `type` keyword this plugin desugars (authored as `{ type: 'seo' }`). */
19
+ export const SEO_TYPE = 'seo';
20
+ /** Build the "SEO & Social" object field. Everything is optional — the frontend
21
+ * falls back to the document's own title / excerpt / cover image. */
22
+ function buildSeoField(config = {}) {
23
+ const { name = 'seo', title = 'SEO & Social', description = 'Optional. Control how this appears in Google and on social media. Leave blank to use sensible defaults from the fields above.', group } = config;
24
+ return {
25
+ name,
26
+ type: 'object',
27
+ title,
28
+ description,
29
+ ...(group ? { group } : {}),
30
+ fields: [
31
+ {
32
+ name: 'metaTitle',
33
+ type: 'string',
34
+ title: 'Meta title',
35
+ description: 'Overrides the title in search results and social cards. Best around 60 characters.',
36
+ // Render with this plugin's length-metered input (aphex/field/component).
37
+ input: 'seo-length',
38
+ validation: (Rule) => Rule.max(70)
39
+ },
40
+ {
41
+ name: 'metaDescription',
42
+ type: 'text',
43
+ title: 'Meta description',
44
+ rows: 3,
45
+ description: 'The snippet shown under the title in search results. ~155 characters. Falls back to the excerpt.',
46
+ // Length-metered textarea (aphex/field/component).
47
+ input: 'seo-length',
48
+ validation: (Rule) => Rule.max(200)
49
+ },
50
+ {
51
+ name: 'ogImage',
52
+ type: 'image',
53
+ title: 'Social share image',
54
+ description: 'Shown when this is shared on social media. Ideally 1200×630. Falls back to the cover image.'
55
+ },
56
+ {
57
+ name: 'noIndex',
58
+ type: 'boolean',
59
+ title: 'Hide from search engines',
60
+ description: 'Stops Google and others from indexing this page (it stays publicly reachable).'
61
+ },
62
+ {
63
+ // UI-only: renders a live Google-style search-result preview.
64
+ name: 'seoPreview',
65
+ type: 'string',
66
+ title: 'Search preview',
67
+ input: 'seo-preview'
68
+ }
69
+ ]
70
+ };
71
+ }
72
+ /**
73
+ * The reusable "SEO & Social" object field. Embed it in any document with
74
+ * `seoField('seo')` (or pass a group name), or use the `{ type: 'seo' }` literal.
75
+ */
76
+ export function seoField(group) {
77
+ return buildSeoField({ group });
78
+ }
79
+ /**
80
+ * Schema-transform: desugar every `{ type: 'seo' }` field into the SEO `object`,
81
+ * everywhere in the schema list. Registered as an `aphex/schema/transform` part so
82
+ * it runs in the engine, admin, and type generator alike — the engine never sees a
83
+ * `seo` primitive.
84
+ */
85
+ export function expandSeoTypes(schemas) {
86
+ return desugarFieldType(schemas, {
87
+ type: SEO_TYPE,
88
+ build: (f) => buildSeoField({ name: f.name, title: f.title })
89
+ });
90
+ }
91
+ /**
92
+ * Inject the SEO field group into a document schema (adds the `seo` field and a
93
+ * `SEO` group tab if absent). Idempotent — a schema that already has a `seo` field
94
+ * is returned untouched. Used by the plugin's schema-transform part to auto-enable
95
+ * SEO on chosen collections, like Payload's `collections: [...]`.
96
+ */
97
+ export function injectSeoField(schema, group = 'seo') {
98
+ if (schema.type !== 'document')
99
+ return schema;
100
+ if (schema.fields.some((f) => f.name === 'seo'))
101
+ return schema;
102
+ const groups = schema.groups ?? [];
103
+ const withGroup = groups.some((g) => g.name === group)
104
+ ? groups
105
+ : [...groups, { name: group, title: 'SEO' }];
106
+ return { ...schema, groups: withGroup, fields: [...schema.fields, seoField(group)] };
107
+ }
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@aphexcms/plugin-seo",
3
+ "version": "0.0.0",
4
+ "description": "SEO plugin for AphexCMS — meta fields, auto-generation, length metering, live search preview, and an audit tool",
5
+ "license": "MIT",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "https://github.com/IcelandicIcecream/aphex.git",
12
+ "directory": "plugins/plugin-seo"
13
+ },
14
+ "type": "module",
15
+ "main": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "svelte": "./dist/index.js",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "svelte": "./dist/index.js",
22
+ "default": "./dist/index.js"
23
+ },
24
+ "./schema": {
25
+ "types": "./dist/schema.d.ts",
26
+ "default": "./dist/schema.js"
27
+ }
28
+ },
29
+ "files": [
30
+ "dist"
31
+ ],
32
+ "scripts": {
33
+ "dev": "tsc --watch --preserveWatchOutput",
34
+ "build": "svelte-package",
35
+ "check": "svelte-check --tsconfig ./tsconfig.json",
36
+ "dev:local": "node ../../scripts/swap-package-paths.js ./package.json src lib",
37
+ "prepack": "node ../../scripts/swap-package-paths.js ./package.json dist lib",
38
+ "postpack": "node ../../scripts/swap-package-paths.js ./package.json src lib"
39
+ },
40
+ "keywords": [
41
+ "aphex",
42
+ "aphexcms",
43
+ "cms",
44
+ "plugin",
45
+ "seo"
46
+ ],
47
+ "devDependencies": {
48
+ "@sveltejs/package": "^2.5.6",
49
+ "svelte": "^5.0.0",
50
+ "svelte-check": "^4.0.0",
51
+ "typescript": "^5.9.3"
52
+ },
53
+ "peerDependencies": {
54
+ "@aphexcms/cms-core": "workspace:^",
55
+ "@aphexcms/ui": "workspace:^",
56
+ "@lucide/svelte": "^0.554.0",
57
+ "svelte": "^5.0.0",
58
+ "svelte-sonner": "^1.0.7"
59
+ }
60
+ }