@easy-cms/plugin-seo 0.13.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 +21 -0
- package/README.md +29 -0
- package/dist/admin.js +52 -0
- package/dist/index.d.ts +161 -0
- package/dist/index.js +236 -0
- package/package.json +50 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kanawoot K.
|
|
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
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# @easy-cms/plugin-seo
|
|
2
|
+
|
|
3
|
+
SEO for [Easy CMS](https://maritonx.github.io/easy-cms/): a `meta` group (title, description,
|
|
4
|
+
share image) on the collections and globals you choose, with length meters, a search result
|
|
5
|
+
preview and Generate buttons in the admin, and page metadata for Nuxt and Next.js.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { seoPlugin } from '@easy-cms/plugin-seo'
|
|
9
|
+
|
|
10
|
+
export default defineConfig({
|
|
11
|
+
// …
|
|
12
|
+
plugins: [
|
|
13
|
+
seoPlugin({
|
|
14
|
+
collections: ['posts'],
|
|
15
|
+
generateTitle: ({ doc }) => `${doc.title} | My Blog`,
|
|
16
|
+
generateDescription: ({ doc }) => doc.excerpt,
|
|
17
|
+
}),
|
|
18
|
+
],
|
|
19
|
+
})
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
import { seoMeta } from '@easy-cms/plugin-seo'
|
|
24
|
+
|
|
25
|
+
useSeoMeta(seoMeta(post, { url: `/posts/${post.slug}` }).nuxt) // Nuxt
|
|
26
|
+
return seoMeta(post, { config, url: `/posts/${post.slug}` }).next // Next.js generateMetadata()
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
See [SEO](https://maritonx.github.io/easy-cms/guide/seo).
|
package/dist/admin.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
var f="/seo/generate";var v=["value","path","doc","collection","global","id","locale","uiLocale","readOnly","options","api"],b={en:{characters:"{n} / {max} characters",empty:"Empty: search engines pick text from the page",short:"Short: aim for {min}\u2013{max}",good:"Good length",long:"Too long: may be cut off after {max}",generate:"Generate",generating:"Generating\u2026",generateImage:"Use image from content",noValue:"Nothing to generate from yet",failed:"Could not generate: {message}",preview:"Search result preview",noTitle:"Page title",noDescription:"Add a description to control the text under the title."},th:{characters:"{n} / {max} \u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",empty:"\u0E27\u0E48\u0E32\u0E07: \u0E40\u0E04\u0E23\u0E37\u0E48\u0E2D\u0E07\u0E21\u0E37\u0E2D\u0E04\u0E49\u0E19\u0E2B\u0E32\u0E08\u0E30\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E08\u0E32\u0E01\u0E2B\u0E19\u0E49\u0E32\u0E40\u0E2D\u0E07",short:"\u0E2A\u0E31\u0E49\u0E19\u0E44\u0E1B: \u0E04\u0E27\u0E23\u0E22\u0E32\u0E27 {min}\u2013{max}",good:"\u0E04\u0E27\u0E32\u0E21\u0E22\u0E32\u0E27\u0E1E\u0E2D\u0E14\u0E35",long:"\u0E22\u0E32\u0E27\u0E44\u0E1B: \u0E2D\u0E32\u0E08\u0E16\u0E39\u0E01\u0E15\u0E31\u0E14\u0E2B\u0E25\u0E31\u0E07 {max}",generate:"\u0E2A\u0E23\u0E49\u0E32\u0E07\u0E43\u0E2B\u0E49",generating:"\u0E01\u0E33\u0E25\u0E31\u0E07\u0E2A\u0E23\u0E49\u0E32\u0E07\u2026",generateImage:"\u0E43\u0E0A\u0E49\u0E23\u0E39\u0E1B\u0E08\u0E32\u0E01\u0E40\u0E19\u0E37\u0E49\u0E2D\u0E2B\u0E32",noValue:"\u0E22\u0E31\u0E07\u0E44\u0E21\u0E48\u0E21\u0E35\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E43\u0E2B\u0E49\u0E2A\u0E23\u0E49\u0E32\u0E07",failed:"\u0E2A\u0E23\u0E49\u0E32\u0E07\u0E44\u0E21\u0E48\u0E2A\u0E33\u0E40\u0E23\u0E47\u0E08: {message}",preview:"\u0E15\u0E31\u0E27\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E1C\u0E25\u0E01\u0E32\u0E23\u0E04\u0E49\u0E19\u0E2B\u0E32",noTitle:"\u0E0A\u0E37\u0E48\u0E2D\u0E2B\u0E19\u0E49\u0E32",noDescription:"\u0E40\u0E1E\u0E34\u0E48\u0E21\u0E04\u0E33\u0E2D\u0E18\u0E34\u0E1A\u0E32\u0E22\u0E40\u0E1E\u0E37\u0E48\u0E2D\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E43\u0E15\u0E49\u0E0A\u0E37\u0E48\u0E2D\u0E2B\u0E19\u0E49\u0E32"}},i=r=>r.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e]);function y(r){if(typeof Intl.Segmenter!="function")return[...r].length;let e=0;for(let t of new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(r))e++;return e}function x(r,e){let t=[...r];return t.length>e?`${t.slice(0,e-1).join("").trimEnd()}\u2026`:r}var w=`
|
|
2
|
+
:host { display: block; font: inherit; color: var(--text); }
|
|
3
|
+
.row { display: flex; align-items: center; gap: 0.75rem; flex-wrap: wrap; }
|
|
4
|
+
.hint { margin: 0; font-size: 0.8rem; color: var(--text-muted); }
|
|
5
|
+
.error { margin: 0.35rem 0 0; font-size: 0.8rem; color: var(--danger); }
|
|
6
|
+
p.hint { margin-top: 0.35rem; }
|
|
7
|
+
button {
|
|
8
|
+
display: inline-flex; align-items: center; gap: 0.35rem; min-height: 1.9rem; padding: 0 0.7rem;
|
|
9
|
+
border: 1px solid var(--border-strong); border-radius: var(--radius-sm, 8px);
|
|
10
|
+
background: var(--surface); color: var(--text); font: inherit; font-size: 0.8rem; font-weight: 500;
|
|
11
|
+
cursor: pointer;
|
|
12
|
+
}
|
|
13
|
+
button:hover:not(:disabled) { background: var(--surface-2); }
|
|
14
|
+
button:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
|
|
15
|
+
button:disabled { opacity: 0.6; cursor: default; }
|
|
16
|
+
`,d=class r extends HTMLElement{ctx={value:void 0,path:void 0,doc:{},collection:void 0,global:void 0,id:null,locale:null,uiLocale:"en",readOnly:!1,options:{},api:void 0};busy=!1;notice=null;queued=!1;html="";constructor(){super(),this.attachShadow({mode:"open"}).addEventListener("click",t=>{let n=t.target.closest("[data-action]")?.getAttribute("data-action");n&&this.onAction(n)})}static{for(let e of v)Object.defineProperty(r.prototype,e,{get(){return this.ctx[e]},set(t){this.ctx[e]=t,this.update()}})}connectedCallback(){this.update()}t(e,t={}){return(this.ctx.uiLocale==="th"?b.th:b.en)[e].replace(/\{(\w+)\}/g,(o,c)=>String(t[c]??""))}update(){this.queued||(this.queued=!0,queueMicrotask(()=>{this.queued=!1;let e=this.shadowRoot;if(!e)return;let t=`<style>${w}${this.css()}</style>${this.render()}`;if(t===this.html)return;let n=e.activeElement?.getAttribute("data-action");this.html=t,e.innerHTML=t,n&&e.querySelector(`[data-action="${n}"]`)?.focus()}))}async generate(e){let{api:t,collection:n,global:o,id:c,doc:s,locale:a}=this.ctx;return t?(await t("POST",f,{kind:e,...n?{collection:n}:{},...o?{global:o}:{},id:c,doc:s,locale:a})).value??null:null}async generateInto(e,t){if(!(!t||this.busy)){this.busy=!0,this.notice=null,this.update();try{let n=await this.generate(e);n===null||n===""?this.notice={text:this.t("noValue"),error:!1}:this.dispatchEvent(new CustomEvent("set-field",{detail:{path:t,value:n}}))}catch(n){this.notice={text:this.t("failed",{message:n.message}),error:!0}}finally{this.busy=!1,this.update()}}}renderNotice(){if(!this.notice)return"";let{text:e,error:t}=this.notice;return t?`<p class="error" role="alert">${i(e)}</p>`:`<p class="hint" role="status">${i(e)}</p>`}onAction(e){}css(){return""}},p=class extends d{css(){return`
|
|
17
|
+
.bar { flex: 1 1 8rem; height: 4px; border-radius: 2px; background: var(--surface-2); overflow: hidden; }
|
|
18
|
+
.fill { height: 100%; border-radius: 2px; }
|
|
19
|
+
.empty .fill { background: var(--border-strong); }
|
|
20
|
+
.short .fill { background: var(--warning-text); }
|
|
21
|
+
.good .fill { background: var(--ok); }
|
|
22
|
+
.long .fill { background: var(--danger); }
|
|
23
|
+
.long .state { color: var(--danger); }
|
|
24
|
+
.good .state { color: var(--ok); }
|
|
25
|
+
`}render(){let{kind:e,min:t,max:n,generate:o}=this.ctx.options,c=typeof this.ctx.value=="string"?this.ctx.value:"",s=y(c.trim()),a=s===0?"empty":s<t?"short":s>n?"long":"good",l=Math.min(100,Math.round(s/n*100)),u=o&&!this.ctx.readOnly?`<button type="button" data-action="generate" ${this.busy?"disabled":""}>${i(this.t(this.busy?"generating":"generate"))}</button>`:"";return`
|
|
26
|
+
<div class="row ${a}" data-kind="${i(e)}" data-state="${a}">
|
|
27
|
+
<div class="bar" aria-hidden="true"><div class="fill" style="width:${l}%"></div></div>
|
|
28
|
+
<span class="hint">${i(this.t("characters",{n:s,max:n}))}</span>
|
|
29
|
+
<span class="hint state">${i(this.t(a,{min:t,max:n}))}</span>
|
|
30
|
+
${u}
|
|
31
|
+
</div>
|
|
32
|
+
${this.renderNotice()}
|
|
33
|
+
`}onAction(e){if(e==="generate"){let{kind:t}=this.ctx.options;return this.generateInto(t,this.ctx.path)}}},g=class extends d{render(){let{generate:e}=this.ctx.options;return!e||this.ctx.readOnly?"":`
|
|
34
|
+
<div class="row">
|
|
35
|
+
<button type="button" data-action="generate" ${this.busy?"disabled":""}>${i(this.t(this.busy?"generating":"generateImage"))}</button>
|
|
36
|
+
</div>
|
|
37
|
+
${this.renderNotice()}
|
|
38
|
+
`}onAction(e){if(e==="generate")return this.generateInto("image",this.ctx.path)}},h=class extends d{url="";urlFor="";timer;css(){return`
|
|
39
|
+
.card { padding: 0.9rem 1rem; border: 1px solid var(--border); border-radius: var(--radius-sm, 8px); background: var(--surface); }
|
|
40
|
+
.label { margin: 0 0 0.5rem; font-size: 0.75rem; font-weight: 600; letter-spacing: 0.02em; text-transform: uppercase; color: var(--text-muted); }
|
|
41
|
+
.url { margin: 0; font-size: 0.8rem; color: var(--text-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
42
|
+
.title { margin: 0.15rem 0; font-size: 1.15rem; line-height: 1.3; color: var(--info); }
|
|
43
|
+
.description { margin: 0; font-size: 0.875rem; line-height: 1.5; color: var(--text-muted); }
|
|
44
|
+
.placeholder { font-style: italic; opacity: 0.75; }
|
|
45
|
+
`}render(){let{titleField:e,url:t,siteUrl:n}=this.ctx.options,o=k(this.ctx.doc,this.ctx.path)??{},c=e?this.ctx.doc[e]:void 0,s=[o.title,c].find(u=>typeof u=="string"&&u.trim()),a=typeof o.description=="string"?o.description.trim():"";t&&this.refreshUrl();let l=E(t?this.url:n);return`
|
|
46
|
+
<section class="card" aria-label="${i(this.t("preview"))}">
|
|
47
|
+
<p class="label">${i(this.t("preview"))}</p>
|
|
48
|
+
${l?`<p class="url">${i(l)}</p>`:""}
|
|
49
|
+
<p class="title ${s?"":"placeholder"}">${i(x(s??this.t("noTitle"),60))}</p>
|
|
50
|
+
<p class="description ${a?"":"placeholder"}">${i(a?x(a,160):this.t("noDescription"))}</p>
|
|
51
|
+
</section>
|
|
52
|
+
`}refreshUrl(){let e=JSON.stringify([this.ctx.doc,this.ctx.locale]);e!==this.urlFor&&(this.urlFor=e,clearTimeout(this.timer),this.timer=setTimeout(async()=>{try{let t=await this.generate("url"),n=typeof t=="string"?t:"";n!==this.url&&(this.url=n,this.update())}catch{}},400))}};function k(r,e){if(e)return e.split(".").reduce((t,n)=>typeof t=="object"&&t!==null?t[n]:void 0,r)}function E(r){if(!r)return"";try{let{host:e,pathname:t}=new URL(r,"https://site.invalid"),n=t.split("/").filter(Boolean).map(decodeURIComponent);return[e==="site.invalid"?"":e,...n].filter(Boolean).join(" \u203A ")}catch{return r}}var m=(r,e)=>{customElements.get(r)||customElements.define(r,e)};m("ecms-seo-meter",p);m("ecms-seo-image",g);m("ecms-seo-preview",h);
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { EasyCMS, AuthUser, Field, Label, Plugin } from '@easy-cms/core';
|
|
2
|
+
|
|
3
|
+
type Doc = Record<string, unknown>;
|
|
4
|
+
interface SeoMetaOptions {
|
|
5
|
+
/**
|
|
6
|
+
* The site's public address, to make the canonical and image URLs absolute, e.g.
|
|
7
|
+
* `https://example.com`. Default: `config.admin.siteUrl`, then `config.serverURL`.
|
|
8
|
+
*/
|
|
9
|
+
readonly siteUrl?: string;
|
|
10
|
+
/** Your Easy CMS config, to read `admin.siteUrl` (and `serverURL`) from. */
|
|
11
|
+
readonly config?: {
|
|
12
|
+
readonly admin?: {
|
|
13
|
+
readonly siteUrl?: string;
|
|
14
|
+
};
|
|
15
|
+
readonly serverURL?: string;
|
|
16
|
+
};
|
|
17
|
+
/** The page's canonical address: absolute, or a path on the site. */
|
|
18
|
+
readonly url?: string | ((doc: Doc) => string | null | undefined);
|
|
19
|
+
/** The title when `meta.title` is empty. Default: the document's `title`. */
|
|
20
|
+
readonly title?: (doc: Doc) => string | null | undefined;
|
|
21
|
+
/** The description when `meta.description` is empty. Default: `excerpt`, then `description`. */
|
|
22
|
+
readonly description?: (doc: Doc) => string | null | undefined;
|
|
23
|
+
/** Shown as `og:site_name`. */
|
|
24
|
+
readonly siteName?: string;
|
|
25
|
+
}
|
|
26
|
+
interface SeoImage {
|
|
27
|
+
readonly url: string;
|
|
28
|
+
readonly alt?: string;
|
|
29
|
+
readonly width?: number;
|
|
30
|
+
readonly height?: number;
|
|
31
|
+
}
|
|
32
|
+
/** Keys of Nuxt's `useSeoMeta()` that `seoMeta` fills. */
|
|
33
|
+
interface NuxtSeoMeta {
|
|
34
|
+
title?: string;
|
|
35
|
+
description?: string;
|
|
36
|
+
ogTitle?: string;
|
|
37
|
+
ogDescription?: string;
|
|
38
|
+
ogUrl?: string;
|
|
39
|
+
ogType?: 'website';
|
|
40
|
+
ogSiteName?: string;
|
|
41
|
+
ogImage?: string;
|
|
42
|
+
ogImageAlt?: string;
|
|
43
|
+
ogImageWidth?: number;
|
|
44
|
+
ogImageHeight?: number;
|
|
45
|
+
twitterCard?: 'summary' | 'summary_large_image';
|
|
46
|
+
twitterTitle?: string;
|
|
47
|
+
twitterDescription?: string;
|
|
48
|
+
twitterImage?: string;
|
|
49
|
+
}
|
|
50
|
+
/** The part of Next.js `Metadata` that `seoMeta` fills. */
|
|
51
|
+
interface NextSeoMetadata {
|
|
52
|
+
title?: string;
|
|
53
|
+
description?: string;
|
|
54
|
+
alternates?: {
|
|
55
|
+
canonical: string;
|
|
56
|
+
};
|
|
57
|
+
openGraph: {
|
|
58
|
+
type: 'website';
|
|
59
|
+
title?: string;
|
|
60
|
+
description?: string;
|
|
61
|
+
url?: string;
|
|
62
|
+
siteName?: string;
|
|
63
|
+
images?: SeoImage[];
|
|
64
|
+
};
|
|
65
|
+
twitter: {
|
|
66
|
+
card: 'summary' | 'summary_large_image';
|
|
67
|
+
title?: string;
|
|
68
|
+
description?: string;
|
|
69
|
+
images?: string[];
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
interface SeoMeta {
|
|
73
|
+
readonly title: string | undefined;
|
|
74
|
+
readonly description: string | undefined;
|
|
75
|
+
readonly canonical: string | undefined;
|
|
76
|
+
readonly image: SeoImage | undefined;
|
|
77
|
+
/** For Nuxt's `useSeoMeta()`. Add the canonical link with `useHead()`. */
|
|
78
|
+
readonly nuxt: NuxtSeoMeta;
|
|
79
|
+
/** For Next.js `generateMetadata()`. */
|
|
80
|
+
readonly next: NextSeoMetadata;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Page metadata from a document with SEO fields: the meta values, or fallbacks from the
|
|
84
|
+
* document. Fetch the document with `depth` 1 or more so the share image has its URL.
|
|
85
|
+
*
|
|
86
|
+
* ```ts
|
|
87
|
+
* const meta = seoMeta(post, { config, url: `/posts/${post.slug}` })
|
|
88
|
+
* useSeoMeta(meta.nuxt) // Nuxt
|
|
89
|
+
* return meta.next // Next.js generateMetadata()
|
|
90
|
+
* ```
|
|
91
|
+
*/
|
|
92
|
+
declare function seoMeta(doc: Doc, options?: SeoMetaOptions): SeoMeta;
|
|
93
|
+
|
|
94
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
95
|
+
interface GenerateArgs {
|
|
96
|
+
/** The document as edited in the admin (not saved yet), or as saved with `autoGenerate`. */
|
|
97
|
+
readonly doc: Record<string, unknown>;
|
|
98
|
+
/** The document's id; `null` while it is being created. */
|
|
99
|
+
readonly id: string | number | null;
|
|
100
|
+
/** The content locale being edited; `null` without localization or when saving. */
|
|
101
|
+
readonly locale: string | null;
|
|
102
|
+
/** Slug of the collection, when the document is in one. */
|
|
103
|
+
readonly collection?: string;
|
|
104
|
+
/** Slug of the global, when the document is a global. */
|
|
105
|
+
readonly global?: string;
|
|
106
|
+
readonly cms: EasyCMS;
|
|
107
|
+
readonly user: AuthUser | null;
|
|
108
|
+
}
|
|
109
|
+
type Generate<T> = (args: GenerateArgs) => MaybePromise<T | null | undefined>;
|
|
110
|
+
interface SeoPluginOptions {
|
|
111
|
+
/** Collections that get SEO fields, by slug. */
|
|
112
|
+
readonly collections?: readonly string[];
|
|
113
|
+
/** Globals that get SEO fields, by slug. */
|
|
114
|
+
readonly globals?: readonly string[];
|
|
115
|
+
/** `main`: below the other fields (room for the search preview). `sidebar`: the side column. Default `main`. */
|
|
116
|
+
readonly position?: 'main' | 'sidebar';
|
|
117
|
+
/** Suggests a meta title, e.g. `({ doc }) => \`${doc.title} | My Blog\``. Adds a Generate button. */
|
|
118
|
+
readonly generateTitle?: Generate<string>;
|
|
119
|
+
/** Suggests a meta description, e.g. from an excerpt. Adds a Generate button. */
|
|
120
|
+
readonly generateDescription?: Generate<string>;
|
|
121
|
+
/** Suggests a share image: the id of a media document, e.g. the post's cover. */
|
|
122
|
+
readonly generateImage?: Generate<string | number>;
|
|
123
|
+
/** The page's address (absolute, or a path on `admin.siteUrl`), shown in the search preview. */
|
|
124
|
+
readonly generateURL?: Generate<string>;
|
|
125
|
+
/** Fill empty meta fields with the generators when a document is saved. Default false. */
|
|
126
|
+
readonly autoGenerate?: boolean;
|
|
127
|
+
/** Changes the fields of the group, e.g. `(defaults) => [...defaults, noindexField]`. */
|
|
128
|
+
readonly fields?: (defaults: Field[]) => Field[];
|
|
129
|
+
/** Length the admin marks as good for titles. Default 50–60 characters. */
|
|
130
|
+
readonly titleLength?: {
|
|
131
|
+
readonly min: number;
|
|
132
|
+
readonly max: number;
|
|
133
|
+
};
|
|
134
|
+
/** Length the admin marks as good for descriptions. Default 100–150 characters. */
|
|
135
|
+
readonly descriptionLength?: {
|
|
136
|
+
readonly min: number;
|
|
137
|
+
readonly max: number;
|
|
138
|
+
};
|
|
139
|
+
/** One value per content locale. Default: true when the config has `localization`. */
|
|
140
|
+
readonly localized?: boolean;
|
|
141
|
+
/** Label of the group. Default "SEO". */
|
|
142
|
+
readonly label?: Label;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Adds a `meta` group (title, description, image) to the chosen collections and globals,
|
|
146
|
+
* with length meters, a search result preview and Generate buttons in the admin.
|
|
147
|
+
*/
|
|
148
|
+
declare function seoPlugin(options?: SeoPluginOptions): Plugin;
|
|
149
|
+
|
|
150
|
+
/** Shared by the server plugin and the admin module (which must not import anything else). */
|
|
151
|
+
/** Length ranges search engines show in full, from Payload's SEO plugin and Google's guidance. */
|
|
152
|
+
declare const DEFAULT_TITLE_LENGTH: {
|
|
153
|
+
readonly min: 50;
|
|
154
|
+
readonly max: 60;
|
|
155
|
+
};
|
|
156
|
+
declare const DEFAULT_DESCRIPTION_LENGTH: {
|
|
157
|
+
readonly min: 100;
|
|
158
|
+
readonly max: 150;
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
export { DEFAULT_DESCRIPTION_LENGTH, DEFAULT_TITLE_LENGTH, type Generate, type GenerateArgs, type NextSeoMetadata, type NuxtSeoMeta, type SeoImage, type SeoMeta, type SeoMetaOptions, type SeoPluginOptions, seoMeta, seoPlugin };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
// src/shared.ts
|
|
2
|
+
var DEFAULT_TITLE_LENGTH = { min: 50, max: 60 };
|
|
3
|
+
var DEFAULT_DESCRIPTION_LENGTH = { min: 100, max: 150 };
|
|
4
|
+
var META_FIELD = "meta";
|
|
5
|
+
var GENERATE_PATH = "/seo/generate";
|
|
6
|
+
var GENERATE_KINDS = ["title", "description", "image", "url"];
|
|
7
|
+
|
|
8
|
+
// src/meta.ts
|
|
9
|
+
var text = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
|
|
10
|
+
function absolute(url, site) {
|
|
11
|
+
if (/^https?:\/\//.test(url) || !site || !/^https?:\/\//.test(site)) return url;
|
|
12
|
+
return `${site.replace(/\/+$/, "")}/${url.replace(/^\/+/, "")}`;
|
|
13
|
+
}
|
|
14
|
+
function seoMeta(doc, options = {}) {
|
|
15
|
+
const meta = doc[META_FIELD] ?? {};
|
|
16
|
+
const site = options.siteUrl ?? options.config?.admin?.siteUrl ?? options.config?.serverURL;
|
|
17
|
+
const title = text(meta.title) ?? text((options.title ?? ((d) => d.title))(doc));
|
|
18
|
+
const description = text(meta.description) ?? text((options.description ?? ((d) => d.excerpt ?? d.description))(doc));
|
|
19
|
+
const url = typeof options.url === "function" ? options.url(doc) : options.url;
|
|
20
|
+
const canonical = text(url) ? absolute(text(url), site) : void 0;
|
|
21
|
+
const media = meta.image;
|
|
22
|
+
const image = typeof media === "object" && media !== null && text(media.url) ? {
|
|
23
|
+
url: absolute(text(media.url), site),
|
|
24
|
+
...text(media.alt) ? { alt: text(media.alt) } : {},
|
|
25
|
+
...typeof media.width === "number" ? { width: media.width } : {},
|
|
26
|
+
...typeof media.height === "number" ? { height: media.height } : {}
|
|
27
|
+
} : void 0;
|
|
28
|
+
const defined = (record) => Object.fromEntries(Object.entries(record).filter(([, v]) => v !== void 0));
|
|
29
|
+
const card = image ? "summary_large_image" : "summary";
|
|
30
|
+
return {
|
|
31
|
+
title,
|
|
32
|
+
description,
|
|
33
|
+
canonical,
|
|
34
|
+
image,
|
|
35
|
+
nuxt: defined({
|
|
36
|
+
title,
|
|
37
|
+
description,
|
|
38
|
+
ogTitle: title,
|
|
39
|
+
ogDescription: description,
|
|
40
|
+
ogUrl: canonical,
|
|
41
|
+
ogType: "website",
|
|
42
|
+
ogSiteName: options.siteName,
|
|
43
|
+
ogImage: image?.url,
|
|
44
|
+
ogImageAlt: image?.alt,
|
|
45
|
+
ogImageWidth: image?.width,
|
|
46
|
+
ogImageHeight: image?.height,
|
|
47
|
+
twitterCard: card,
|
|
48
|
+
twitterTitle: title,
|
|
49
|
+
twitterDescription: description,
|
|
50
|
+
twitterImage: image?.url
|
|
51
|
+
}),
|
|
52
|
+
next: defined({
|
|
53
|
+
title,
|
|
54
|
+
description,
|
|
55
|
+
alternates: canonical ? { canonical } : void 0,
|
|
56
|
+
openGraph: defined({
|
|
57
|
+
title,
|
|
58
|
+
description,
|
|
59
|
+
url: canonical,
|
|
60
|
+
siteName: options.siteName,
|
|
61
|
+
type: "website",
|
|
62
|
+
images: image ? [image] : void 0
|
|
63
|
+
}),
|
|
64
|
+
twitter: defined({
|
|
65
|
+
card,
|
|
66
|
+
title,
|
|
67
|
+
description,
|
|
68
|
+
images: image ? [image.url] : void 0
|
|
69
|
+
})
|
|
70
|
+
})
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// src/plugin.ts
|
|
75
|
+
var ADMIN_MODULE = "@easy-cms/plugin-seo/admin";
|
|
76
|
+
var TEXT_KINDS = ["title", "description"];
|
|
77
|
+
function seoPlugin(options = {}) {
|
|
78
|
+
return (config) => {
|
|
79
|
+
const collections = options.collections ?? [];
|
|
80
|
+
const globals = options.globals ?? [];
|
|
81
|
+
const known = (list, slugs, kind) => {
|
|
82
|
+
const missing = slugs.filter((slug) => !list?.some((c) => c.slug === slug));
|
|
83
|
+
if (missing.length > 0)
|
|
84
|
+
throw new Error(`seoPlugin: unknown ${kind} ${missing.map((s) => `"${s}"`).join(", ")}`);
|
|
85
|
+
};
|
|
86
|
+
known(config.collections, collections, "collection");
|
|
87
|
+
known(config.globals, globals, "global");
|
|
88
|
+
const localized = options.localized ?? !!config.localization;
|
|
89
|
+
const generators = {
|
|
90
|
+
title: options.generateTitle,
|
|
91
|
+
description: options.generateDescription,
|
|
92
|
+
image: options.generateImage,
|
|
93
|
+
url: options.generateURL
|
|
94
|
+
};
|
|
95
|
+
const group = (titleField) => {
|
|
96
|
+
const meter = (kind, range) => ({
|
|
97
|
+
tag: "ecms-seo-meter",
|
|
98
|
+
props: {
|
|
99
|
+
kind,
|
|
100
|
+
min: range.min,
|
|
101
|
+
max: range.max,
|
|
102
|
+
generate: !!generators[kind]
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
const defaults = [
|
|
106
|
+
{
|
|
107
|
+
name: "title",
|
|
108
|
+
type: "text",
|
|
109
|
+
label: { en: "Meta title", th: "\u0E0A\u0E37\u0E48\u0E2D\u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E04\u0E49\u0E19\u0E2B\u0E32" },
|
|
110
|
+
...localized ? { localized: true } : {},
|
|
111
|
+
admin: { after: [meter("title", options.titleLength ?? DEFAULT_TITLE_LENGTH)] }
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
name: "description",
|
|
115
|
+
type: "textarea",
|
|
116
|
+
label: { en: "Meta description", th: "\u0E04\u0E33\u0E2D\u0E18\u0E34\u0E1A\u0E32\u0E22\u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E04\u0E49\u0E19\u0E2B\u0E32" },
|
|
117
|
+
...localized ? { localized: true } : {},
|
|
118
|
+
admin: {
|
|
119
|
+
after: [meter("description", options.descriptionLength ?? DEFAULT_DESCRIPTION_LENGTH)]
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
name: "image",
|
|
124
|
+
type: "upload",
|
|
125
|
+
label: { en: "Share image", th: "\u0E23\u0E39\u0E1B\u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E41\u0E0A\u0E23\u0E4C" },
|
|
126
|
+
...generators.image ? {
|
|
127
|
+
admin: {
|
|
128
|
+
after: [
|
|
129
|
+
{ tag: "ecms-seo-image", props: { generate: true } }
|
|
130
|
+
]
|
|
131
|
+
}
|
|
132
|
+
} : {}
|
|
133
|
+
}
|
|
134
|
+
];
|
|
135
|
+
return {
|
|
136
|
+
name: META_FIELD,
|
|
137
|
+
type: "group",
|
|
138
|
+
label: options.label ?? "SEO",
|
|
139
|
+
...options.position === "sidebar" ? { position: "sidebar" } : {},
|
|
140
|
+
fields: options.fields ? options.fields(defaults) : defaults,
|
|
141
|
+
admin: {
|
|
142
|
+
after: [
|
|
143
|
+
{
|
|
144
|
+
tag: "ecms-seo-preview",
|
|
145
|
+
props: {
|
|
146
|
+
titleField,
|
|
147
|
+
url: !!generators.url,
|
|
148
|
+
siteUrl: config.admin?.siteUrl ?? ""
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
]
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
};
|
|
155
|
+
const hook = options.autoGenerate ? async ({ data, operation, originalDoc, cms, user, slug }) => {
|
|
156
|
+
if (operation === "update" && data[META_FIELD] === void 0) return data;
|
|
157
|
+
const saved = originalDoc?.[META_FIELD] ?? {};
|
|
158
|
+
const meta = { ...saved, ...data[META_FIELD] ?? {} };
|
|
159
|
+
const doc = { ...originalDoc, ...data };
|
|
160
|
+
const target = globals.includes(slug) ? { global: slug } : { collection: slug };
|
|
161
|
+
for (const kind of [...TEXT_KINDS, "image"]) {
|
|
162
|
+
const generate = generators[kind];
|
|
163
|
+
if (!generate || !isEmpty(meta[kind])) continue;
|
|
164
|
+
const id = originalDoc?.id ?? null;
|
|
165
|
+
const value = await generate({ doc, id, locale: null, cms, user, ...target });
|
|
166
|
+
if (value !== null && value !== void 0 && value !== "") meta[kind] = value;
|
|
167
|
+
}
|
|
168
|
+
return { ...data, [META_FIELD]: meta };
|
|
169
|
+
} : void 0;
|
|
170
|
+
const withSeo = (container, titleField) => {
|
|
171
|
+
if (container.fields.some((f) => f.name === META_FIELD))
|
|
172
|
+
throw new Error(`seoPlugin: "${container.slug}" already has a field named "${META_FIELD}"`);
|
|
173
|
+
return {
|
|
174
|
+
...container,
|
|
175
|
+
fields: [...container.fields, group(titleField)],
|
|
176
|
+
...hook ? {
|
|
177
|
+
hooks: {
|
|
178
|
+
...container.hooks,
|
|
179
|
+
beforeChange: [...container.hooks?.beforeChange ?? [], hook]
|
|
180
|
+
}
|
|
181
|
+
} : {}
|
|
182
|
+
};
|
|
183
|
+
};
|
|
184
|
+
const endpoint = {
|
|
185
|
+
path: GENERATE_PATH,
|
|
186
|
+
method: "post",
|
|
187
|
+
handler: async ({ json, user, cms }) => {
|
|
188
|
+
if (!user) return error(401, "Log in to generate SEO values");
|
|
189
|
+
const body = await json();
|
|
190
|
+
const kind = body.kind;
|
|
191
|
+
if (!GENERATE_KINDS.includes(kind))
|
|
192
|
+
return error(400, `kind must be one of ${GENERATE_KINDS.join(", ")}`);
|
|
193
|
+
const collection = typeof body.collection === "string" ? body.collection : void 0;
|
|
194
|
+
const global = typeof body.global === "string" ? body.global : void 0;
|
|
195
|
+
if (!(collection && collections.includes(collection)) && !(global && globals.includes(global)))
|
|
196
|
+
return error(404, "No SEO fields on this collection or global");
|
|
197
|
+
const generate = generators[kind];
|
|
198
|
+
if (!generate) return error(404, `No generator for "${kind}"`);
|
|
199
|
+
const doc = typeof body.doc === "object" && body.doc !== null ? body.doc : {};
|
|
200
|
+
const locale = typeof body.locale === "string" ? body.locale : null;
|
|
201
|
+
const id = typeof body.id === "string" || typeof body.id === "number" ? body.id : null;
|
|
202
|
+
const value = await generate({
|
|
203
|
+
doc,
|
|
204
|
+
id,
|
|
205
|
+
locale,
|
|
206
|
+
cms,
|
|
207
|
+
user,
|
|
208
|
+
...collection ? { collection } : { global }
|
|
209
|
+
});
|
|
210
|
+
return { value: value ?? null };
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
return {
|
|
214
|
+
...config,
|
|
215
|
+
collections: (config.collections ?? []).map(
|
|
216
|
+
(c) => collections.includes(c.slug) ? withSeo(c, c.useAsTitle ?? null) : c
|
|
217
|
+
),
|
|
218
|
+
globals: (config.globals ?? []).map((g) => globals.includes(g.slug) ? withSeo(g, null) : g),
|
|
219
|
+
admin: {
|
|
220
|
+
...config.admin,
|
|
221
|
+
modules: [.../* @__PURE__ */ new Set([...config.admin?.modules ?? [], ADMIN_MODULE])]
|
|
222
|
+
},
|
|
223
|
+
endpoints: [...config.endpoints ?? [], endpoint]
|
|
224
|
+
};
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
var isEmpty = (value) => value === null || value === void 0 || value === "";
|
|
228
|
+
function error(status, message) {
|
|
229
|
+
return Response.json({ errors: [{ message }] }, { status });
|
|
230
|
+
}
|
|
231
|
+
export {
|
|
232
|
+
DEFAULT_DESCRIPTION_LENGTH,
|
|
233
|
+
DEFAULT_TITLE_LENGTH,
|
|
234
|
+
seoMeta,
|
|
235
|
+
seoPlugin
|
|
236
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@easy-cms/plugin-seo",
|
|
3
|
+
"version": "0.13.0",
|
|
4
|
+
"description": "SEO for Easy CMS: meta fields, length meters, a search result preview, generators and page metadata",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./admin": "./dist/admin.js",
|
|
14
|
+
"./package.json": "./package.json"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist"
|
|
18
|
+
],
|
|
19
|
+
"peerDependencies": {
|
|
20
|
+
"@easy-cms/core": "^0.13.0"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"happy-dom": "^20.14.5",
|
|
24
|
+
"@easy-cms/core": "^0.13.0",
|
|
25
|
+
"@easy-cms/db-sqlite": "^0.13.0"
|
|
26
|
+
},
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=22.12"
|
|
29
|
+
},
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "git+https://github.com/maritonx/easy-cms.git",
|
|
36
|
+
"directory": "packages/plugin-seo"
|
|
37
|
+
},
|
|
38
|
+
"keywords": [
|
|
39
|
+
"easy-cms",
|
|
40
|
+
"easy-cms-plugin",
|
|
41
|
+
"seo",
|
|
42
|
+
"meta",
|
|
43
|
+
"open-graph"
|
|
44
|
+
],
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "tsup",
|
|
47
|
+
"typecheck": "tsc --noEmit",
|
|
48
|
+
"test": "vitest run"
|
|
49
|
+
}
|
|
50
|
+
}
|