-
Notifications
You must be signed in to change notification settings - Fork 7
/
mod.ts
245 lines (216 loc) · 6.44 KB
/
mod.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import type { ReactElement } from "https://esm.sh/[email protected]";
import type { SatoriOptions } from "https://esm.sh/[email protected]";
import satori, { init as initSatori } from "https://esm.sh/[email protected]/wasm";
import { initStreaming } from "https://esm.sh/[email protected]";
import {
initWasm,
Resvg,
} from "https://esm.sh/@resvg/[email protected]";
import { EmojiType, getIconCode, loadEmoji } from "./emoji.ts";
declare module "https://esm.sh/[email protected]" {
interface HTMLAttributes<T> {
/**
* Specify styles using Tailwind CSS classes. This feature is currently experimental.
* If `style` prop is also specified, styles generated with `tw` prop will be overridden.
*
* Example:
* - `tw='w-full h-full bg-blue-200'`
* - `tw='text-9xl'`
* - `tw='text-[80px]'`
*
* @type {string}
*/
tw?: string;
}
}
const resvg_wasm = fetch(
"https://cdn.jsdelivr.net/npm/@vercel/[email protected]/vendor/resvg.simd.wasm",
).then((res) => res.arrayBuffer());
const yoga_wasm = fetch(
"https://cdn.jsdelivr.net/npm/@vercel/[email protected]/vendor/yoga.wasm",
);
const fallbackFont = fetch(
"https://cdn.jsdelivr.net/npm/@vercel/[email protected]/vendor/noto-sans-v27-latin-regular.ttf",
).then((a) => a.arrayBuffer());
const initializedResvg = initWasm(resvg_wasm);
const initializedYoga = initStreaming(yoga_wasm).then((yoga: unknown) =>
initSatori(yoga)
);
const isDev = Boolean(Deno.env.get("NETLIFY_LOCAL"));
type ImageResponseOptions = ConstructorParameters<typeof Response>[1] & {
/**
* The width of the image.
*
* @type {number}
* @default 1200
*/
width?: number;
/**
* The height of the image.
*
* @type {number}
* @default 630
*/
height?: number;
/**
* Display debug information on the image.
*
* @type {boolean}
* @default false
*/
debug?: boolean;
/**
* A list of fonts to use.
*
* @type {{ data: ArrayBuffer; name: string; weight?: 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900; style?: 'normal' | 'italic' }[]}
* @default Noto Sans Latin Regular.
*/
fonts?: SatoriOptions["fonts"];
/**
* Using a specific Emoji style. Defaults to `twemoji`.
*
* @link https://github.com/vercel/og#emoji
* @type {EmojiType}
* @default 'twemoji'
*/
emoji?: EmojiType;
};
// @TODO: Support font style and weights, and make this option extensible rather
// than built-in.
// @TODO: Cover most languages with Noto Sans.
const languageFontMap = {
"ja-JP": "Noto+Sans+JP",
"ko-KR": "Noto+Sans+KR",
"zh-CN": "Noto+Sans+SC",
"zh-TW": "Noto+Sans+TC",
"zh-HK": "Noto+Sans+HK",
"th-TH": "Noto+Sans+Thai",
"bn-IN": "Noto+Sans+Bengali",
"ar-AR": "Noto+Sans+Arabic",
"ta-IN": "Noto+Sans+Tamil",
"ml-IN": "Noto+Sans+Malayalam",
"he-IL": "Noto+Sans+Hebrew",
"te-IN": "Noto+Sans+Telugu",
devanagari: "Noto+Sans+Devanagari",
kannada: "Noto+Sans+Kannada",
symbol: ["Noto+Sans+Symbols", "Noto+Sans+Symbols+2"],
math: "Noto+Sans+Math",
unknown: "Noto+Sans",
};
async function loadGoogleFont(fonts: string | string[], text: string) {
// @TODO: Support multiple fonts.
const font = Array.isArray(fonts) ? fonts.at(-1) : fonts;
if (!font || !text) return;
const API = `https://fonts.googleapis.com/css2?family=${font}&text=${
encodeURIComponent(
text,
)
}`;
const css = await (
await fetch(API, {
headers: {
// Make sure it returns TTF.
"User-Agent":
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; de-at) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1",
},
})
).text();
const resource = css.match(
/src: url\((.+)\) format\('(opentype|truetype)'\)/,
);
if (!resource) throw new Error("Failed to load font");
return fetch(resource[1]).then((res) => res.arrayBuffer());
}
type Asset = SatoriOptions["fonts"][0] | string;
const assetCache = new Map<string, Asset | undefined>();
const loadDynamicAsset = ({ emoji }: { emoji?: EmojiType }) => {
const fn = async (
code: keyof typeof languageFontMap | "emoji",
text: string,
): Promise<Asset | undefined> => {
if (code === "emoji") {
// It's an emoji, load the image.
return (
`data:image/svg+xml;base64,` +
btoa(await (await loadEmoji(getIconCode(text), emoji)).text())
);
}
// Try to load from Google Fonts.
if (!languageFontMap[code]) code = "unknown";
try {
const data = await loadGoogleFont(languageFontMap[code], text);
if (data) {
return {
name: `satori_${code}_fallback_${text}`,
data,
weight: 400,
style: "normal",
};
}
} catch (e) {
console.error("Failed to load dynamic font for", text, ". Error:", e);
}
};
return async (...args: Parameters<typeof fn>) => {
const key = JSON.stringify(args);
const cache = assetCache.get(key);
if (cache) return cache;
const asset = await fn(...args);
assetCache.set(key, asset);
return asset;
};
};
export class ImageResponse extends Response {
constructor(element: ReactElement, options: ImageResponseOptions = {}) {
const extendedOptions = Object.assign(
{
width: 1200,
height: 630,
debug: false,
},
options,
);
const result = new ReadableStream({
async start(controller) {
await initializedYoga;
await initializedResvg;
const fontData = await fallbackFont;
const svg = await satori(element, {
width: extendedOptions.width,
height: extendedOptions.height,
debug: extendedOptions.debug,
fonts: extendedOptions.fonts || [
{
name: "sans serif",
data: fontData,
weight: 700,
style: "normal",
},
],
loadAdditionalAsset: loadDynamicAsset({
emoji: extendedOptions.emoji,
}),
});
const resvgJS = new Resvg(svg, {
fitTo: {
mode: "width",
value: extendedOptions.width,
},
});
controller.enqueue(resvgJS.render());
controller.close();
},
});
super(result, {
headers: {
"content-type": "image/png",
"cache-control": isDev
? "no-cache, no-store"
: "public, max-age=31536000, no-transform, immutable",
...extendedOptions.headers,
},
status: extendedOptions.status,
statusText: extendedOptions.statusText,
});
}
}