@kitcms/plugin-seo 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 +21 -0
- package/README.md +118 -2
- package/package.json +42 -3
- package/src/index.ts +4 -0
- package/src/meta.ts +46 -0
- package/src/paths.ts +118 -0
- package/src/plugin.ts +181 -0
- package/src/redirects.ts +203 -0
- package/src/sitemap.ts +90 -0
- package/src/svelte/SeoHead.svelte +17 -0
- package/src/svelte/SerpPreview.svelte +62 -0
- package/src/svelte/index.ts +2 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 kitcms contributors
|
|
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,119 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @kitcms/plugin-seo
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Adds an SEO `meta` group (title, description, image, noIndex) to chosen collections and globals,
|
|
4
|
+
plus helpers to render it on the site and preview it in the admin.
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
pnpm add @kitcms/plugin-seo
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Config
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
// src/kitcms.config.ts
|
|
16
|
+
import { defineConfig } from '@kitcms/core';
|
|
17
|
+
import { seo } from '@kitcms/plugin-seo';
|
|
18
|
+
|
|
19
|
+
export default defineConfig({
|
|
20
|
+
collections: [pages, media],
|
|
21
|
+
plugins: [
|
|
22
|
+
seo({
|
|
23
|
+
collections: ['pages'],
|
|
24
|
+
globals: ['settings'],
|
|
25
|
+
uploadsCollection: 'media', // omit for no image field
|
|
26
|
+
// fieldName: 'meta', titleMaxLength: 60, descriptionMaxLength: 160 (hints only)
|
|
27
|
+
}),
|
|
28
|
+
],
|
|
29
|
+
});
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
`seo()` throws (message starts with `seo: `) when a listed slug does not exist, the target already has a field
|
|
33
|
+
named `fieldName`, or `uploadsCollection` is not an `upload: true` collection.
|
|
34
|
+
|
|
35
|
+
## Redirects, sitemap and robots.txt
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
seo({
|
|
39
|
+
collections: ['pages', 'rooms'],
|
|
40
|
+
redirects: true, // or { collection: 'redirects', cacheTtl: 60 }
|
|
41
|
+
sitemap: {
|
|
42
|
+
collections: {
|
|
43
|
+
pages: (doc) => (doc.slug === 'home' ? '/' : `/${doc.slug}`), // return null to skip a doc
|
|
44
|
+
rooms: '/rooms/:slug', // `:field` is replaced with the doc's field, URL-encoded
|
|
45
|
+
},
|
|
46
|
+
paths: ['/rooms', '/journal'], // extra static paths
|
|
47
|
+
origin: 'https://example.com', // default: the request's origin
|
|
48
|
+
},
|
|
49
|
+
robots: { disallow: ['/private'] }, // or true
|
|
50
|
+
});
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
The plugin answers these in its `handle` step, which runs for every site request (never `/admin*` or `/api*`)
|
|
54
|
+
before routing. Only `GET` and `HEAD` are handled. `path` is relative to the app's `paths.base`; the plugin works
|
|
55
|
+
out the base from the request URL, so redirect targets starting with `/` and sitemap URLs get the base prefix.
|
|
56
|
+
|
|
57
|
+
**Redirects.** `redirects` adds a `redirects` collection under the "SEO" admin group (default signed-in access;
|
|
58
|
+
reads are not public). Fields: `from` (path, unique, trailing slash ignored), `to` (a `/path` or an `http(s)://`
|
|
59
|
+
URL), `type` (301 or 302), `enabled`, `note`. Validation rejects a `from` under `/admin` or `/api`, a `to` that is
|
|
60
|
+
not a `/path` or an http(s) URL (so no `javascript:` and no `//host`), redirects to themselves and loops (the chain
|
|
61
|
+
of enabled redirects is followed up to 10 hops). Matching is exact on the path. The request's query string is kept
|
|
62
|
+
unless `to` has its own. The enabled redirects are cached per isolate for `cacheTtl` seconds (an empty list is
|
|
63
|
+
cached too, so a warm request does no D1 query). A write drops the cache of the isolate that handled it; other
|
|
64
|
+
isolates catch up within `cacheTtl`. At most 5000 enabled redirects are read.
|
|
65
|
+
|
|
66
|
+
**Sitemap.** `/sitemap.xml` is built as the anonymous visitor: only published docs the public may read, so a
|
|
67
|
+
collection without public read access is skipped silently. Docs with `meta.noIndex` are left out, `lastmod` is the
|
|
68
|
+
date part of `updatedAt`, and at most 5000 docs per collection are listed. Served as `application/xml` with
|
|
69
|
+
`cache-control: public, max-age=300`.
|
|
70
|
+
|
|
71
|
+
**robots.txt.** `User-agent: *`, `Disallow: /admin`, `Disallow: /api`, your extra `disallow` lines, and a
|
|
72
|
+
`Sitemap:` line when `sitemap` is configured. If the app has a static `robots.txt` (or `sitemap.xml`) in its
|
|
73
|
+
assets, the asset wins, because Cloudflare serves assets before the Worker runs.
|
|
74
|
+
|
|
75
|
+
## On the site
|
|
76
|
+
|
|
77
|
+
```svelte
|
|
78
|
+
<!-- src/routes/[slug]/+page.svelte -->
|
|
79
|
+
<script lang="ts">
|
|
80
|
+
import { getMeta } from '@kitcms/plugin-seo';
|
|
81
|
+
import { SeoHead } from '@kitcms/plugin-seo/svelte';
|
|
82
|
+
|
|
83
|
+
let { data } = $props();
|
|
84
|
+
const meta = $derived(
|
|
85
|
+
getMeta(data.page, { siteName: 'Acme', titleTemplate: '%s | Acme', description: 'Default description' }),
|
|
86
|
+
);
|
|
87
|
+
</script>
|
|
88
|
+
|
|
89
|
+
<SeoHead {meta} url={data.url} siteName="Acme" />
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Load the page with `depth: 1` so `meta.image` is populated. With depth 0 the image is a bare id, and `getMeta`
|
|
93
|
+
falls back to `defaults.image` rather than returning the id.
|
|
94
|
+
|
|
95
|
+
## In the admin
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
// src/kitcms.admin.ts
|
|
99
|
+
import { defineAdmin } from '@kitcms/ui';
|
|
100
|
+
|
|
101
|
+
export default defineAdmin({
|
|
102
|
+
previews: { collections: { pages: () => import('#lib/PagePreview.svelte') } },
|
|
103
|
+
});
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
```svelte
|
|
107
|
+
<!-- src/lib/PagePreview.svelte -->
|
|
108
|
+
<script lang="ts">
|
|
109
|
+
import { SerpPreview } from '@kitcms/plugin-seo/svelte';
|
|
110
|
+
let { doc } = $props();
|
|
111
|
+
</script>
|
|
112
|
+
|
|
113
|
+
<SerpPreview {doc} url="acme.com/{doc.slug}" defaults={{ siteName: 'Acme', titleTemplate: '%s | Acme' }} />
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## Types
|
|
117
|
+
|
|
118
|
+
Fields added by a plugin are not part of the app's inferred `DocOf` types. Use `generate:types` for headless
|
|
119
|
+
consumers, or cast the `meta` value to `Parameters<typeof getMeta>[0]` (it accepts any object).
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kitcms/plugin-seo",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/Norden-Tenzin/kitcms.git",
|
|
8
|
+
"directory": "packages/plugin-seo"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://kitcms.dev",
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/Norden-Tenzin/kitcms/issues"
|
|
13
|
+
},
|
|
14
|
+
"type": "module",
|
|
15
|
+
"sideEffects": false,
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"types": "./src/index.ts",
|
|
19
|
+
"default": "./src/index.ts"
|
|
20
|
+
},
|
|
21
|
+
"./svelte": {
|
|
22
|
+
"svelte": "./src/svelte/index.ts",
|
|
23
|
+
"types": "./src/svelte/index.ts",
|
|
24
|
+
"default": "./src/svelte/index.ts"
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"peerDependencies": {
|
|
28
|
+
"@kitcms/core": "^0.1.0",
|
|
29
|
+
"svelte": "^5"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@kitcms/core": "0.1.0",
|
|
33
|
+
"@sveltejs/vite-plugin-svelte": "^7.3.1",
|
|
34
|
+
"svelte": "^5.57.3",
|
|
35
|
+
"svelte-check": "^4.7.8"
|
|
36
|
+
},
|
|
37
|
+
"files": [
|
|
38
|
+
"src",
|
|
39
|
+
"!src/**/*.test.ts"
|
|
40
|
+
],
|
|
41
|
+
"scripts": {
|
|
42
|
+
"typecheck": "svelte-check --tsconfig ./tsconfig.json",
|
|
43
|
+
"test": "vitest run"
|
|
44
|
+
}
|
|
6
45
|
}
|
package/src/index.ts
ADDED
package/src/meta.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
export interface MetaDefaults {
|
|
2
|
+
siteName?: string;
|
|
3
|
+
/** e.g. `'%s | Site'` */
|
|
4
|
+
titleTemplate?: string;
|
|
5
|
+
description?: string;
|
|
6
|
+
/** Fallback image URL. */
|
|
7
|
+
image?: string;
|
|
8
|
+
/** Name of the meta group field. Default `'meta'`. */
|
|
9
|
+
fieldName?: string;
|
|
10
|
+
/** Document field used when `meta.title` is empty. Default `'title'`. */
|
|
11
|
+
fallbackTitleField?: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface ResolvedMeta {
|
|
15
|
+
title: string;
|
|
16
|
+
description: string | null;
|
|
17
|
+
image: string | null;
|
|
18
|
+
robots: 'index, follow' | 'noindex, nofollow';
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
22
|
+
const str = (v: unknown): string => (typeof v === 'string' ? v.trim() : '');
|
|
23
|
+
|
|
24
|
+
/** Resolve the SEO fields of a document into final head values. Pure and defensive: never throws. */
|
|
25
|
+
export function getMeta(doc: unknown, defaults: MetaDefaults = {}): ResolvedMeta {
|
|
26
|
+
const d: MetaDefaults = isRecord(defaults) ? defaults : {};
|
|
27
|
+
const root = isRecord(doc) ? doc : {};
|
|
28
|
+
const rawMeta = root[d.fieldName ?? 'meta'];
|
|
29
|
+
const meta = isRecord(rawMeta) ? rawMeta : {};
|
|
30
|
+
const siteName = str(d.siteName);
|
|
31
|
+
|
|
32
|
+
let title = str(meta.title) || str(root[d.fallbackTitleField ?? 'title']) || siteName;
|
|
33
|
+
const template = typeof d.titleTemplate === 'string' ? d.titleTemplate : '';
|
|
34
|
+
if (template && title && title !== siteName) title = template.replaceAll('%s', title);
|
|
35
|
+
|
|
36
|
+
const image = isRecord(meta.image) && typeof meta.image.url === 'string' && meta.image.url
|
|
37
|
+
? meta.image.url
|
|
38
|
+
: str(d.image) || null;
|
|
39
|
+
|
|
40
|
+
return {
|
|
41
|
+
title,
|
|
42
|
+
description: str(meta.description) || str(d.description) || null,
|
|
43
|
+
image,
|
|
44
|
+
robots: meta.noIndex === true ? 'noindex, nofollow' : 'index, follow',
|
|
45
|
+
};
|
|
46
|
+
}
|
package/src/paths.ts
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// Pure helpers shared by redirects, sitemap and robots. No runtime dependencies.
|
|
2
|
+
|
|
3
|
+
/** Strip trailing slashes (keeps `/`) and surrounding whitespace. `'/about/'` -> `'/about'`. */
|
|
4
|
+
export function normalizePath(path: string): string {
|
|
5
|
+
const p = path.trim().replace(/\/+$/, '');
|
|
6
|
+
return p === '' ? '/' : p;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const hasBadChars = (s: string): boolean => {
|
|
10
|
+
if (/[\s\\]/.test(s)) return true;
|
|
11
|
+
for (let i = 0; i < s.length; i++) {
|
|
12
|
+
const c = s.charCodeAt(i);
|
|
13
|
+
if (c < 32 || c === 127) return true;
|
|
14
|
+
}
|
|
15
|
+
return false;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/** Is `path` under `/admin` or `/api` (never reaches the plugin handle)? */
|
|
19
|
+
export const isReservedPath = (path: string): boolean =>
|
|
20
|
+
/^\/(admin|api)(\/|$)/.test(path);
|
|
21
|
+
|
|
22
|
+
/** `true` when valid, else an error message. Expects an already normalized value. */
|
|
23
|
+
export function checkFrom(from: string): true | string {
|
|
24
|
+
if (from.length > 500) return 'Must be at most 500 characters.';
|
|
25
|
+
if (!from.startsWith('/') || from.startsWith('//')) return 'Must be a path starting with a single "/", e.g. /old-page.';
|
|
26
|
+
if (from.includes('?') || from.includes('#')) return 'Path only: leave out the query string and #fragment.';
|
|
27
|
+
if (hasBadChars(from)) return 'Must not contain spaces or backslashes.';
|
|
28
|
+
if (isReservedPath(from)) return 'Paths under /admin and /api cannot be redirected.';
|
|
29
|
+
return true;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** `true` when valid, else an error message. Only `/`-relative paths and http(s) URLs are allowed. */
|
|
33
|
+
export function checkTo(to: string): true | string {
|
|
34
|
+
if (to.length > 2000) return 'Must be at most 2000 characters.';
|
|
35
|
+
if (hasBadChars(to)) return 'Must not contain spaces or backslashes.';
|
|
36
|
+
if (to.startsWith('//')) return 'Protocol-relative URLs are not allowed. Use a /path or a full https:// URL.';
|
|
37
|
+
if (to.startsWith('/')) return true;
|
|
38
|
+
if (/^https?:\/\//i.test(to)) {
|
|
39
|
+
try {
|
|
40
|
+
return new URL(to).hostname ? true : 'Invalid URL.';
|
|
41
|
+
} catch {
|
|
42
|
+
return 'Invalid URL.';
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return 'Must be a /path or a full http(s):// URL.';
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The path part of a redirect target, normalized, or `null` for external URLs. */
|
|
49
|
+
export function targetPath(to: string): string | null {
|
|
50
|
+
if (!to.startsWith('/')) return null;
|
|
51
|
+
const end = to.search(/[?#]/);
|
|
52
|
+
return normalizePath(end === -1 ? to : to.slice(0, end));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Follow `map` from `to`. Returns `true` when the chain comes back to `from` within `maxHops`
|
|
57
|
+
* (including `to === from`), i.e. adding `from -> to` would create a loop.
|
|
58
|
+
*/
|
|
59
|
+
export function createsLoop(map: ReadonlyMap<string, string>, from: string, to: string, maxHops = 10): boolean {
|
|
60
|
+
let current = targetPath(to);
|
|
61
|
+
for (let i = 0; i < maxHops && current !== null; i++) {
|
|
62
|
+
if (current === from) return true;
|
|
63
|
+
const next = map.get(current);
|
|
64
|
+
current = next === undefined ? null : targetPath(next);
|
|
65
|
+
}
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Escape text for XML element content. */
|
|
70
|
+
export function xmlEscape(s: string): string {
|
|
71
|
+
return s
|
|
72
|
+
.replace(/&/g, '&')
|
|
73
|
+
.replace(/</g, '<')
|
|
74
|
+
.replace(/>/g, '>')
|
|
75
|
+
.replace(/"/g, '"')
|
|
76
|
+
.replace(/'/g, ''');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export type PathBuilder = string | ((doc: Record<string, unknown>) => string | null);
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Build a doc's path. A string pattern substitutes `:field` with the (URL-encoded) field value;
|
|
83
|
+
* a missing or empty value skips the doc (`null`). The result must start with `/`.
|
|
84
|
+
*/
|
|
85
|
+
export function buildDocPath(builder: PathBuilder, doc: Record<string, unknown>): string | null {
|
|
86
|
+
let out: string | null;
|
|
87
|
+
if (typeof builder === 'function') {
|
|
88
|
+
out = builder(doc);
|
|
89
|
+
} else {
|
|
90
|
+
let missing = false;
|
|
91
|
+
out = builder.replace(/:([A-Za-z_][A-Za-z0-9_]*)/g, (_m, name: string) => {
|
|
92
|
+
const v = doc[name];
|
|
93
|
+
if ((typeof v !== 'string' && typeof v !== 'number') || String(v) === '') {
|
|
94
|
+
missing = true;
|
|
95
|
+
return '';
|
|
96
|
+
}
|
|
97
|
+
return encodeURIComponent(String(v));
|
|
98
|
+
});
|
|
99
|
+
if (missing) out = null;
|
|
100
|
+
}
|
|
101
|
+
return typeof out === 'string' && out.startsWith('/') && !out.startsWith('//') ? out : null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* The app's `paths.base` (`''` or `/prefix`), from the full pathname and the base-relative,
|
|
106
|
+
* decoded `path` the plugin handle receives.
|
|
107
|
+
*/
|
|
108
|
+
export function baseFrom(pathname: string, path: string): string {
|
|
109
|
+
let decoded = pathname;
|
|
110
|
+
try {
|
|
111
|
+
decoded = decodeURI(pathname);
|
|
112
|
+
} catch {
|
|
113
|
+
/* keep the raw pathname */
|
|
114
|
+
}
|
|
115
|
+
const p = decoded.replace(/\/+$/, '');
|
|
116
|
+
const q = path.replace(/\/+$/, '');
|
|
117
|
+
return p.endsWith(q) ? p.slice(0, p.length - q.length) : '';
|
|
118
|
+
}
|
package/src/plugin.ts
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import type { CollectionDef, Config, FieldDef, GlobalDef, KitcmsPlugin, PluginHandleArgs } from '@kitcms/core';
|
|
2
|
+
import { fields } from '@kitcms/core';
|
|
3
|
+
import { baseFrom, normalizePath } from './paths';
|
|
4
|
+
import { createRedirectCache, locationFor, redirectsCollection, type RedirectsOptions } from './redirects';
|
|
5
|
+
import {
|
|
6
|
+
collectEntries,
|
|
7
|
+
renderRobots,
|
|
8
|
+
renderSitemap,
|
|
9
|
+
type RobotsOptions,
|
|
10
|
+
type SitemapOptions,
|
|
11
|
+
} from './sitemap';
|
|
12
|
+
|
|
13
|
+
export interface SeoOptions {
|
|
14
|
+
/** Collection slugs to add the meta group to. */
|
|
15
|
+
collections?: string[];
|
|
16
|
+
/** Global slugs to add the meta group to. */
|
|
17
|
+
globals?: string[];
|
|
18
|
+
/** Upload collection for `meta.image`. Omit for no image field. */
|
|
19
|
+
uploadsCollection?: string;
|
|
20
|
+
/** Name of the group field. Default `'meta'`. */
|
|
21
|
+
fieldName?: string;
|
|
22
|
+
/** Recommended title length, shown as a hint only. Default 60. */
|
|
23
|
+
titleMaxLength?: number;
|
|
24
|
+
/** Recommended description length, shown as a hint only. Default 160. */
|
|
25
|
+
descriptionMaxLength?: number;
|
|
26
|
+
/**
|
|
27
|
+
* Editor-managed redirects, applied before the site renders. Adds a `redirects` collection
|
|
28
|
+
* (signed-in access) and a cache per isolate: edits show up in this isolate at once and in
|
|
29
|
+
* others within `cacheTtl` seconds (default 60). `/`-relative targets get the app's base path.
|
|
30
|
+
*/
|
|
31
|
+
redirects?: boolean | RedirectsOptions;
|
|
32
|
+
/** `/sitemap.xml` from published docs. */
|
|
33
|
+
sitemap?: SitemapOptions;
|
|
34
|
+
/**
|
|
35
|
+
* `/robots.txt`. `true` = `Disallow: /admin` and `/api`, plus a `Sitemap:` line when `sitemap` is
|
|
36
|
+
* set. A static `robots.txt` in the app's assets wins (Cloudflare serves assets before the Worker).
|
|
37
|
+
*/
|
|
38
|
+
robots?: boolean | RobotsOptions;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export type { RedirectsOptions, RobotsOptions, SitemapOptions };
|
|
42
|
+
|
|
43
|
+
const fail = (msg: string): never => {
|
|
44
|
+
throw new Error(`seo: ${msg}`);
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/** Adds an SEO `meta` group (title, description, image, noIndex) to the listed collections and globals. */
|
|
48
|
+
export function seo(options: SeoOptions = {}): KitcmsPlugin {
|
|
49
|
+
const fieldName = options.fieldName ?? 'meta';
|
|
50
|
+
const titleLen = options.titleMaxLength ?? 60;
|
|
51
|
+
const descLen = options.descriptionMaxLength ?? 160;
|
|
52
|
+
|
|
53
|
+
const redirects = options.redirects ? (typeof options.redirects === 'object' ? options.redirects : {}) : null;
|
|
54
|
+
const redirectsSlug = redirects?.collection ?? 'redirects';
|
|
55
|
+
const cacheTtl = redirects?.cacheTtl ?? 60;
|
|
56
|
+
if (redirects && !(cacheTtl >= 0)) fail('redirects.cacheTtl must be a number of seconds.');
|
|
57
|
+
const cache = redirects ? createRedirectCache(redirectsSlug, cacheTtl) : null;
|
|
58
|
+
const robots = options.robots ? (typeof options.robots === 'object' ? options.robots : {}) : null;
|
|
59
|
+
const sitemap = options.sitemap ?? null;
|
|
60
|
+
|
|
61
|
+
if (sitemap) {
|
|
62
|
+
if (!sitemap.collections || typeof sitemap.collections !== 'object') fail('sitemap.collections is required.');
|
|
63
|
+
for (const [slug, b] of Object.entries(sitemap.collections)) {
|
|
64
|
+
if (typeof b === 'string' && !b.startsWith('/')) fail(`sitemap pattern for "${slug}" must start with "/".`);
|
|
65
|
+
}
|
|
66
|
+
for (const p of sitemap.paths ?? []) if (!p.startsWith('/')) fail(`sitemap path "${p}" must start with "/".`);
|
|
67
|
+
if (sitemap.origin !== undefined) {
|
|
68
|
+
let ok = false;
|
|
69
|
+
try {
|
|
70
|
+
ok = /^https?:$/.test(new URL(sitemap.origin).protocol);
|
|
71
|
+
} catch {
|
|
72
|
+
/* invalid */
|
|
73
|
+
}
|
|
74
|
+
if (!ok) fail(`sitemap.origin "${sitemap.origin}" must be an http(s) origin like https://example.com.`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const sitemapOrigin = sitemap?.origin ? new URL(sitemap.origin).origin : null;
|
|
78
|
+
|
|
79
|
+
const handle: KitcmsPlugin['handle'] =
|
|
80
|
+
redirects || sitemap || robots
|
|
81
|
+
? async ({ event, path, cms }: PluginHandleArgs) => {
|
|
82
|
+
const method = event.request.method;
|
|
83
|
+
if (method !== 'GET' && method !== 'HEAD') return;
|
|
84
|
+
const base = baseFrom(event.url.pathname, path);
|
|
85
|
+
const origin = sitemapOrigin ?? event.url.origin;
|
|
86
|
+
if (sitemap && path === '/sitemap.xml') {
|
|
87
|
+
const entries = await collectEntries(sitemap, cms, origin, base, fieldName);
|
|
88
|
+
return new Response(renderSitemap(entries), {
|
|
89
|
+
headers: { 'content-type': 'application/xml; charset=utf-8', 'cache-control': 'public, max-age=300' },
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
if (robots && path === '/robots.txt') {
|
|
93
|
+
const sitemapUrl = sitemap ? `${origin}${base}/sitemap.xml` : null;
|
|
94
|
+
return new Response(renderRobots(robots, sitemapUrl), {
|
|
95
|
+
headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'public, max-age=300' },
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
if (cache) {
|
|
99
|
+
const target = (await cache.get(cms)).get(normalizePath(path));
|
|
100
|
+
if (!target) return;
|
|
101
|
+
const location = locationFor(target, event.url, base);
|
|
102
|
+
if (location) return new Response(null, { status: target.status, headers: { location } });
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
: undefined;
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
name: 'seo',
|
|
109
|
+
...(handle ? { handle } : {}),
|
|
110
|
+
config(config: Config): Config {
|
|
111
|
+
const collections = (config.collections ?? []) as readonly CollectionDef[];
|
|
112
|
+
const globals = (config.globals ?? []) as readonly GlobalDef[];
|
|
113
|
+
|
|
114
|
+
if (options.uploadsCollection !== undefined) {
|
|
115
|
+
const up = collections.find((c) => c.slug === options.uploadsCollection);
|
|
116
|
+
if (!up) fail(`uploadsCollection "${options.uploadsCollection}" does not exist.`);
|
|
117
|
+
else if (!up.upload) fail(`uploadsCollection "${options.uploadsCollection}" is not an upload collection.`);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
let withRedirects = collections;
|
|
121
|
+
if (redirects) {
|
|
122
|
+
if (collections.some((c) => c.slug === redirectsSlug)) fail(`collection "${redirectsSlug}" already exists.`);
|
|
123
|
+
withRedirects = [...collections, redirectsCollection(redirectsSlug, () => cache!.invalidate())];
|
|
124
|
+
}
|
|
125
|
+
if (sitemap) {
|
|
126
|
+
for (const slug of Object.keys(sitemap.collections)) {
|
|
127
|
+
if (!withRedirects.some((c) => c.slug === slug)) fail(`sitemap collection "${slug}" does not exist.`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const group = (): FieldDef =>
|
|
132
|
+
fields.group({
|
|
133
|
+
admin: { position: 'sidebar', description: 'Search engine and social sharing.' },
|
|
134
|
+
fields: {
|
|
135
|
+
title: fields.text({
|
|
136
|
+
admin: { description: `Recommended: up to ${titleLen} characters. Falls back to the page title.` },
|
|
137
|
+
}),
|
|
138
|
+
description: fields.textarea({
|
|
139
|
+
admin: { description: `Recommended: up to ${descLen} characters.` },
|
|
140
|
+
}),
|
|
141
|
+
...(options.uploadsCollection !== undefined
|
|
142
|
+
? {
|
|
143
|
+
image: fields.upload({
|
|
144
|
+
relationTo: options.uploadsCollection,
|
|
145
|
+
admin: { description: 'Shown when the page is shared. 1200x630 works best.' },
|
|
146
|
+
}),
|
|
147
|
+
}
|
|
148
|
+
: {}),
|
|
149
|
+
noIndex: fields.checkbox({
|
|
150
|
+
defaultValue: false,
|
|
151
|
+
admin: { description: 'Ask search engines not to list this page.' },
|
|
152
|
+
}),
|
|
153
|
+
},
|
|
154
|
+
}) as FieldDef;
|
|
155
|
+
|
|
156
|
+
const apply = <T extends { slug: string; fields: Record<string, FieldDef> }>(
|
|
157
|
+
items: readonly T[],
|
|
158
|
+
slugs: string[] | undefined,
|
|
159
|
+
kind: string,
|
|
160
|
+
): readonly T[] => {
|
|
161
|
+
if (!slugs?.length) return items;
|
|
162
|
+
for (const s of slugs) if (!items.some((i) => i.slug === s)) fail(`${kind} "${s}" does not exist.`);
|
|
163
|
+
return items.map((item) => {
|
|
164
|
+
if (!slugs.includes(item.slug)) return item;
|
|
165
|
+
if (fieldName in item.fields) fail(`${kind} "${item.slug}" already has a field named "${fieldName}".`);
|
|
166
|
+
return { ...item, fields: { ...item.fields, [fieldName]: group() } };
|
|
167
|
+
});
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
return {
|
|
171
|
+
...config,
|
|
172
|
+
...(config.collections || options.collections?.length || redirects
|
|
173
|
+
? { collections: apply(withRedirects, options.collections, 'collection') as CollectionDef[] }
|
|
174
|
+
: {}),
|
|
175
|
+
...(config.globals || options.globals?.length
|
|
176
|
+
? { globals: apply(globals, options.globals, 'global') as GlobalDef[] }
|
|
177
|
+
: {}),
|
|
178
|
+
};
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
}
|
package/src/redirects.ts
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import type { CollectionDef } from '@kitcms/core';
|
|
2
|
+
import { collection, fields as f } from '@kitcms/core';
|
|
3
|
+
import { checkFrom, checkTo, createsLoop, normalizePath } from './paths';
|
|
4
|
+
|
|
5
|
+
export interface RedirectsOptions {
|
|
6
|
+
collection?: string;
|
|
7
|
+
/** Seconds the per-isolate cache is trusted. Default 60. */
|
|
8
|
+
cacheTtl?: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
type Row = Record<string, unknown>;
|
|
12
|
+
interface LooseCms {
|
|
13
|
+
find(slug: string, args: Record<string, unknown>): Promise<{ docs: Row[] }>;
|
|
14
|
+
findByID(slug: string, id: string, args?: Record<string, unknown>): Promise<Row | null>;
|
|
15
|
+
}
|
|
16
|
+
interface Req {
|
|
17
|
+
cms: unknown;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface RedirectTarget {
|
|
21
|
+
to: string;
|
|
22
|
+
status: 301 | 302;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const PAGE = 1000;
|
|
26
|
+
export const MAX_REDIRECTS = 5000;
|
|
27
|
+
const FAILURE_TTL_MS = 10_000;
|
|
28
|
+
|
|
29
|
+
/** Every row of a collection (trusted read), up to `max`. `truncated` when there were more. */
|
|
30
|
+
export async function readAll(
|
|
31
|
+
cms: unknown,
|
|
32
|
+
slug: string,
|
|
33
|
+
args: Record<string, unknown>,
|
|
34
|
+
max: number,
|
|
35
|
+
): Promise<{ docs: Row[]; truncated: boolean }> {
|
|
36
|
+
const docs: Row[] = [];
|
|
37
|
+
for (let page = 1; docs.length < max; page++) {
|
|
38
|
+
const res = await (cms as LooseCms).find(slug, { ...args, limit: PAGE, page, pagination: false });
|
|
39
|
+
docs.push(...res.docs);
|
|
40
|
+
if (res.docs.length < PAGE) return { docs, truncated: false };
|
|
41
|
+
}
|
|
42
|
+
return { docs: docs.slice(0, max), truncated: true };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const str = (v: unknown): string => (typeof v === 'string' ? v : '');
|
|
46
|
+
|
|
47
|
+
/** The enabled redirects as `from -> { to, status }`. */
|
|
48
|
+
export async function loadRedirects(cms: unknown, slug: string): Promise<Map<string, RedirectTarget>> {
|
|
49
|
+
const { docs, truncated } = await readAll(
|
|
50
|
+
cms,
|
|
51
|
+
slug,
|
|
52
|
+
{ where: { enabled: { equals: true } }, overrideAccess: true, depth: 0, sort: 'createdAt' },
|
|
53
|
+
MAX_REDIRECTS,
|
|
54
|
+
);
|
|
55
|
+
if (truncated) console.warn(`seo: more than ${MAX_REDIRECTS} redirects; the rest are ignored.`);
|
|
56
|
+
const map = new Map<string, RedirectTarget>();
|
|
57
|
+
for (const d of docs) {
|
|
58
|
+
const from = normalizePath(str(d.from));
|
|
59
|
+
const to = str(d.to);
|
|
60
|
+
if (!from || !to || map.has(from)) continue;
|
|
61
|
+
map.set(from, { to, status: d.type === '302' ? 302 : 301 });
|
|
62
|
+
}
|
|
63
|
+
return map;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A per-isolate cache of the enabled redirects with a TTL. Failures fail open (empty, short TTL). */
|
|
67
|
+
export function createRedirectCache(slug: string, ttlSeconds: number) {
|
|
68
|
+
let value: Map<string, RedirectTarget> | null = null;
|
|
69
|
+
let expires = 0;
|
|
70
|
+
let loading: Promise<Map<string, RedirectTarget>> | null = null;
|
|
71
|
+
let generation = 0;
|
|
72
|
+
|
|
73
|
+
return {
|
|
74
|
+
async get(cms: unknown): Promise<Map<string, RedirectTarget>> {
|
|
75
|
+
if (value && Date.now() < expires) return value;
|
|
76
|
+
if (!loading) {
|
|
77
|
+
const gen = generation;
|
|
78
|
+
loading = loadRedirects(cms, slug)
|
|
79
|
+
.then((m) => {
|
|
80
|
+
if (gen === generation) {
|
|
81
|
+
value = m;
|
|
82
|
+
expires = Date.now() + ttlSeconds * 1000;
|
|
83
|
+
}
|
|
84
|
+
return m;
|
|
85
|
+
})
|
|
86
|
+
.catch((err) => {
|
|
87
|
+
console.warn('seo: could not load redirects', err);
|
|
88
|
+
const empty = new Map<string, RedirectTarget>();
|
|
89
|
+
if (gen === generation) {
|
|
90
|
+
value = empty;
|
|
91
|
+
expires = Date.now() + Math.min(FAILURE_TTL_MS, ttlSeconds * 1000);
|
|
92
|
+
}
|
|
93
|
+
return empty;
|
|
94
|
+
})
|
|
95
|
+
.finally(() => {
|
|
96
|
+
loading = null;
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
return loading;
|
|
100
|
+
},
|
|
101
|
+
/** Drop the cache of this isolate. Other isolates catch up within the TTL. */
|
|
102
|
+
invalidate(): void {
|
|
103
|
+
value = null;
|
|
104
|
+
expires = 0;
|
|
105
|
+
generation++;
|
|
106
|
+
loading = null;
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The collection the plugin adds. Validation lives on `to` because it needs the other fields. */
|
|
112
|
+
export function redirectsCollection(slug: string, invalidate: () => void): CollectionDef {
|
|
113
|
+
const hooks = {
|
|
114
|
+
beforeValidate: [
|
|
115
|
+
({ data }: { data: Row }) => {
|
|
116
|
+
const out: Row = { ...data };
|
|
117
|
+
if (typeof data.from === 'string') out.from = normalizePath(data.from);
|
|
118
|
+
if (typeof data.to === 'string') out.to = data.to.trim();
|
|
119
|
+
return out;
|
|
120
|
+
},
|
|
121
|
+
],
|
|
122
|
+
afterChange: [() => void invalidate()],
|
|
123
|
+
afterDelete: [() => void invalidate()],
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
return collection({
|
|
127
|
+
slug,
|
|
128
|
+
labels: { singular: 'Redirect', plural: 'Redirects' },
|
|
129
|
+
admin: {
|
|
130
|
+
useAsTitle: 'from',
|
|
131
|
+
defaultColumns: ['from', 'to', 'type', 'enabled'],
|
|
132
|
+
listSearchableFields: ['from', 'to'],
|
|
133
|
+
group: 'SEO',
|
|
134
|
+
description: 'Send visitors from an old path to a new page or URL.',
|
|
135
|
+
},
|
|
136
|
+
hooks,
|
|
137
|
+
fields: {
|
|
138
|
+
from: f.text({
|
|
139
|
+
required: true,
|
|
140
|
+
unique: true,
|
|
141
|
+
admin: { description: 'The old path, e.g. /old-page. Path only, no domain or query.' },
|
|
142
|
+
validate: (value: string | null | undefined) => {
|
|
143
|
+
if (!value) return undefined;
|
|
144
|
+
return checkFrom(normalizePath(value));
|
|
145
|
+
},
|
|
146
|
+
}),
|
|
147
|
+
to: f.text({
|
|
148
|
+
required: true,
|
|
149
|
+
admin: { description: 'A /path on this site, or a full https:// URL.' },
|
|
150
|
+
validate: async (
|
|
151
|
+
value: string | null | undefined,
|
|
152
|
+
{ req, id, data }: { req: Req; id?: string; data: Row },
|
|
153
|
+
) => {
|
|
154
|
+
if (!value) return undefined;
|
|
155
|
+
const to = value.trim();
|
|
156
|
+
const bad = checkTo(to);
|
|
157
|
+
if (bad !== true) return bad;
|
|
158
|
+
const cms = req.cms as LooseCms;
|
|
159
|
+
|
|
160
|
+
let from = typeof data.from === 'string' ? normalizePath(data.from) : '';
|
|
161
|
+
let enabled = data.enabled;
|
|
162
|
+
if ((!from || enabled === undefined) && id) {
|
|
163
|
+
const original = await cms.findByID(slug, id, { overrideAccess: true, depth: 0 });
|
|
164
|
+
if (!from) from = normalizePath(str(original?.from));
|
|
165
|
+
if (enabled === undefined) enabled = original?.enabled;
|
|
166
|
+
}
|
|
167
|
+
if (!from) return undefined;
|
|
168
|
+
if (enabled === false) return undefined;
|
|
169
|
+
if (normalizePath(to) === from) return 'A redirect cannot point to itself.';
|
|
170
|
+
|
|
171
|
+
const { docs } = await readAll(
|
|
172
|
+
cms,
|
|
173
|
+
slug,
|
|
174
|
+
{ where: { enabled: { equals: true } }, overrideAccess: true, depth: 0 },
|
|
175
|
+
MAX_REDIRECTS,
|
|
176
|
+
);
|
|
177
|
+
const map = new Map<string, string>();
|
|
178
|
+
for (const d of docs) if (d.id !== id) map.set(normalizePath(str(d.from)), str(d.to));
|
|
179
|
+
if (createsLoop(map, from, to)) return 'This redirect would create a loop.';
|
|
180
|
+
return true;
|
|
181
|
+
},
|
|
182
|
+
}),
|
|
183
|
+
type: f.select({ options: ['301', '302'], defaultValue: '301', required: true }),
|
|
184
|
+
enabled: f.checkbox({ defaultValue: true }),
|
|
185
|
+
note: f.textarea({ admin: { description: 'Why this redirect exists. Not shown to visitors.' } }),
|
|
186
|
+
},
|
|
187
|
+
} as never) as CollectionDef;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* The `Location` for a redirect: `/`-relative targets are prefixed with the app's base path, and the
|
|
192
|
+
* request's query string is kept when the target has none. Returns `null` for an unusable target.
|
|
193
|
+
*/
|
|
194
|
+
export function locationFor(target: RedirectTarget, requestUrl: URL, base: string): string | null {
|
|
195
|
+
try {
|
|
196
|
+
const external = !target.to.startsWith('/');
|
|
197
|
+
const u = external ? new URL(target.to) : new URL(base + target.to, requestUrl.origin);
|
|
198
|
+
if (!u.search) u.search = requestUrl.search;
|
|
199
|
+
return external ? u.href : u.pathname + u.search + u.hash;
|
|
200
|
+
} catch {
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
}
|
package/src/sitemap.ts
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { readAll } from './redirects';
|
|
2
|
+
import { buildDocPath, xmlEscape, type PathBuilder } from './paths';
|
|
3
|
+
|
|
4
|
+
export interface SitemapOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Collections to list and how to build each doc's path, e.g.
|
|
7
|
+
* `{ pages: (doc) => doc.slug === 'home' ? '/' : `/${doc.slug}`, rooms: '/rooms/:slug' }`.
|
|
8
|
+
* A string pattern substitutes `:field` with the doc's field (URL-encoded). Return `null` to skip a doc.
|
|
9
|
+
*/
|
|
10
|
+
collections: Record<string, PathBuilder>;
|
|
11
|
+
/** Extra static paths (e.g. `'/rooms'`, `'/journal'`). */
|
|
12
|
+
paths?: string[];
|
|
13
|
+
/** Canonical origin (`https://example.com`). Default: the request's origin. */
|
|
14
|
+
origin?: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const MAX_PER_COLLECTION = 5000;
|
|
18
|
+
const DATE = /^\d{4}-\d{2}-\d{2}/;
|
|
19
|
+
|
|
20
|
+
interface Entry {
|
|
21
|
+
loc: string;
|
|
22
|
+
lastmod?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const isDenied = (err: unknown): boolean => {
|
|
26
|
+
const status = (err as { status?: number } | null)?.status;
|
|
27
|
+
return status === 401 || status === 403;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/** Collect sitemap entries as the anonymous visitor. `base` is the app's `paths.base`. */
|
|
31
|
+
export async function collectEntries(
|
|
32
|
+
options: SitemapOptions,
|
|
33
|
+
cms: unknown,
|
|
34
|
+
origin: string,
|
|
35
|
+
base: string,
|
|
36
|
+
fieldName: string,
|
|
37
|
+
): Promise<Entry[]> {
|
|
38
|
+
const seen = new Set<string>();
|
|
39
|
+
const entries: Entry[] = [];
|
|
40
|
+
const add = (path: string, lastmod?: string): void => {
|
|
41
|
+
const loc = origin + base + path;
|
|
42
|
+
if (seen.has(loc)) return;
|
|
43
|
+
seen.add(loc);
|
|
44
|
+
entries.push(lastmod ? { loc, lastmod } : { loc });
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
for (const p of options.paths ?? []) add(p);
|
|
48
|
+
|
|
49
|
+
for (const [slug, builder] of Object.entries(options.collections)) {
|
|
50
|
+
let docs: Record<string, unknown>[];
|
|
51
|
+
try {
|
|
52
|
+
// Anonymous: published documents the visitor may read. No `overrideAccess`.
|
|
53
|
+
({ docs } = await readAll(cms, slug, { depth: 0 }, MAX_PER_COLLECTION));
|
|
54
|
+
} catch (err) {
|
|
55
|
+
if (!isDenied(err)) console.warn(`seo: sitemap skipped "${slug}"`, err);
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
for (const doc of docs) {
|
|
59
|
+
const meta = doc[fieldName];
|
|
60
|
+
if (typeof meta === 'object' && meta !== null && (meta as { noIndex?: unknown }).noIndex === true) continue;
|
|
61
|
+
const path = buildDocPath(builder, doc);
|
|
62
|
+
if (path === null) continue;
|
|
63
|
+
const updated = doc.updatedAt;
|
|
64
|
+
add(path, typeof updated === 'string' && DATE.test(updated) ? updated.slice(0, 10) : undefined);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return entries;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function renderSitemap(entries: Entry[]): string {
|
|
71
|
+
const urls = entries
|
|
72
|
+
.map(
|
|
73
|
+
(e) =>
|
|
74
|
+
`<url><loc>${xmlEscape(e.loc)}</loc>${e.lastmod ? `<lastmod>${e.lastmod}</lastmod>` : ''}</url>`,
|
|
75
|
+
)
|
|
76
|
+
.join('\n');
|
|
77
|
+
return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls}\n</urlset>\n`;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface RobotsOptions {
|
|
81
|
+
/** Extra `Disallow` paths. */
|
|
82
|
+
disallow?: string[];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function renderRobots(options: RobotsOptions, sitemapUrl: string | null): string {
|
|
86
|
+
const lines = ['User-agent: *', 'Disallow: /admin', 'Disallow: /api'];
|
|
87
|
+
for (const d of options.disallow ?? []) lines.push(`Disallow: ${d}`);
|
|
88
|
+
if (sitemapUrl) lines.push('', `Sitemap: ${sitemapUrl}`);
|
|
89
|
+
return lines.join('\n') + '\n';
|
|
90
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
<script lang="ts">
|
|
2
|
+
import type { ResolvedMeta } from '../meta';
|
|
3
|
+
|
|
4
|
+
let { meta, url, siteName }: { meta: ResolvedMeta; url?: string; siteName?: string } = $props();
|
|
5
|
+
</script>
|
|
6
|
+
|
|
7
|
+
<svelte:head>
|
|
8
|
+
<title>{meta.title}</title>
|
|
9
|
+
{#if meta.description}<meta name="description" content={meta.description} />{/if}
|
|
10
|
+
<meta name="robots" content={meta.robots} />
|
|
11
|
+
<meta property="og:title" content={meta.title} />
|
|
12
|
+
{#if meta.description}<meta property="og:description" content={meta.description} />{/if}
|
|
13
|
+
{#if meta.image}<meta property="og:image" content={meta.image} />{/if}
|
|
14
|
+
{#if url}<meta property="og:url" content={url} />{/if}
|
|
15
|
+
{#if siteName}<meta property="og:site_name" content={siteName} />{/if}
|
|
16
|
+
<meta name="twitter:card" content={meta.image ? 'summary_large_image' : 'summary'} />
|
|
17
|
+
</svelte:head>
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
<script lang="ts">
|
|
2
|
+
import { getMeta, type MetaDefaults } from '../meta';
|
|
3
|
+
|
|
4
|
+
let { doc, url = '', defaults }: { doc: Record<string, unknown>; url?: string; defaults?: MetaDefaults } = $props();
|
|
5
|
+
|
|
6
|
+
const TITLE_MAX = 60;
|
|
7
|
+
const DESC_MAX = 160;
|
|
8
|
+
|
|
9
|
+
const meta = $derived(getMeta(doc, defaults));
|
|
10
|
+
const cut = (s: string, max: number) => (s.length > max ? `${s.slice(0, max - 1).trimEnd()}…` : s);
|
|
11
|
+
const title = $derived(cut(meta.title, TITLE_MAX));
|
|
12
|
+
const description = $derived(cut(meta.description ?? '', DESC_MAX));
|
|
13
|
+
const titleOver = $derived(meta.title.length > TITLE_MAX);
|
|
14
|
+
const descOver = $derived((meta.description ?? '').length > DESC_MAX);
|
|
15
|
+
</script>
|
|
16
|
+
|
|
17
|
+
<div class="serp">
|
|
18
|
+
<div class="serp-url">{url}</div>
|
|
19
|
+
<div class="serp-title">{title || 'Untitled'}</div>
|
|
20
|
+
{#if description}<div class="serp-desc">{description}</div>{/if}
|
|
21
|
+
{#if titleOver || descOver}
|
|
22
|
+
<p class="serp-hint">
|
|
23
|
+
{#if titleOver}The title is over the recommended length ({TITLE_MAX}) and may be cut off. {/if}
|
|
24
|
+
{#if descOver}The description is over the recommended length ({DESC_MAX}) and may be cut off.{/if}
|
|
25
|
+
</p>
|
|
26
|
+
{/if}
|
|
27
|
+
</div>
|
|
28
|
+
|
|
29
|
+
<style>
|
|
30
|
+
.serp {
|
|
31
|
+
font-family: Arial, sans-serif;
|
|
32
|
+
max-width: 600px;
|
|
33
|
+
padding: 12px 16px;
|
|
34
|
+
background: #fff;
|
|
35
|
+
color: #4d5156;
|
|
36
|
+
border: 1px solid #dadce0;
|
|
37
|
+
border-radius: 8px;
|
|
38
|
+
}
|
|
39
|
+
.serp-url {
|
|
40
|
+
font-size: 12px;
|
|
41
|
+
line-height: 1.4;
|
|
42
|
+
color: #202124;
|
|
43
|
+
overflow: hidden;
|
|
44
|
+
text-overflow: ellipsis;
|
|
45
|
+
white-space: nowrap;
|
|
46
|
+
}
|
|
47
|
+
.serp-title {
|
|
48
|
+
font-size: 20px;
|
|
49
|
+
line-height: 1.3;
|
|
50
|
+
color: #1a0dab;
|
|
51
|
+
margin: 2px 0;
|
|
52
|
+
}
|
|
53
|
+
.serp-desc {
|
|
54
|
+
font-size: 14px;
|
|
55
|
+
line-height: 1.58;
|
|
56
|
+
}
|
|
57
|
+
.serp-hint {
|
|
58
|
+
margin: 8px 0 0;
|
|
59
|
+
font-size: 12px;
|
|
60
|
+
color: #b3261e;
|
|
61
|
+
}
|
|
62
|
+
</style>
|