@ethercorps/sveltekit-og 3.0.0-alpha.1 → 3.0.0-next.10

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/README.md CHANGED
@@ -0,0 +1,171 @@
1
+ # SvelteKit Open Graph Image Generation
2
+
3
+ Dynamically generate Open Graph images from an HTML+CSS template or Svelte component using fast and efficient conversion from HTML > SVG > PNG. Based on [Satori](https://github.com/vercel/satori#documentation). No headless browser required.
4
+
5
+ ## Disclaimer
6
+ This project doesn't support edge services like vercel edge and cloudflare workers.
7
+
8
+ ## Installation
9
+
10
+ ```bash
11
+ pnpm install @ethercorps/sveltekit-og
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ Create a file at `/src/routes/og/+server.ts`. Alternatively, you can use JavaScript by removing the types from this example.
17
+
18
+ ```typescript
19
+ // src/routes/og/+server.ts
20
+ import { ImageResponse } from '@ethercorps/sveltekit-og';
21
+ import { RequestHandler } from './$types';
22
+
23
+ const template = `
24
+ <div tw="bg-gray-50 flex w-full h-full items-center justify-center">
25
+ <div tw="flex flex-col md:flex-row w-full py-12 px-4 md:items-center justify-between p-8">
26
+ <h2 tw="flex flex-col text-3xl sm:text-4xl font-bold tracking-tight text-gray-900 text-left">
27
+ <span>Ready to dive in?</span>
28
+ <span tw="text-indigo-600">Start your free trial today.</span>
29
+ </h2>
30
+ <div tw="mt-8 flex md:mt-0">
31
+ <div tw="flex rounded-md shadow">
32
+ <a href="#" tw="flex items-center justify-center rounded-md border border-transparent bg-indigo-600 px-5 py-3 text-base font-medium text-white">Get started</a>
33
+ </div>
34
+ <div tw="ml-3 flex rounded-md shadow">
35
+ <a href="#" tw="flex items-center justify-center rounded-md border border-transparent bg-white px-5 py-3 text-base font-medium text-indigo-600">Learn more</a>
36
+ </div>
37
+ </div>
38
+ </div>
39
+ </div>
40
+ `;
41
+
42
+ const fontFile = await fetch('https://og-playground.vercel.app/inter-latin-ext-400-normal.woff');
43
+ const fontData: ArrayBuffer = await fontFile.arrayBuffer();
44
+
45
+ export const GET: RequestHandler = async () => {
46
+ return await ImageResponse(template, {
47
+ height: 630,
48
+ width: 1200,
49
+ fonts: [
50
+ {
51
+ name: 'Inter Latin',
52
+ data: fontData,
53
+ weight: 400
54
+ }
55
+ ]
56
+ });
57
+ };
58
+ ```
59
+
60
+ Then run `npm dev` and visit `localhost:5173/og` to view your generated PNG. Remember that hot module reloading does not work with server routes, so if you change your HTML or CSS, hard refresh the route to see changes.
61
+
62
+ ## Example Output
63
+
64
+ ![Rendered OG image](static/demo.png)
65
+
66
+ ## Headers
67
+
68
+ When run in development, image headers contain `cache-control: no-cache, no-store`. In production, image headers contain `'cache-control': 'public, immutable, no-transform, max-age=31536000'`, which caches the image for 1 year. In both cases, the `'content-type': 'image/png'` is used.
69
+
70
+ ## Styling
71
+
72
+ Notice that our example uses TailwindCSS classes (e.g. `tw="bg-gray-50"`). Alternatively, your HTML can contain style attributes using any of [the subset of CSS supported by Satori](https://github.com/vercel/satori#css).
73
+
74
+ Satori supports only a subset of HTML and CSS. For full details, see [Satori’s documentation](https://github.com/vercel/satori#documentation). Notably, Satori only supports flex-based layouts.
75
+
76
+ ## Fonts
77
+
78
+ Satori supports `ttf`, `otf`, and `woff` font formats; `woff2` is not supported. To maximize the font parsing speed, `ttf` or `otf` are recommended over `woff`.
79
+
80
+ By default, `@ethercorps/sveltekit-og` includes only 'Noto Sans' font. If you need to use other fonts, you can specify them as shown in the example. Notably, you can also import a font file that is stored locally within your project and are not required to use fetch.
81
+
82
+ ## Examples
83
+
84
+ - `ImageResponse` · [_source_](/src/routes/+server.ts) · [_demo_](https://sveltekit-og-five.vercel.app)
85
+ - `Component Rendering` · [_source_](/src/routes/sc/+server.ts) · [_demo_](https://sveltekit-og-five.vercel.app/sc)
86
+
87
+ ## API Reference
88
+
89
+ The package exposes an `ImageResponse` constructors, with the following options available:
90
+
91
+ ```typescript
92
+ import {ImageResponse} from '@ethercorps/sveltekit-og'
93
+ import {SvelteComponent} from "svelte";
94
+
95
+ // ...
96
+ ImageResponse(
97
+ element : string,
98
+ options : {
99
+ width ? : number = 1200
100
+ height ? : number = 630,
101
+ backgroundColor ? : string = "#fff"
102
+ fonts ? : {
103
+ name: string,
104
+ data: ArrayBuffer,
105
+ weight: number,
106
+ style: 'normal' | 'italic'
107
+ }[]
108
+ debug ? : boolean = false
109
+ graphemeImages ? : Record<string, string>;
110
+ loadAdditionalAsset ? : (languageCode: string, segment: string) => Promise<SatoriOptions["fonts"] | string | undefined>;
111
+ // Options that will be passed to the HTTP response
112
+ status ? : number = 200
113
+ statusText ? : string
114
+ headers ? : Record<string, string>
115
+ } {props})
116
+ ```
117
+
118
+ ## Changelog
119
+
120
+ ### v3.0.0 (Breaking Changes)
121
+
122
+ > Just install @ethercorps/sveltekit-og
123
+ > No wasm as of now, only support for nodejs based runtime.
124
+
125
+ ### v1.2.3 Update (Breaking Changes)
126
+
127
+ > Now you have to install dependency by yourself which will make it easier to build for all plateforms.
128
+
129
+ ```
130
+ npm i @resvg/resvg-js
131
+ ```
132
+
133
+ ```
134
+ npm i satori
135
+ ```
136
+
137
+ > From now on their will be no issues related to build, and soon this library going to have its own documentation.
138
+
139
+ ### v1.2.2 Update (Breaking Change)
140
+
141
+ - We don't provide access to satori from `@ethercorps/sveltekit-og`.
142
+
143
+ ### v1.0.0 Update (Breaking Changes)
144
+
145
+ Finally, We have added html to react like element like object converter out of the box and with svelte compiler.
146
+ Now you can use `{ toReactElement }` with `"@ethercorps/sveltekit-og"` like:
147
+
148
+ - We have changed to function based instead of class based ImageResponse and componentToImageResponse.
149
+ - Removed `@resvg/resvg-wasm` with `@resvg/resvg-js` because of internal errors.
150
+ - Removed `satori-html` because now we have `toReactElement` out of the box with svelte compiler.
151
+ > If you find a problem related to undefined a please check [_vite.config.js_](/vite.config.ts) and add ` define: { _a: 'undefined' } in config.`
152
+
153
+ > If you find any issue and have suggestion for this project please open a ticket and if you want to contribute please create a new discussion.
154
+
155
+ ## Acknowledgements
156
+
157
+ This project will not be possible without the following projects:
158
+
159
+ - [Satori & @vercel/og](https://github.com/vercel/satori)
160
+ - [Noto by Google Fonts](https://fonts.google.com/noto)
161
+
162
+ [//]: # (- [svg2png-wasm]&#40;https://github.com/ssssota/svg2png-wasm&#41;)
163
+
164
+ ## Authors
165
+
166
+ - [@theetherGit](https://www.github.com/theetherGit)
167
+ - [@etherCorps](https://www.github.com/etherCorps)
168
+
169
+ ## Contributors
170
+
171
+ - [@jasongitmail](https://github.com/jasongitmail)
@@ -0,0 +1,5 @@
1
+ import type { SvelteComponent } from "svelte";
2
+ import type { ComponentOptions, ImageOptions, VNode } from '../types.js';
3
+ export declare function createVNode(element: string | SvelteComponent, componentOptions?: ComponentOptions): VNode;
4
+ export declare function createSvg(element: string | SvelteComponent, imageOptions: ImageOptions, componentOptions?: ComponentOptions): Promise<string>;
5
+ export declare function createPng(element: string | SvelteComponent, imageOptions: ImageOptions, componentOptions?: ComponentOptions): Promise<Uint8Array>;
@@ -0,0 +1,45 @@
1
+ import { svelteComponentToJsx, toReactElement } from '@ethercorps/svelte-h2j';
2
+ import { loadDynamicAsset } from './emoji.js';
3
+ import { default_fonts } from '../helpers/defaults.js';
4
+ import { useResvg, useSatori } from '../providers/instances.js';
5
+ // TODO: Export VNode Type from svelte-h2j
6
+ // TODO: Make svelte-h2j functions async in new v5 support
7
+ export async function createVNode(element, componentOptions) {
8
+ return typeof element === 'string' ? toReactElement(element) : svelteComponentToJsx(element, componentOptions?.props);
9
+ }
10
+ export async function createSvg(element, imageOptions, componentOptions) {
11
+ const [satori, vnodes] = await Promise.all([useSatori(), createVNode(element, componentOptions)]);
12
+ if (!Object.hasOwn(imageOptions, 'fonts')) {
13
+ imageOptions['fonts'] = await default_fonts();
14
+ }
15
+ // Add dynamic emoji loading handler
16
+ imageOptions['loadAdditionalAsset'] = loadDynamicAsset({
17
+ emoji: imageOptions.emoji
18
+ });
19
+ if (imageOptions.debug) {
20
+ console.info('VNode proivided to satori:', vnodes, '\n');
21
+ console.info('Options proivided to satori:', imageOptions, '\n');
22
+ }
23
+ return satori(vnodes, imageOptions);
24
+ }
25
+ export async function createPng(element, imageOptions, componentOptions) {
26
+ const svg = await createSvg(element, imageOptions, componentOptions);
27
+ if (imageOptions.debug) {
28
+ console.info('SVG generated by satori:', svg, '\n');
29
+ }
30
+ const resvg_instance = await useResvg();
31
+ console.log(resvg_instance, 'f');
32
+ const resvg_options = {
33
+ fitTo: {
34
+ mode: 'width',
35
+ value: imageOptions.width
36
+ },
37
+ logLevel: imageOptions.debug ? 'info' : 'error'
38
+ };
39
+ if (imageOptions.debug) {
40
+ console.info('Options provided to ReSVG:', resvg_options, '\n');
41
+ }
42
+ const resvg = new resvg_instance(svg, resvg_options);
43
+ const png_data = resvg.render();
44
+ return png_data.asPng();
45
+ }
@@ -0,0 +1,10 @@
1
+ import type { SatoriOptions } from 'satori';
2
+ import type { ImageOptions } from '../types.js';
3
+ export declare function default_fonts(): SatoriOptions['fonts'];
4
+ export declare const DEFAULT_FORMAT = "png";
5
+ export declare const DEFAULT_WIDTH = 1200;
6
+ export declare const DEFAULT_HEIGHT = 630;
7
+ export declare const DEFAULT_EMOJI_PROVIDER = "twemoji";
8
+ export declare const DEFAULT_STATUS_CODE = 200;
9
+ export declare const DEFAULT_STATUS_TEXT = "Success";
10
+ export declare const DEFAULT_OPTIONS: ImageOptions;
@@ -0,0 +1,37 @@
1
+ export async function default_fonts() {
2
+ const [noto_sans_regular_font_resp, noto_sans_bold_font_reps] = await Promise.all([
3
+ fetch('https://cdn-sveltekit-og.ethercorps.io/NotoSans-Regular.ttf'), fetch('https://cdn-sveltekit-og.ethercorps.io/NotoSans-Bold.ttf')
4
+ ]);
5
+ if (!(noto_sans_bold_font_reps.ok || noto_sans_bold_font_reps.ok)) {
6
+ console.error('Not able to load default fonts');
7
+ throw new Error('Not able to load default fonts');
8
+ }
9
+ const [noto_sans_regular_font, noto_sans_bold_font] = await Promise.all([noto_sans_regular_font_resp.arrayBuffer(), noto_sans_bold_font_reps.arrayBuffer()]);
10
+ return [
11
+ {
12
+ data: noto_sans_regular_font,
13
+ name: 'Inter',
14
+ weight: 400,
15
+ style: 'normal'
16
+ },
17
+ {
18
+ data: noto_sans_bold_font,
19
+ name: 'Inter',
20
+ weight: 700,
21
+ style: 'normal'
22
+ }
23
+ ];
24
+ }
25
+ export const DEFAULT_FORMAT = 'png';
26
+ export const DEFAULT_WIDTH = 1200;
27
+ export const DEFAULT_HEIGHT = 630;
28
+ export const DEFAULT_EMOJI_PROVIDER = 'twemoji';
29
+ export const DEFAULT_STATUS_CODE = 200;
30
+ export const DEFAULT_STATUS_TEXT = 'Success';
31
+ export const DEFAULT_OPTIONS = {
32
+ height: DEFAULT_HEIGHT,
33
+ width: DEFAULT_WIDTH,
34
+ debug: false,
35
+ format: 'png',
36
+ emoji: 'twemoji'
37
+ };
@@ -0,0 +1,3 @@
1
+ export declare const loadDynamicAsset: ({ emoji }: {
2
+ emoji: any;
3
+ }) => (...args: any[]) => Promise<string | undefined>;
@@ -0,0 +1,53 @@
1
+ import { DEFAULT_EMOJI_PROVIDER } from '../helpers/defaults.js';
2
+ // Code stolen from @vercel/og
3
+ const U200D = String.fromCharCode(8205);
4
+ const UFE0Fg = /\uFE0F/g;
5
+ function getIconCode(char) {
6
+ return toCodePoint(char.indexOf(U200D) < 0 ? char.replace(UFE0Fg, "") : char);
7
+ }
8
+ function toCodePoint(unicodeSurrogates) {
9
+ const r = [];
10
+ let c = 0, p = 0, i = 0;
11
+ while (i < unicodeSurrogates.length) {
12
+ c = unicodeSurrogates.charCodeAt(i++);
13
+ if (p) {
14
+ r.push((65536 + (p - 55296 << 10) + (c - 56320)).toString(16));
15
+ p = 0;
16
+ }
17
+ else if (55296 <= c && c <= 56319) {
18
+ p = c;
19
+ }
20
+ else {
21
+ r.push(c.toString(16));
22
+ }
23
+ }
24
+ return r.join("-");
25
+ }
26
+ const emoji_apis = {
27
+ twemoji: (code) => "https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/svg/" + code.toLowerCase() + ".svg",
28
+ openmoji: "https://cdn.jsdelivr.net/npm/@svgmoji/openmoji@2.0.0/svg/",
29
+ blobmoji: "https://cdn.jsdelivr.net/npm/@svgmoji/blob@2.0.0/svg/",
30
+ noto: "https://cdn.jsdelivr.net/gh/svgmoji/svgmoji/packages/svgmoji__noto/svg/",
31
+ fluent: (code) => "https://cdn.jsdelivr.net/gh/shuding/fluentui-emoji-unicode/assets/" + code.toLowerCase() + "_color.svg",
32
+ fluentFlat: (code) => "https://cdn.jsdelivr.net/gh/shuding/fluentui-emoji-unicode/assets/" + code.toLowerCase() + "_flat.svg"
33
+ };
34
+ function loadEmoji(code, type) {
35
+ if (!type || !apis[type]) {
36
+ type = DEFAULT_EMOJI_PROVIDER;
37
+ }
38
+ const api = apis[type];
39
+ if (typeof api === "function") {
40
+ return fetch(api(code));
41
+ }
42
+ return fetch(`${api}${code.toUpperCase()}.svg`);
43
+ }
44
+ export const loadDynamicAsset = ({ emoji }) => {
45
+ const fn = async (code, text) => {
46
+ if (code === "emoji") {
47
+ return `data:image/svg+xml;base64,` + btoa(await (await loadEmoji(getIconCode(text), emoji)).text());
48
+ }
49
+ };
50
+ return async (...args) => {
51
+ return await fn(...args);
52
+ };
53
+ };
@@ -0,0 +1,5 @@
1
+ import type { SvelteComponent } from 'svelte';
2
+ import type { ImageResponseOptions } from './types.js';
3
+ export declare class ImageResponse extends Response {
4
+ constructor(element: string | SvelteComponent, options?: ImageResponseOptions, props?: Record<string, any>);
5
+ }
@@ -0,0 +1,27 @@
1
+ import { DEFAULT_OPTIONS, DEFAULT_STATUS_CODE, DEFAULT_STATUS_TEXT } from './helpers/defaults.js';
2
+ import { createPng, createSvg } from './helpers/create.js';
3
+ import { isDevelopment } from 'std-env';
4
+ export class ImageResponse extends Response {
5
+ constructor(element, options, props) {
6
+ const extended_options = Object.assign({ ...DEFAULT_OPTIONS }, options);
7
+ const create_image_funtion = extended_options.format === 'png' ? createPng : createSvg;
8
+ const body = new ReadableStream({
9
+ async start(controller) {
10
+ const buffer = await create_image_funtion(element, extended_options, { props });
11
+ controller.enqueue(buffer);
12
+ controller.close();
13
+ }
14
+ });
15
+ super(body, {
16
+ headers: {
17
+ 'Content-Type': `image/${extended_options.format}`,
18
+ 'Cache-Control': (extended_options.debug || isDevelopment)
19
+ ? 'no-cache, no-store'
20
+ : 'public, immutable, no-transform, max-age=31536000',
21
+ ...extended_options.headers
22
+ },
23
+ status: extended_options.status || DEFAULT_STATUS_CODE,
24
+ statusText: extended_options.statusText || DEFAULT_STATUS_TEXT
25
+ });
26
+ }
27
+ }
package/dist/index.d.ts CHANGED
@@ -1 +1,2 @@
1
- export { ImageResponse } from "./api.js";
1
+ export { ImageResponse } from "./image-response.js";
2
+ export type { ImageResponseOptions, VNode } from "./types.js";