@rimelight/seo 0.0.5 → 0.0.6

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.
@@ -1,74 +1,172 @@
1
- import type { AstroIntegration } from "astro"
2
- import type { RobotsOptions, SitemapUrl, LlmsTxtOptions } from "./types.js"
3
-
4
- export interface RimelightSeoOptions {
5
- /**
6
- * Sitemap configuration or false to disable automatic /sitemap.xml
7
- */
8
- sitemap?:
9
- | boolean
10
- | {
11
- urls?: SitemapUrl[]
12
- [key: string]: any
13
- }
14
- /**
15
- * Robots.txt configuration or false to disable automatic /robots.txt
16
- */
17
- robots?: boolean | RobotsOptions
18
- /**
19
- * LLMs.txt configuration or false to disable automatic /llms.txt
20
- */
21
- llms?: boolean | LlmsTxtOptions
22
- }
23
-
24
- export function rimelightSeo(options: RimelightSeoOptions = {}): AstroIntegration {
25
- return {
26
- name: "@rimelight/seo",
27
- hooks: {
28
- "astro:config:setup": ({ injectRoute, updateConfig }) => {
29
- if (options.robots !== false) {
30
- injectRoute({
31
- pattern: "/robots.txt",
32
- entrypoint: "@rimelight/seo/routes/robots.txt.ts"
33
- })
34
- }
35
-
36
- if (options.sitemap !== false) {
37
- injectRoute({
38
- pattern: "/sitemap.xml",
39
- entrypoint: "@rimelight/seo/routes/sitemap.xml.ts"
40
- })
41
- }
42
-
43
- if (options.llms !== false) {
44
- injectRoute({
45
- pattern: "/llms.txt",
46
- entrypoint: "@rimelight/seo/routes/llms.txt.ts"
47
- })
48
- }
49
-
50
- updateConfig({
51
- vite: {
52
- plugins: [
53
- {
54
- name: "vite-plugin-rimelight-seo",
55
- resolveId(id) {
56
- if (id === "virtual:rimelight-seo-config") {
57
- return "\0virtual:rimelight-seo-config"
58
- }
59
- return null
60
- },
61
- load(id) {
62
- if (id === "\0virtual:rimelight-seo-config") {
63
- return `export default ${JSON.stringify(options)};`
64
- }
65
- return null
66
- }
67
- }
68
- ]
69
- }
70
- })
71
- }
72
- }
73
- }
74
- }
1
+ import type { AstroIntegration } from "astro"
2
+ import path from "node:path"
3
+ import fs from "node:fs"
4
+ import { fileURLToPath } from "node:url"
5
+ import type { RimelightSeoOptions } from "./types.js"
6
+
7
+ export { type RimelightSeoOptions } from "./types.js"
8
+
9
+ export function rimelightSeo(options: RimelightSeoOptions = {}): AstroIntegration {
10
+ return {
11
+ name: "@rimelight/seo",
12
+ hooks: {
13
+ "astro:config:setup": ({ injectRoute, updateConfig, config }) => {
14
+ const rootDir = fileURLToPath(config.root)
15
+
16
+ // Resolve site files
17
+ const findFile = (candidates: string[]): string | null => {
18
+ for (const c of candidates) {
19
+ const resolved = path.resolve(rootDir, c)
20
+ if (fs.existsSync(resolved)) return resolved
21
+ }
22
+ return null
23
+ }
24
+
25
+ const seoConfigPath = findFile([
26
+ "src/config/seo.config.ts",
27
+ "src/config/seo.config.js",
28
+ "src/config/seo.config.mjs"
29
+ ])
30
+
31
+ const siteConfigPath = findFile([
32
+ "src/config/site.config.ts",
33
+ "src/config/site.config.js",
34
+ "src/config/site.config.mjs"
35
+ ])
36
+
37
+ const dbPath = findFile(["src/db/index.ts", "src/db/index.js", "src/db/index.mjs"])
38
+
39
+ const corpusPath = findFile([
40
+ "src/config/llms.corpus.ts",
41
+ "src/config/llms.corpus.js",
42
+ "src/config/llms.corpus.mjs"
43
+ ])
44
+
45
+ // Inject routes
46
+ if (options.robots !== false) {
47
+ const pattern =
48
+ typeof options.robots === "object" && options.robots.path
49
+ ? options.robots.path
50
+ : "/robots.txt"
51
+ injectRoute({
52
+ pattern,
53
+ entrypoint: "@rimelight/seo/routes/robots.txt.ts"
54
+ })
55
+ }
56
+
57
+ if (options.sitemap !== false) {
58
+ const pattern =
59
+ typeof options.sitemap === "object" && options.sitemap.path
60
+ ? options.sitemap.path
61
+ : "/sitemap.xml"
62
+ injectRoute({
63
+ pattern,
64
+ entrypoint: "@rimelight/seo/routes/sitemap.xml.ts"
65
+ })
66
+ }
67
+
68
+ if (options.rss !== false) {
69
+ const pattern =
70
+ typeof options.rss === "object" && options.rss.path ? options.rss.path : "/rss.xml"
71
+ injectRoute({
72
+ pattern,
73
+ entrypoint: "@rimelight/seo/routes/rss.xml.ts"
74
+ })
75
+ }
76
+
77
+ if (options.llms !== false) {
78
+ const pattern =
79
+ typeof options.llms === "object" && options.llms.path ? options.llms.path : "/llms.txt"
80
+ injectRoute({
81
+ pattern,
82
+ entrypoint: "@rimelight/seo/routes/llms.txt.ts"
83
+ })
84
+ }
85
+
86
+ if (options.llmsFull !== false) {
87
+ const pattern =
88
+ typeof options.llmsFull === "object" && options.llmsFull.path
89
+ ? options.llmsFull.path
90
+ : "/llms-full.txt"
91
+ injectRoute({
92
+ pattern,
93
+ entrypoint: "@rimelight/seo/routes/llms-full.txt.ts"
94
+ })
95
+ }
96
+
97
+ updateConfig({
98
+ vite: {
99
+ plugins: [
100
+ {
101
+ name: "vite-plugin-rimelight-seo",
102
+ resolveId(id) {
103
+ if (
104
+ id === "virtual:rimelight-seo-config" ||
105
+ id === "virtual:rimelight-seo/options"
106
+ ) {
107
+ return "\0virtual:rimelight-seo/options"
108
+ }
109
+ if (id === "virtual:rimelight-seo/config") {
110
+ return "\0virtual:rimelight-seo/config"
111
+ }
112
+ if (id === "virtual:rimelight-seo/site-config") {
113
+ return "\0virtual:rimelight-seo/site-config"
114
+ }
115
+ if (id === "virtual:rimelight-seo/db") {
116
+ return "\0virtual:rimelight-seo/db"
117
+ }
118
+ if (id === "virtual:rimelight-seo/corpus") {
119
+ return "\0virtual:rimelight-seo/corpus"
120
+ }
121
+ return null
122
+ },
123
+ load(id) {
124
+ if (id === "\0virtual:rimelight-seo/options") {
125
+ return `export default ${JSON.stringify(options)};`
126
+ }
127
+ if (id === "\0virtual:rimelight-seo/config") {
128
+ if (seoConfigPath) {
129
+ return `import * as customConfig from ${JSON.stringify(seoConfigPath)};
130
+ export const SEO_LOCALES = customConfig.SEO_LOCALES;
131
+ export const PRIVATE_PATH_PREFIXES = customConfig.PRIVATE_PATH_PREFIXES || [];
132
+ export const seoEntries = customConfig.seoEntries;
133
+ export const rssEntries = customConfig.rssEntries;
134
+ export default customConfig;`
135
+ }
136
+ return `export const SEO_LOCALES = undefined;
137
+ export const PRIVATE_PATH_PREFIXES = [];
138
+ export const seoEntries = async () => [];
139
+ export const rssEntries = undefined;`
140
+ }
141
+ if (id === "\0virtual:rimelight-seo/site-config") {
142
+ if (siteConfigPath) {
143
+ return `export * from ${JSON.stringify(siteConfigPath)};`
144
+ }
145
+ return `export const siteConfig = { name: "Site", description: "", url: "" };`
146
+ }
147
+ if (id === "\0virtual:rimelight-seo/db") {
148
+ if (dbPath) {
149
+ return `export * from ${JSON.stringify(dbPath)};`
150
+ }
151
+ return `export const db = null;
152
+ export const pages = null;`
153
+ }
154
+ if (id === "\0virtual:rimelight-seo/corpus") {
155
+ if (corpusPath) {
156
+ return `export * from ${JSON.stringify(corpusPath)};`
157
+ }
158
+ return `export const corpusPages = [];`
159
+ }
160
+ return null
161
+ }
162
+ }
163
+ ]
164
+ }
165
+ })
166
+ }
167
+ }
168
+ }
169
+ }
170
+
171
+ export default rimelightSeo
172
+
package/src/og.ts ADDED
@@ -0,0 +1,444 @@
1
+ /**
2
+ * Font configuration for OG image rendering. Pass to `loadOgFonts()` or `renderOgResponse()`.
3
+ */
4
+ export interface OgFontConfig {
5
+ /**
6
+ * Font-family name referenced in layout styles
7
+ */
8
+ name: string
9
+ /**
10
+ * URL to the regular-weight TTF
11
+ */
12
+ regularUrl: string
13
+ /**
14
+ * URL to the bold-weight TTF
15
+ */
16
+ boldUrl: string
17
+ }
18
+
19
+ /**
20
+ * Default font: Noto Sans from jsDelivr Fontsource CDN.
21
+ */
22
+ export const NOTO_SANS: OgFontConfig = {
23
+ name: "Noto Sans",
24
+ regularUrl: "https://cdn.jsdelivr.net/fontsource/fonts/noto-sans@latest/latin-400-normal.ttf",
25
+ boldUrl: "https://cdn.jsdelivr.net/fontsource/fonts/noto-sans@latest/latin-700-normal.ttf"
26
+ }
27
+
28
+ /**
29
+ * Options for the default OG image layout. Build your own layout instead via `renderOgResponse()`
30
+ * directly.
31
+ */
32
+ export interface OgLayoutOptions {
33
+ /**
34
+ * Main heading -- required
35
+ */
36
+ title: string
37
+ /**
38
+ * Subtitle / excerpt beneath the title
39
+ */
40
+ description?: string
41
+ /**
42
+ * Branding shown top-left. Pass a plain string (site name) or a pre-built takumi-js VNode for a
43
+ * custom logo treatment.
44
+ */
45
+ brand?: string | object
46
+ /**
47
+ * Pill badge shown bottom-left. e.g. "Blog Post", "Documentation", "Legal"
48
+ */
49
+ badge?: string
50
+ /**
51
+ * Date string shown bottom-right. e.g. new Date(postedAt).toLocaleDateString()
52
+ */
53
+ date?: string
54
+ /**
55
+ * Background style. "dark" -> solid #0a0a0a (default) "gradient" -> diagonal dark-to-navy
56
+ * gradient any string -> treated as a CSS `background` value
57
+ */
58
+ background?: "dark" | "gradient" | (string & {})
59
+ /**
60
+ * When true, overlays a dashed red PREVIEW border. Useful during development.
61
+ */
62
+ preview?: boolean
63
+ }
64
+
65
+ /**
66
+ * Rendering config shared by `renderOgResponse()` and `renderDefaultOg()`.
67
+ */
68
+ export interface OgRenderConfig {
69
+ /**
70
+ * Font to embed -- defaults to `NOTO_SANS`
71
+ */
72
+ font?: OgFontConfig
73
+ /**
74
+ * Image width in px -- defaults to 1200
75
+ */
76
+ width?: number
77
+ /**
78
+ * Image height in px -- defaults to 630
79
+ */
80
+ height?: number
81
+ }
82
+
83
+ // ---------------------------------------------------------------------------
84
+ // Font loading
85
+ // ---------------------------------------------------------------------------
86
+
87
+ const fontCaches = new Map<string, { regular: ArrayBuffer; bold: ArrayBuffer }>()
88
+
89
+ /**
90
+ * Fetches an ArrayBuffer with a timeout.
91
+ */
92
+ async function fetchArrayBuffer(url: string, timeoutMs = 5000): Promise<ArrayBuffer> {
93
+ const controller = new AbortController()
94
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs)
95
+ try {
96
+ const res = await fetch(url, { signal: controller.signal })
97
+ if (!res.ok) {
98
+ throw new Error(`Failed to fetch font from ${url}: status ${res.status}`)
99
+ }
100
+ return await res.arrayBuffer()
101
+ } finally {
102
+ clearTimeout(timeoutId)
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Fetches and caches the regular + bold TTF buffers for the given font config. Uses a module-level
108
+ * cache keyed on `regularUrl`, so repeated calls within the same Worker lifetime are free after the
109
+ * first fetch.
110
+ */
111
+ export async function loadOgFonts(
112
+ config: OgFontConfig = NOTO_SANS,
113
+ timeoutMs = 5000
114
+ ): Promise<{ regular: ArrayBuffer; bold: ArrayBuffer }> {
115
+ const cached = fontCaches.get(config.regularUrl)
116
+ if (cached) return cached
117
+
118
+ const [regular, bold] = await Promise.all([
119
+ fetchArrayBuffer(config.regularUrl, timeoutMs),
120
+ fetchArrayBuffer(config.boldUrl, timeoutMs)
121
+ ])
122
+ const result = { regular, bold }
123
+ fontCaches.set(config.regularUrl, result)
124
+ return result
125
+ }
126
+
127
+ // ---------------------------------------------------------------------------
128
+ // Default layout builder
129
+ // ---------------------------------------------------------------------------
130
+
131
+ /**
132
+ * Builds a takumi-js-compatible VNode for the default Rimelight OG layout.
133
+ *
134
+ * Consumers that need a fully custom look should build their own VNode and call
135
+ * `renderOgResponse()` directly -- this function is just the house style.
136
+ */
137
+ export function defaultOgLayout(options: OgLayoutOptions, font: OgFontConfig = NOTO_SANS): object {
138
+ const {
139
+ title = "",
140
+ description,
141
+ brand,
142
+ badge,
143
+ date,
144
+ background = "dark",
145
+ preview = false
146
+ } = options
147
+
148
+ const MAX_TITLE_LEN = 160
149
+ const MAX_DESC_LEN = 240
150
+ const safeTitle = title.length > MAX_TITLE_LEN ? title.slice(0, MAX_TITLE_LEN - 1) + "…" : title
151
+ const safeDescription =
152
+ description && description.length > MAX_DESC_LEN
153
+ ? description.slice(0, MAX_DESC_LEN - 1) + "…"
154
+ : description
155
+
156
+ const bg =
157
+ background === "dark"
158
+ ? { backgroundColor: "#0a0a0a" }
159
+ : background === "gradient"
160
+ ? { background: "linear-gradient(135deg, #0a0a0a 0%, #1a1a2e 100%)" }
161
+ : { background }
162
+
163
+ const isGradient = background !== "dark"
164
+
165
+ const brandNode: object =
166
+ typeof brand === "object" && brand !== null
167
+ ? brand
168
+ : {
169
+ type: "span",
170
+ props: {
171
+ style: {
172
+ fontSize: "28px",
173
+ fontWeight: 700,
174
+ color: "#ffffff",
175
+ letterSpacing: "-0.02em"
176
+ },
177
+ children: brand ?? ""
178
+ }
179
+ }
180
+
181
+ const accentBar: object | null = isGradient
182
+ ? {
183
+ type: "div",
184
+ props: {
185
+ style: {
186
+ width: "60px",
187
+ height: "4px",
188
+ backgroundColor: "#60a5fa",
189
+ borderRadius: "2px",
190
+ marginBottom: "16px"
191
+ }
192
+ }
193
+ }
194
+ : null
195
+
196
+ const titleFontSize = isGradient ? "52px" : "56px"
197
+ const descColor = isGradient ? "#94a3b8" : "#a0a0a0"
198
+ const descFontSize = isGradient ? "22px" : "24px"
199
+
200
+ const badgeNode: object | null = badge
201
+ ? isGradient
202
+ ? {
203
+ type: "div",
204
+ props: {
205
+ style: {
206
+ padding: "6px 16px",
207
+ borderRadius: "9999px",
208
+ backgroundColor: "rgba(96,165,250,0.15)",
209
+ border: "1px solid rgba(96,165,250,0.3)",
210
+ fontSize: "14px",
211
+ fontWeight: 600,
212
+ color: "#93c5fd"
213
+ },
214
+ children: badge
215
+ }
216
+ }
217
+ : {
218
+ type: "div",
219
+ props: {
220
+ style: {
221
+ padding: "8px 20px",
222
+ borderRadius: "9999px",
223
+ border: "1px solid #333333",
224
+ fontSize: "16px",
225
+ fontWeight: 600,
226
+ color: "#e5e5e5"
227
+ },
228
+ children: badge
229
+ }
230
+ }
231
+ : null
232
+
233
+ const dateNode: object | null = date
234
+ ? {
235
+ type: "div",
236
+ props: {
237
+ style: { fontSize: "16px", color: "#666666" },
238
+ children: date
239
+ }
240
+ }
241
+ : null
242
+
243
+ const previewOverlay: object | null = preview
244
+ ? {
245
+ type: "div",
246
+ props: {
247
+ style: {
248
+ position: "absolute",
249
+ inset: 0,
250
+ border: "6px dashed #ff4444",
251
+ pointerEvents: "none"
252
+ }
253
+ }
254
+ }
255
+ : null
256
+
257
+ const previewLabel: object | null = preview
258
+ ? {
259
+ type: "div",
260
+ props: {
261
+ style: {
262
+ position: "absolute",
263
+ top: "12px",
264
+ right: "12px",
265
+ backgroundColor: "#ff4444",
266
+ color: "#ffffff",
267
+ fontSize: "14px",
268
+ fontWeight: 700,
269
+ padding: "6px 16px",
270
+ borderRadius: "4px",
271
+ letterSpacing: "0.05em"
272
+ },
273
+ children: "PREVIEW"
274
+ }
275
+ }
276
+ : null
277
+
278
+ return {
279
+ type: "div",
280
+ props: {
281
+ style: {
282
+ width: "100%",
283
+ height: "100%",
284
+ display: "flex",
285
+ flexDirection: "column",
286
+ padding: "56px",
287
+ color: "#e5e5e5",
288
+ fontFamily: font.name,
289
+ position: "relative",
290
+ overflow: "hidden",
291
+ ...bg
292
+ },
293
+ children: [
294
+ {
295
+ type: "div",
296
+ props: {
297
+ style: { display: "flex", alignItems: "center" },
298
+ children: [brandNode]
299
+ }
300
+ },
301
+ {
302
+ type: "div",
303
+ props: {
304
+ style: {
305
+ display: "flex",
306
+ flexDirection: "column",
307
+ justifyContent: "center",
308
+ flexGrow: 1,
309
+ paddingTop: "24px"
310
+ },
311
+ children: [
312
+ accentBar,
313
+ {
314
+ type: "div",
315
+ props: {
316
+ style: {
317
+ fontSize: titleFontSize,
318
+ fontWeight: 700,
319
+ color: "#ffffff",
320
+ lineHeight: 1.15,
321
+ maxWidth: "950px"
322
+ },
323
+ children: safeTitle
324
+ }
325
+ },
326
+ safeDescription
327
+ ? {
328
+ type: "div",
329
+ props: {
330
+ style: {
331
+ fontSize: descFontSize,
332
+ fontWeight: 400,
333
+ color: descColor,
334
+ marginTop: isGradient ? "12px" : "16px",
335
+ lineHeight: 1.4,
336
+ maxWidth: isGradient ? "800px" : "850px"
337
+ },
338
+ children: safeDescription
339
+ }
340
+ }
341
+ : null
342
+ ].filter(Boolean)
343
+ }
344
+ },
345
+ {
346
+ type: "div",
347
+ props: {
348
+ style: {
349
+ display: "flex",
350
+ alignItems: "center",
351
+ justifyContent: isGradient ? "flex-start" : "space-between",
352
+ gap: "12px",
353
+ marginTop: "auto"
354
+ },
355
+ children: [badgeNode, dateNode].filter(Boolean)
356
+ }
357
+ },
358
+ previewOverlay,
359
+ previewLabel
360
+ ].filter(Boolean)
361
+ }
362
+ }
363
+ }
364
+
365
+ // ---------------------------------------------------------------------------
366
+ // Render helpers
367
+ // ---------------------------------------------------------------------------
368
+
369
+ /**
370
+ * Renders any takumi-js VNode to a PNG `Response` with standard OG headers. Use this when you
371
+ * supply your own layout entirely.
372
+ *
373
+ * @example
374
+ * const vnode = myBrandedLayout({ title, description })
375
+ * return renderOgResponse(vnode, { font: MY_FONT })
376
+ */
377
+ export async function renderOgResponse(
378
+ vnode: object,
379
+ config: OgRenderConfig = {}
380
+ ): Promise<Response> {
381
+ const { font = NOTO_SANS, width = 1200, height = 630 } = config
382
+
383
+ try {
384
+ const { render } = await import("takumi-js")
385
+ const { regular, bold } = await loadOgFonts(font)
386
+
387
+ const pngBuffer = await render(vnode, {
388
+ width,
389
+ height,
390
+ fonts: [
391
+ { name: font.name, data: regular, weight: 400, style: "normal" },
392
+ { name: font.name, data: bold, weight: 700, style: "normal" }
393
+ ]
394
+ })
395
+
396
+ return new Response(new Blob([new Uint8Array(pngBuffer)], { type: "image/png" }), {
397
+ status: 200,
398
+ headers: {
399
+ "Content-Type": "image/png",
400
+ "Cache-Control": "public, max-age=31536000, immutable",
401
+ "CDN-Cache-Control": "public, max-age=31536000"
402
+ }
403
+ })
404
+ } catch (error) {
405
+ console.error("[OG Render Error]:", error)
406
+ return new Response(
407
+ JSON.stringify({
408
+ error: "Failed to render Open Graph image",
409
+ message: error instanceof Error ? error.message : String(error)
410
+ }),
411
+ {
412
+ status: 500,
413
+ headers: {
414
+ "Content-Type": "application/json",
415
+ "Cache-Control": "no-store"
416
+ }
417
+ }
418
+ )
419
+ }
420
+ }
421
+
422
+ /**
423
+ * Renders the default OG layout to a PNG `Response`. The 90% case -- use `renderOgResponse()` for
424
+ * full layout control.
425
+ *
426
+ * @example
427
+ * export const GET: APIRoute = async ({ request }) => {
428
+ * const url = new URL(request.url)
429
+ * return renderDefaultOg({
430
+ * title: url.searchParams.get("title") ?? "Untitled",
431
+ * description: url.searchParams.get("description") ?? "",
432
+ * brand: "My Site",
433
+ * badge: url.searchParams.get("type") ?? ""
434
+ * })
435
+ * }
436
+ */
437
+ export async function renderDefaultOg(
438
+ options: OgLayoutOptions,
439
+ config: OgRenderConfig = {}
440
+ ): Promise<Response> {
441
+ const { font = NOTO_SANS } = config
442
+ const vnode = defaultOgLayout(options, font)
443
+ return renderOgResponse(vnode, config)
444
+ }