@growth-labs/opengraph 0.2.0 → 0.2.1
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/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -1
- package/dist/index.js.map +1 -1
- package/package.json +9 -4
- package/src/index.ts +50 -0
- package/src/options.ts +54 -0
- package/src/routes/og.ts +91 -0
- package/src/state.ts +22 -0
- package/src/types.ts +55 -0
- package/src/utils/generate.ts +117 -0
- package/src/utils/index.ts +4 -0
- package/src/utils/r2.ts +61 -0
- package/src/utils/template.ts +168 -0
- package/src/utils/url.ts +39 -0
- package/src/virtual.d.ts +9 -0
- package/src/vite-plugin.ts +24 -0
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,OAAO,CAAA;AAC7C,OAAO,EAAE,KAAK,gBAAgB,EAA0B,MAAM,cAAc,CAAA;AAU5E,MAAM,CAAC,OAAO,UAAU,SAAS,CAAC,WAAW,EAAE,gBAAgB,GAAG,gBAAgB,CA4BjF;AAED,YAAY,EAAE,gBAAgB,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAA;AAC9E,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAA;AACrD,YAAY,EAAE,SAAS,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAE/E,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAA;AACrD,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAA;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAA;AACrD,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA"}
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
1
2
|
import { opengraphOptionsSchema } from './options.js';
|
|
2
3
|
import { _setContentProvider, _setTemplate } from './state.js';
|
|
3
4
|
import { growthLabsOpengraphPlugin } from './vite-plugin.js';
|
|
5
|
+
const ENTRYPOINT_EXTENSION = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
|
|
6
|
+
function resolveEntrypoint(path) {
|
|
7
|
+
return fileURLToPath(new URL(`${path}${ENTRYPOINT_EXTENSION}`, import.meta.url));
|
|
8
|
+
}
|
|
4
9
|
export default function opengraph(userOptions) {
|
|
5
10
|
const options = opengraphOptionsSchema.parse(userOptions);
|
|
6
11
|
if (userOptions.contentProvider) {
|
|
@@ -19,7 +24,7 @@ export default function opengraph(userOptions) {
|
|
|
19
24
|
if (options.route.enabled) {
|
|
20
25
|
injectRoute({
|
|
21
26
|
pattern: `/og/[...path].${options.format}`,
|
|
22
|
-
entrypoint: '
|
|
27
|
+
entrypoint: resolveEntrypoint('./routes/og'),
|
|
23
28
|
prerender: false,
|
|
24
29
|
});
|
|
25
30
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAExC,OAAO,EAAyB,sBAAsB,EAAE,MAAM,cAAc,CAAA;AAC5E,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAC9D,OAAO,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAA;AAE5D,MAAM,oBAAoB,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAA;AAE5E,SAAS,iBAAiB,CAAC,IAAY;IACtC,OAAO,aAAa,CAAC,IAAI,GAAG,CAAC,GAAG,IAAI,GAAG,oBAAoB,EAAE,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAA;AACjF,CAAC;AAED,MAAM,CAAC,OAAO,UAAU,SAAS,CAAC,WAA6B;IAC9D,MAAM,OAAO,GAAG,sBAAsB,CAAC,KAAK,CAAC,WAAW,CAAC,CAAA;IAEzD,IAAI,WAAW,CAAC,eAAe,EAAE,CAAC;QACjC,mBAAmB,CAAC,WAAW,CAAC,eAAe,CAAC,CAAA;IACjD,CAAC;IACD,IAAI,WAAW,CAAC,QAAQ,EAAE,CAAC;QAC1B,YAAY,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAA;IACnC,CAAC;IAED,OAAO;QACN,IAAI,EAAE,wBAAwB;QAC9B,KAAK,EAAE;YACN,oBAAoB,EAAE,CAAC,EAAE,WAAW,EAAE,YAAY,EAAE,EAAE,EAAE;gBACvD,YAAY,CAAC;oBACZ,IAAI,EAAE,EAAE,OAAO,EAAE,CAAC,yBAAyB,CAAC,OAAO,CAAC,CAAC,EAAE;iBACvD,CAAC,CAAA;gBAEF,IAAI,OAAO,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;oBAC3B,WAAW,CAAC;wBACX,OAAO,EAAE,iBAAiB,OAAO,CAAC,MAAM,EAAE;wBAC1C,UAAU,EAAE,iBAAiB,CAAC,aAAa,CAAC;wBAC5C,SAAS,EAAE,KAAK;qBAChB,CAAC,CAAA;gBACH,CAAC;YACF,CAAC;SACD;KACD,CAAA;AACF,CAAC;AAGD,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAA;AAErD,6CAA6C;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAA;AACrD,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAA;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAA;AACrD,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@growth-labs/opengraph",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"types": "./dist/index.d.ts",
|
|
6
6
|
"exports": {
|
|
@@ -24,6 +24,11 @@
|
|
|
24
24
|
},
|
|
25
25
|
"files": [
|
|
26
26
|
"dist",
|
|
27
|
+
"src/**/*.ts",
|
|
28
|
+
"src/**/*.astro",
|
|
29
|
+
"src/**/*.css",
|
|
30
|
+
"src/**/*.md",
|
|
31
|
+
"src/**/*.sql",
|
|
27
32
|
"README.md"
|
|
28
33
|
],
|
|
29
34
|
"publishConfig": {
|
|
@@ -35,13 +40,13 @@
|
|
|
35
40
|
"zod": "^3.23.0"
|
|
36
41
|
},
|
|
37
42
|
"peerDependencies": {
|
|
38
|
-
"astro": "^6.
|
|
43
|
+
"astro": "^6.1.10"
|
|
39
44
|
},
|
|
40
45
|
"devDependencies": {
|
|
41
46
|
"@cloudflare/workers-types": "^4.20241230.0",
|
|
42
|
-
"astro": "^6.
|
|
47
|
+
"astro": "^6.1.10",
|
|
43
48
|
"typescript": "^5.7.0",
|
|
44
|
-
"vite": "^7.
|
|
49
|
+
"vite": "^7.3.2",
|
|
45
50
|
"vitest": "^3.0.0"
|
|
46
51
|
},
|
|
47
52
|
"scripts": {
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url'
|
|
2
|
+
import type { AstroIntegration } from 'astro'
|
|
3
|
+
import { type OpengraphOptions, opengraphOptionsSchema } from './options.js'
|
|
4
|
+
import { _setContentProvider, _setTemplate } from './state.js'
|
|
5
|
+
import { growthLabsOpengraphPlugin } from './vite-plugin.js'
|
|
6
|
+
|
|
7
|
+
const ENTRYPOINT_EXTENSION = import.meta.url.endsWith('.ts') ? '.ts' : '.js'
|
|
8
|
+
|
|
9
|
+
function resolveEntrypoint(path: string): string {
|
|
10
|
+
return fileURLToPath(new URL(`${path}${ENTRYPOINT_EXTENSION}`, import.meta.url))
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export default function opengraph(userOptions: OpengraphOptions): AstroIntegration {
|
|
14
|
+
const options = opengraphOptionsSchema.parse(userOptions)
|
|
15
|
+
|
|
16
|
+
if (userOptions.contentProvider) {
|
|
17
|
+
_setContentProvider(userOptions.contentProvider)
|
|
18
|
+
}
|
|
19
|
+
if (userOptions.template) {
|
|
20
|
+
_setTemplate(userOptions.template)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
return {
|
|
24
|
+
name: '@growth-labs/opengraph',
|
|
25
|
+
hooks: {
|
|
26
|
+
'astro:config:setup': ({ injectRoute, updateConfig }) => {
|
|
27
|
+
updateConfig({
|
|
28
|
+
vite: { plugins: [growthLabsOpengraphPlugin(options)] },
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
if (options.route.enabled) {
|
|
32
|
+
injectRoute({
|
|
33
|
+
pattern: `/og/[...path].${options.format}`,
|
|
34
|
+
entrypoint: resolveEntrypoint('./routes/og'),
|
|
35
|
+
prerender: false,
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export type { OpengraphOptions, ResolvedOpengraphOptions } from './options.js'
|
|
44
|
+
export { opengraphOptionsSchema } from './options.js'
|
|
45
|
+
export type { OgContext, OgGenerationResult, OgTemplateData } from './types.js'
|
|
46
|
+
// Re-export utilities for direct consumption
|
|
47
|
+
export { generateOgImage } from './utils/generate.js'
|
|
48
|
+
export { invalidateCache } from './utils/r2.js'
|
|
49
|
+
export { defaultTemplate } from './utils/template.js'
|
|
50
|
+
export { getOgDiscoverUrl, getOgImageUrl, getOgUrls } from './utils/url.js'
|
package/src/options.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
|
|
3
|
+
const brandColorsSchema = z.object({
|
|
4
|
+
primary: z.string(),
|
|
5
|
+
accent: z.string().optional(),
|
|
6
|
+
background: z.string().optional(),
|
|
7
|
+
text: z.string().optional(),
|
|
8
|
+
})
|
|
9
|
+
|
|
10
|
+
export const opengraphOptionsSchema = z.object({
|
|
11
|
+
// Required
|
|
12
|
+
publicDomain: z.string(),
|
|
13
|
+
|
|
14
|
+
// R2
|
|
15
|
+
r2Binding: z.string().default('MEDIA_BUCKET'),
|
|
16
|
+
r2Prefix: z.string().default('og/'),
|
|
17
|
+
|
|
18
|
+
// Browser Rendering
|
|
19
|
+
browserBinding: z.string().default('BROWSER'),
|
|
20
|
+
|
|
21
|
+
// Brand configuration
|
|
22
|
+
brandName: z.string().optional(),
|
|
23
|
+
brandColors: brandColorsSchema.optional(),
|
|
24
|
+
logoUrl: z.string().url().optional(),
|
|
25
|
+
defaultSubtitle: z.string().optional(),
|
|
26
|
+
fontFamily: z.string().default('Inter'),
|
|
27
|
+
fontWeight: z.string().default('600'),
|
|
28
|
+
|
|
29
|
+
// Custom template
|
|
30
|
+
template: z.function().args(z.any()).returns(z.string()).optional(),
|
|
31
|
+
|
|
32
|
+
// Route
|
|
33
|
+
route: z
|
|
34
|
+
.object({
|
|
35
|
+
enabled: z.boolean().default(true),
|
|
36
|
+
regenerateSecret: z.string().optional(),
|
|
37
|
+
})
|
|
38
|
+
.default({}),
|
|
39
|
+
|
|
40
|
+
// Content provider (for on-demand generation)
|
|
41
|
+
contentProvider: z
|
|
42
|
+
.function()
|
|
43
|
+
.args(z.string(), z.any())
|
|
44
|
+
.returns(z.promise(z.any().nullable()))
|
|
45
|
+
.optional(),
|
|
46
|
+
|
|
47
|
+
// Generation
|
|
48
|
+
quality: z.number().min(1).max(100).default(90),
|
|
49
|
+
format: z.enum(['png', 'jpeg']).default('png'),
|
|
50
|
+
timeout: z.number().default(10_000),
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
export type OpengraphOptions = z.input<typeof opengraphOptionsSchema>
|
|
54
|
+
export type ResolvedOpengraphOptions = z.output<typeof opengraphOptionsSchema>
|
package/src/routes/og.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { env } from 'cloudflare:workers'
|
|
2
|
+
import { getContentProvider, options } from 'virtual:growth-labs/opengraph/config'
|
|
3
|
+
import type { APIRoute } from 'astro'
|
|
4
|
+
import type { OgGenerationResult } from '../types.js'
|
|
5
|
+
import { generateOgImage } from '../utils/generate.js'
|
|
6
|
+
import { getCached, ogDiscoverKey, ogKey } from '../utils/r2.js'
|
|
7
|
+
|
|
8
|
+
export const prerender = false
|
|
9
|
+
|
|
10
|
+
export const GET: APIRoute = async (context) => {
|
|
11
|
+
const envMap = env as Record<string, unknown>
|
|
12
|
+
const r2 = envMap[options.r2Binding] as R2Bucket
|
|
13
|
+
const browser = envMap[options.browserBinding] as Fetcher
|
|
14
|
+
|
|
15
|
+
const rawPath = context.params.path ?? ''
|
|
16
|
+
const format = options.format
|
|
17
|
+
|
|
18
|
+
// Determine if this is a Discover variant request
|
|
19
|
+
const isDiscover = rawPath.endsWith('-discover')
|
|
20
|
+
const pagePath = isDiscover ? `/${rawPath.slice(0, -'-discover'.length)}` : `/${rawPath}`
|
|
21
|
+
|
|
22
|
+
// Check for regeneration request
|
|
23
|
+
const url = new URL(context.request.url)
|
|
24
|
+
const wantsRegenerate = url.searchParams.get('regenerate') === 'true'
|
|
25
|
+
const secret = url.searchParams.get('secret')
|
|
26
|
+
|
|
27
|
+
if (wantsRegenerate) {
|
|
28
|
+
if (!options.route.regenerateSecret || secret !== options.route.regenerateSecret) {
|
|
29
|
+
return new Response('Unauthorized', { status: 401 })
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Try serving from R2 cache
|
|
34
|
+
if (!wantsRegenerate) {
|
|
35
|
+
const key = isDiscover
|
|
36
|
+
? ogDiscoverKey(options.r2Prefix, pagePath, format)
|
|
37
|
+
: ogKey(options.r2Prefix, pagePath, format)
|
|
38
|
+
|
|
39
|
+
const cached = await getCached(r2, key)
|
|
40
|
+
|
|
41
|
+
if (cached) {
|
|
42
|
+
const contentType = format === 'jpeg' ? 'image/jpeg' : 'image/png'
|
|
43
|
+
return new Response(cached.body, {
|
|
44
|
+
headers: {
|
|
45
|
+
'Content-Type': contentType,
|
|
46
|
+
'Cache-Control': 'public, max-age=31536000, immutable',
|
|
47
|
+
'X-OG-Cache': 'HIT',
|
|
48
|
+
},
|
|
49
|
+
})
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Cache miss — need contentProvider
|
|
54
|
+
const contentProvider = getContentProvider()
|
|
55
|
+
if (!contentProvider) {
|
|
56
|
+
return new Response(
|
|
57
|
+
'OG image not found. Pre-generate via generateOgImage() or configure contentProvider.',
|
|
58
|
+
{ status: 404 },
|
|
59
|
+
)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const pageData = await contentProvider(pagePath, context)
|
|
63
|
+
if (!pageData) {
|
|
64
|
+
return new Response('Page not found', { status: 404 })
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
let result: OgGenerationResult
|
|
68
|
+
try {
|
|
69
|
+
result = await generateOgImage(pagePath, pageData, { r2, browser }, options, wantsRegenerate)
|
|
70
|
+
} catch (error) {
|
|
71
|
+
console.error(`OG image generation failed for ${pagePath}:`, error)
|
|
72
|
+
return new Response('Generation failed', { status: 500 })
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Serve the requested variant
|
|
76
|
+
const key = isDiscover ? result.discover.key : result.og.key
|
|
77
|
+
const object = await r2.get(key)
|
|
78
|
+
|
|
79
|
+
if (!object) {
|
|
80
|
+
return new Response('Generation failed', { status: 500 })
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const contentType = format === 'jpeg' ? 'image/jpeg' : 'image/png'
|
|
84
|
+
return new Response(object.body, {
|
|
85
|
+
headers: {
|
|
86
|
+
'Content-Type': contentType,
|
|
87
|
+
'Cache-Control': 'public, max-age=31536000, immutable',
|
|
88
|
+
'X-OG-Cache': 'MISS',
|
|
89
|
+
},
|
|
90
|
+
})
|
|
91
|
+
}
|
package/src/state.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
let _contentProvider: ((pagePath: string, context: any) => Promise<any>) | undefined
|
|
2
|
+
let _template: ((data: any) => string) | undefined
|
|
3
|
+
|
|
4
|
+
export function _setContentProvider(
|
|
5
|
+
provider: (pagePath: string, context: any) => Promise<any>,
|
|
6
|
+
): void {
|
|
7
|
+
_contentProvider = provider
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function _setTemplate(template: (data: any) => string): void {
|
|
11
|
+
_template = template
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function getContentProvider():
|
|
15
|
+
| ((pagePath: string, context: any) => Promise<any>)
|
|
16
|
+
| undefined {
|
|
17
|
+
return _contentProvider
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function getTemplate(): ((data: any) => string) | undefined {
|
|
21
|
+
return _template
|
|
22
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Data passed to the template function (built-in or custom).
|
|
3
|
+
*/
|
|
4
|
+
export interface OgTemplateData {
|
|
5
|
+
title: string
|
|
6
|
+
subtitle?: string
|
|
7
|
+
description?: string
|
|
8
|
+
category?: string
|
|
9
|
+
authorName?: string
|
|
10
|
+
authorImageUrl?: string
|
|
11
|
+
pageType?:
|
|
12
|
+
| 'article'
|
|
13
|
+
| 'category'
|
|
14
|
+
| 'author'
|
|
15
|
+
| 'search'
|
|
16
|
+
| 'landing'
|
|
17
|
+
| 'newsletter'
|
|
18
|
+
| 'product'
|
|
19
|
+
| 'generic'
|
|
20
|
+
|
|
21
|
+
brandName?: string
|
|
22
|
+
brandColors?: {
|
|
23
|
+
primary: string
|
|
24
|
+
accent?: string
|
|
25
|
+
background?: string
|
|
26
|
+
text?: string
|
|
27
|
+
}
|
|
28
|
+
logoUrl?: string
|
|
29
|
+
fontFamily: string
|
|
30
|
+
fontWeight: string
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Result of a generation call.
|
|
35
|
+
*/
|
|
36
|
+
export interface OgGenerationResult {
|
|
37
|
+
og: {
|
|
38
|
+
key: string
|
|
39
|
+
url: string
|
|
40
|
+
}
|
|
41
|
+
discover: {
|
|
42
|
+
key: string
|
|
43
|
+
url: string
|
|
44
|
+
}
|
|
45
|
+
cached: boolean
|
|
46
|
+
generatedAt: string
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Context object providing access to Cloudflare bindings.
|
|
51
|
+
*/
|
|
52
|
+
export interface OgContext {
|
|
53
|
+
r2: R2Bucket
|
|
54
|
+
browser: Fetcher
|
|
55
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import puppeteer from '@cloudflare/puppeteer'
|
|
2
|
+
import type { ResolvedOpengraphOptions } from '../options.js'
|
|
3
|
+
import type { OgContext, OgGenerationResult, OgTemplateData } from '../types.js'
|
|
4
|
+
import { getCached, ogDiscoverKey, ogKey, writeToR2 } from './r2.js'
|
|
5
|
+
import { defaultTemplate } from './template.js'
|
|
6
|
+
|
|
7
|
+
function toExactArrayBuffer(bytes: Uint8Array): ArrayBuffer {
|
|
8
|
+
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Generate OG images for a page. Checks R2 cache first; on miss,
|
|
13
|
+
* renders the template via Browser Rendering and writes both sizes to R2.
|
|
14
|
+
*/
|
|
15
|
+
export async function generateOgImage(
|
|
16
|
+
pagePath: string,
|
|
17
|
+
data: OgTemplateData,
|
|
18
|
+
context: OgContext,
|
|
19
|
+
options: ResolvedOpengraphOptions,
|
|
20
|
+
force = false,
|
|
21
|
+
): Promise<OgGenerationResult> {
|
|
22
|
+
const format = options.format
|
|
23
|
+
const contentType = format === 'jpeg' ? 'image/jpeg' : 'image/png'
|
|
24
|
+
const keyOg = ogKey(options.r2Prefix, pagePath, format)
|
|
25
|
+
const keyDiscover = ogDiscoverKey(options.r2Prefix, pagePath, format)
|
|
26
|
+
const now = new Date().toISOString()
|
|
27
|
+
|
|
28
|
+
// Check R2 cache (both sizes must be present and title must match)
|
|
29
|
+
if (!force) {
|
|
30
|
+
const cachedOg = await getCached(context.r2, keyOg, data.title)
|
|
31
|
+
const cachedDiscover = await getCached(context.r2, keyDiscover, data.title)
|
|
32
|
+
|
|
33
|
+
if (cachedOg && cachedDiscover) {
|
|
34
|
+
return {
|
|
35
|
+
og: {
|
|
36
|
+
key: keyOg,
|
|
37
|
+
url: `https://${options.publicDomain}/${keyOg}`,
|
|
38
|
+
},
|
|
39
|
+
discover: {
|
|
40
|
+
key: keyDiscover,
|
|
41
|
+
url: `https://${options.publicDomain}/${keyDiscover}`,
|
|
42
|
+
},
|
|
43
|
+
cached: true,
|
|
44
|
+
generatedAt: cachedOg.customMetadata?.['x-og-generated-at'] ?? now,
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Populate brand data from options into template data
|
|
50
|
+
const templateData: OgTemplateData = {
|
|
51
|
+
...data,
|
|
52
|
+
brandName: data.brandName ?? options.brandName,
|
|
53
|
+
brandColors: data.brandColors ?? options.brandColors,
|
|
54
|
+
logoUrl: data.logoUrl ?? options.logoUrl,
|
|
55
|
+
fontFamily: options.fontFamily,
|
|
56
|
+
fontWeight: options.fontWeight,
|
|
57
|
+
subtitle: data.subtitle ?? options.defaultSubtitle,
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Render HTML template
|
|
61
|
+
const templateFn = options.template ?? defaultTemplate
|
|
62
|
+
const html = templateFn(templateData)
|
|
63
|
+
|
|
64
|
+
// Browser Rendering: one session, two screenshots
|
|
65
|
+
const browser = await puppeteer.launch(context.browser)
|
|
66
|
+
let ogBuffer: ArrayBuffer
|
|
67
|
+
let discoverBuffer: ArrayBuffer
|
|
68
|
+
|
|
69
|
+
try {
|
|
70
|
+
const page = await browser.newPage()
|
|
71
|
+
|
|
72
|
+
// Set viewport to the larger size (1200x675 Discover)
|
|
73
|
+
await page.setViewport({ width: 1200, height: 675, deviceScaleFactor: 1 })
|
|
74
|
+
await page.setContent(html, {
|
|
75
|
+
waitUntil: 'networkidle0',
|
|
76
|
+
timeout: options.timeout,
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
// Screenshot 1: Discover size (full viewport, 1200x675)
|
|
80
|
+
const discoverScreenshot = (await page.screenshot({
|
|
81
|
+
type: format === 'jpeg' ? 'jpeg' : undefined,
|
|
82
|
+
quality: format === 'jpeg' ? options.quality : undefined,
|
|
83
|
+
clip: { x: 0, y: 0, width: 1200, height: 675 },
|
|
84
|
+
})) as Buffer
|
|
85
|
+
discoverBuffer = toExactArrayBuffer(discoverScreenshot)
|
|
86
|
+
|
|
87
|
+
// Screenshot 2: OG size (center-cropped to 1200x630)
|
|
88
|
+
const ogScreenshot = (await page.screenshot({
|
|
89
|
+
type: format === 'jpeg' ? 'jpeg' : undefined,
|
|
90
|
+
quality: format === 'jpeg' ? options.quality : undefined,
|
|
91
|
+
clip: { x: 0, y: 0, width: 1200, height: 630 },
|
|
92
|
+
})) as Buffer
|
|
93
|
+
ogBuffer = toExactArrayBuffer(ogScreenshot)
|
|
94
|
+
} finally {
|
|
95
|
+
await browser.close()
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Write both images to R2
|
|
99
|
+
const writeMetadata = { title: data.title, generatedAt: now, contentType }
|
|
100
|
+
await Promise.all([
|
|
101
|
+
writeToR2(context.r2, keyOg, ogBuffer, writeMetadata),
|
|
102
|
+
writeToR2(context.r2, keyDiscover, discoverBuffer, writeMetadata),
|
|
103
|
+
])
|
|
104
|
+
|
|
105
|
+
return {
|
|
106
|
+
og: {
|
|
107
|
+
key: keyOg,
|
|
108
|
+
url: `https://${options.publicDomain}/${keyOg}`,
|
|
109
|
+
},
|
|
110
|
+
discover: {
|
|
111
|
+
key: keyDiscover,
|
|
112
|
+
url: `https://${options.publicDomain}/${keyDiscover}`,
|
|
113
|
+
},
|
|
114
|
+
cached: false,
|
|
115
|
+
generatedAt: now,
|
|
116
|
+
}
|
|
117
|
+
}
|
package/src/utils/r2.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { normalizePagePath } from './url.js'
|
|
2
|
+
|
|
3
|
+
export function ogKey(prefix: string, pagePath: string, format: string): string {
|
|
4
|
+
const normalizedPath = normalizePagePath(pagePath)
|
|
5
|
+
return `${prefix}${normalizedPath}.${format}`
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function ogDiscoverKey(prefix: string, pagePath: string, format: string): string {
|
|
9
|
+
const normalizedPath = normalizePagePath(pagePath)
|
|
10
|
+
return `${prefix}${normalizedPath}-discover.${format}`
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function getCached(
|
|
14
|
+
bucket: R2Bucket,
|
|
15
|
+
key: string,
|
|
16
|
+
currentTitle?: string,
|
|
17
|
+
): Promise<R2ObjectBody | null> {
|
|
18
|
+
const object = await bucket.get(key)
|
|
19
|
+
if (!object) return null
|
|
20
|
+
|
|
21
|
+
if (currentTitle) {
|
|
22
|
+
const cachedTitle = object.customMetadata?.['x-og-title']
|
|
23
|
+
if (cachedTitle && cachedTitle !== currentTitle) {
|
|
24
|
+
return null
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
return object
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function writeToR2(
|
|
32
|
+
bucket: R2Bucket,
|
|
33
|
+
key: string,
|
|
34
|
+
body: ArrayBuffer,
|
|
35
|
+
metadata: {
|
|
36
|
+
title: string
|
|
37
|
+
generatedAt: string
|
|
38
|
+
contentType: string
|
|
39
|
+
},
|
|
40
|
+
): Promise<R2Object> {
|
|
41
|
+
return bucket.put(key, body, {
|
|
42
|
+
httpMetadata: {
|
|
43
|
+
contentType: metadata.contentType,
|
|
44
|
+
cacheControl: 'public, max-age=31536000, immutable',
|
|
45
|
+
},
|
|
46
|
+
customMetadata: {
|
|
47
|
+
'x-og-title': metadata.title,
|
|
48
|
+
'x-og-generated-at': metadata.generatedAt,
|
|
49
|
+
},
|
|
50
|
+
})
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function invalidateCache(
|
|
54
|
+
bucket: R2Bucket,
|
|
55
|
+
prefix: string,
|
|
56
|
+
pagePath: string,
|
|
57
|
+
format: string,
|
|
58
|
+
): Promise<void> {
|
|
59
|
+
const keys = [ogKey(prefix, pagePath, format), ogDiscoverKey(prefix, pagePath, format)]
|
|
60
|
+
await Promise.all(keys.map((key) => bucket.delete(key)))
|
|
61
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import type { OgTemplateData } from '../types.js'
|
|
2
|
+
|
|
3
|
+
export function defaultTemplate(data: OgTemplateData): string {
|
|
4
|
+
const bg = data.brandColors?.background ?? data.brandColors?.primary ?? '#1a1a2e'
|
|
5
|
+
const textColor = data.brandColors?.text ?? '#ffffff'
|
|
6
|
+
const accent = data.brandColors?.accent ?? '#e2725b'
|
|
7
|
+
const fontFamily = data.fontFamily
|
|
8
|
+
const fontWeight = data.fontWeight
|
|
9
|
+
const subtitle = data.subtitle ?? data.description
|
|
10
|
+
const category = data.category ?? data.pageType
|
|
11
|
+
|
|
12
|
+
const fontUrl = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(fontFamily)}:wght@400;${fontWeight};700&display=swap`
|
|
13
|
+
|
|
14
|
+
return `<!DOCTYPE html>
|
|
15
|
+
<html>
|
|
16
|
+
<head>
|
|
17
|
+
<meta charset="utf-8">
|
|
18
|
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
19
|
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
20
|
+
<link href="${fontUrl}" rel="stylesheet">
|
|
21
|
+
<style>
|
|
22
|
+
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
23
|
+
|
|
24
|
+
body {
|
|
25
|
+
width: 1200px;
|
|
26
|
+
height: 675px;
|
|
27
|
+
background: ${bg};
|
|
28
|
+
color: ${textColor};
|
|
29
|
+
font-family: '${fontFamily}', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
30
|
+
display: flex;
|
|
31
|
+
flex-direction: column;
|
|
32
|
+
padding: 56px 64px 48px;
|
|
33
|
+
overflow: hidden;
|
|
34
|
+
position: relative;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
.top-bar {
|
|
38
|
+
display: flex;
|
|
39
|
+
align-items: center;
|
|
40
|
+
justify-content: space-between;
|
|
41
|
+
margin-bottom: auto;
|
|
42
|
+
flex-shrink: 0;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
.brand {
|
|
46
|
+
display: flex;
|
|
47
|
+
align-items: center;
|
|
48
|
+
gap: 16px;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
.brand img {
|
|
52
|
+
height: 40px;
|
|
53
|
+
width: auto;
|
|
54
|
+
object-fit: contain;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
.brand-name {
|
|
58
|
+
font-size: 20px;
|
|
59
|
+
font-weight: 400;
|
|
60
|
+
letter-spacing: 0.02em;
|
|
61
|
+
opacity: 0.85;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
.category {
|
|
65
|
+
font-size: 16px;
|
|
66
|
+
font-weight: 600;
|
|
67
|
+
text-transform: uppercase;
|
|
68
|
+
letter-spacing: 0.08em;
|
|
69
|
+
color: ${accent};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
.title {
|
|
73
|
+
font-size: 56px;
|
|
74
|
+
font-weight: ${fontWeight};
|
|
75
|
+
line-height: 1.15;
|
|
76
|
+
letter-spacing: -0.02em;
|
|
77
|
+
margin-bottom: 16px;
|
|
78
|
+
display: -webkit-box;
|
|
79
|
+
-webkit-line-clamp: 3;
|
|
80
|
+
-webkit-box-orient: vertical;
|
|
81
|
+
overflow: hidden;
|
|
82
|
+
flex-shrink: 0;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
.subtitle {
|
|
86
|
+
font-size: 24px;
|
|
87
|
+
font-weight: 400;
|
|
88
|
+
line-height: 1.4;
|
|
89
|
+
opacity: 0.75;
|
|
90
|
+
display: -webkit-box;
|
|
91
|
+
-webkit-line-clamp: 2;
|
|
92
|
+
-webkit-box-orient: vertical;
|
|
93
|
+
overflow: hidden;
|
|
94
|
+
flex-shrink: 0;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
.bottom-bar {
|
|
98
|
+
margin-top: auto;
|
|
99
|
+
flex-shrink: 0;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
.accent-line {
|
|
103
|
+
width: 64px;
|
|
104
|
+
height: 4px;
|
|
105
|
+
background: ${accent};
|
|
106
|
+
margin-bottom: 20px;
|
|
107
|
+
border-radius: 2px;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
.author {
|
|
111
|
+
display: flex;
|
|
112
|
+
align-items: center;
|
|
113
|
+
gap: 14px;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
.author img {
|
|
117
|
+
width: 44px;
|
|
118
|
+
height: 44px;
|
|
119
|
+
border-radius: 50%;
|
|
120
|
+
object-fit: cover;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
.author-name {
|
|
124
|
+
font-size: 18px;
|
|
125
|
+
font-weight: 500;
|
|
126
|
+
opacity: 0.85;
|
|
127
|
+
}
|
|
128
|
+
</style>
|
|
129
|
+
</head>
|
|
130
|
+
<body>
|
|
131
|
+
<div class="top-bar">
|
|
132
|
+
<div class="brand">
|
|
133
|
+
${data.logoUrl ? `<img src="${data.logoUrl}" alt="">` : ''}
|
|
134
|
+
${data.brandName ? `<span class="brand-name">${escapeHtml(data.brandName)}</span>` : ''}
|
|
135
|
+
</div>
|
|
136
|
+
${category ? `<span class="category">${escapeHtml(category)}</span>` : ''}
|
|
137
|
+
</div>
|
|
138
|
+
|
|
139
|
+
<div style="flex: 1; display: flex; flex-direction: column; justify-content: center;">
|
|
140
|
+
<h1 class="title">${escapeHtml(data.title)}</h1>
|
|
141
|
+
${subtitle ? `<p class="subtitle">${escapeHtml(subtitle)}</p>` : ''}
|
|
142
|
+
</div>
|
|
143
|
+
|
|
144
|
+
<div class="bottom-bar">
|
|
145
|
+
<div class="accent-line"></div>
|
|
146
|
+
${
|
|
147
|
+
data.authorName
|
|
148
|
+
? `
|
|
149
|
+
<div class="author">
|
|
150
|
+
${data.authorImageUrl ? `<img src="${data.authorImageUrl}" alt="">` : ''}
|
|
151
|
+
<span class="author-name">${escapeHtml(data.authorName)}</span>
|
|
152
|
+
</div>
|
|
153
|
+
`
|
|
154
|
+
: ''
|
|
155
|
+
}
|
|
156
|
+
</div>
|
|
157
|
+
</body>
|
|
158
|
+
</html>`
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function escapeHtml(str: string): string {
|
|
162
|
+
return str
|
|
163
|
+
.replace(/&/g, '&')
|
|
164
|
+
.replace(/</g, '<')
|
|
165
|
+
.replace(/>/g, '>')
|
|
166
|
+
.replace(/"/g, '"')
|
|
167
|
+
.replace(/'/g, ''')
|
|
168
|
+
}
|
package/src/utils/url.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export function getOgImageUrl(
|
|
2
|
+
publicDomain: string,
|
|
3
|
+
pagePath: string,
|
|
4
|
+
options?: { prefix?: string; format?: 'png' | 'jpeg' },
|
|
5
|
+
): string {
|
|
6
|
+
const prefix = options?.prefix ?? 'og/'
|
|
7
|
+
const ext = options?.format ?? 'png'
|
|
8
|
+
const normalizedPath = normalizePagePath(pagePath)
|
|
9
|
+
return `https://${publicDomain}/${prefix}${normalizedPath}.${ext}`
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function getOgDiscoverUrl(
|
|
13
|
+
publicDomain: string,
|
|
14
|
+
pagePath: string,
|
|
15
|
+
options?: { prefix?: string; format?: 'png' | 'jpeg' },
|
|
16
|
+
): string {
|
|
17
|
+
const prefix = options?.prefix ?? 'og/'
|
|
18
|
+
const ext = options?.format ?? 'png'
|
|
19
|
+
const normalizedPath = normalizePagePath(pagePath)
|
|
20
|
+
return `https://${publicDomain}/${prefix}${normalizedPath}-discover.${ext}`
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function getOgUrls(
|
|
24
|
+
publicDomain: string,
|
|
25
|
+
pagePath: string,
|
|
26
|
+
options?: { prefix?: string; format?: 'png' | 'jpeg' },
|
|
27
|
+
): { og: string; discover: string } {
|
|
28
|
+
return {
|
|
29
|
+
og: getOgImageUrl(publicDomain, pagePath, options),
|
|
30
|
+
discover: getOgDiscoverUrl(publicDomain, pagePath, options),
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Exported for use by r2.ts key builders */
|
|
35
|
+
export function normalizePagePath(pagePath: string): string {
|
|
36
|
+
let path = pagePath.replace(/^\/+/, '').replace(/\/+$/, '')
|
|
37
|
+
if (path === '') path = 'index'
|
|
38
|
+
return path
|
|
39
|
+
}
|
package/src/virtual.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
declare module 'virtual:growth-labs/opengraph/config' {
|
|
2
|
+
import type { ResolvedOpengraphOptions } from '@growth-labs/opengraph'
|
|
3
|
+
|
|
4
|
+
export const options: Omit<ResolvedOpengraphOptions, 'contentProvider' | 'template'>
|
|
5
|
+
export function getContentProvider():
|
|
6
|
+
| ((pagePath: string, context: any) => Promise<any>)
|
|
7
|
+
| undefined
|
|
8
|
+
export function getTemplate(): ((data: any) => string) | undefined
|
|
9
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { Plugin } from 'vite'
|
|
2
|
+
import type { ResolvedOpengraphOptions } from './options.js'
|
|
3
|
+
|
|
4
|
+
const VIRTUAL_MODULE_ID = 'virtual:growth-labs/opengraph/config'
|
|
5
|
+
const RESOLVED_VIRTUAL_MODULE_ID = `\0${VIRTUAL_MODULE_ID}`
|
|
6
|
+
|
|
7
|
+
export function growthLabsOpengraphPlugin(config: ResolvedOpengraphOptions): Plugin {
|
|
8
|
+
const { contentProvider: _cp, template: _t, ...staticConfig } = config as Record<string, unknown>
|
|
9
|
+
|
|
10
|
+
return {
|
|
11
|
+
name: 'growth-labs-opengraph-config',
|
|
12
|
+
resolveId(id) {
|
|
13
|
+
if (id === VIRTUAL_MODULE_ID) return RESOLVED_VIRTUAL_MODULE_ID
|
|
14
|
+
},
|
|
15
|
+
load(id) {
|
|
16
|
+
if (id === RESOLVED_VIRTUAL_MODULE_ID) {
|
|
17
|
+
return [
|
|
18
|
+
`export const options = ${JSON.stringify(staticConfig)};`,
|
|
19
|
+
`export { getContentProvider, getTemplate } from '@growth-labs/opengraph/state';`,
|
|
20
|
+
].join('\n')
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
}
|
|
24
|
+
}
|