@ethercorps/sveltekit-og 1.2.3 → 2.0.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.
Files changed (4) hide show
  1. package/README.md +104 -132
  2. package/index.d.ts +3 -2
  3. package/index.js +20 -9
  4. package/package.json +2 -3
package/README.md CHANGED
@@ -1,91 +1,24 @@
1
- # Open Graph Image Generation
1
+ # SvelteKit Open Graph Image Generation
2
2
 
3
- About
4
- Generate Open Graph Images dynamically from HTML/CSS without a browser in SvelteKit.
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.
5
4
 
6
- ## v1.2.3 Update (Breaking Changes)
7
- > Now you have to install dependency by yourself which will make it easier to build for all plateforms.
8
-
9
- ```
10
- pnpm i @resvg/resvg-js
11
- ```
5
+ ## Installation
12
6
 
7
+ ```bash
8
+ pnpm install -D @ethercorps/sveltekit-og
13
9
  ```
14
- pnpm i satori
15
- ```
16
-
17
- > From now on their will be no issues related to build, and soon this library going to have its own documentation.
18
-
19
- ## v1.2.2 Update (Breaking Change)
20
-
21
- - We don't provide access to satori from `@ethercorps/sveltekit-og`.
22
-
23
- ## v1.0.0 Update (Breaking Changes)
24
-
25
- Finally, We have added html to react like element like object converter out of the box and with svelte compiler.
26
- Now you can use `{ toReactElement }` with `"@ethercorps/sveltekit-og"` like:
27
-
28
- ```typescript
29
- // +page.server.js
30
-
31
- import { toReactElement, satori } from '@ethercorps/sveltekit-og';
32
-
33
- const htmlString = `
34
- <div tw="bg-gray-50 flex w-full">
35
- <div tw="flex flex-col md:flex-row w-full py-12 px-4 md:items-center justify-between p-8">
36
- <h2 tw="flex flex-col text-3xl sm:text-4xl font-bold tracking-tight text-gray-900 text-left">
37
- <span>Ready to dive in?</span>
38
- <span tw="text-indigo-600">Start your free trial today.</span>
39
- </h2>
40
- <div tw="mt-8 flex md:mt-0">
41
- <div tw="flex rounded-md shadow">
42
- <a 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>
43
- </div>
44
- <div tw="ml-3 flex rounded-md shadow">
45
- <a 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>
46
- </div>
47
- </div>
48
- </div>
49
- </div>
50
- `;
51
- const newNode = toReactElement(htmlString);
52
-
53
- /** @type {import('./$types').PageServerLoad} */
54
- export async function load() {
55
- const fontFile400 = await fetch(
56
- 'https://og-playground.vercel.app/inter-latin-ext-400-normal.woff'
57
- );
58
- const fontData400 = await fontFile400.arrayBuffer();
59
- const svg = await satori(newNode, {
60
- height: 350,
61
- width: 500,
62
- fonts: [
63
- {
64
- name: 'sans serif',
65
- data: fontData400,
66
- style: 'normal',
67
- weight: 700
68
- }
69
- ]
70
- });
71
-
72
- return { svg };
73
- }
10
+ > Using with Cloudflare Pages or Workers then you have to provide `url` polyfill by just installing it as `devDependency`.
11
+ >
12
+ ```bash
13
+ pnpm i -D url
74
14
  ```
75
15
 
76
- - We have changed to function based instead of class based ImageResponse and componentToImageResponse.
77
- - Removed `@resvg/resvg-wasm` with `@resvg/resvg-js` because of internal errors.
78
- - Removed `satori-html` because now we have `toReactElement` out of the box with svelte compiler.
79
- > If you find a problem related to undefined a please check [_vite.config.js_](/vite.config.ts) and add ` define: { _a: 'undefined' } in config.`
80
-
81
- > 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.
82
-
83
- ## Quick Start
16
+ ## Usage
84
17
 
85
- Install `@ethercorps/sveltekit-og`, then use it inside a server endpoint route (+server.ts or +server.js):
18
+ Create a file at `/src/routes/og/+server.ts`. Alternatively, you can use JavaScript by removing the types from this example.
86
19
 
87
20
  ```typescript
88
- // /routes/og/+server.ts
21
+ // src/routes/og/+server.ts
89
22
  import { ImageResponse } from '@ethercorps/sveltekit-og';
90
23
  import { RequestHandler } from './$types';
91
24
 
@@ -107,31 +40,49 @@ const template = `
107
40
  </div>
108
41
  </div>
109
42
  `;
43
+
110
44
  const fontFile = await fetch('https://og-playground.vercel.app/inter-latin-ext-400-normal.woff');
111
45
  const fontData: ArrayBuffer = await fontFile.arrayBuffer();
112
46
 
113
47
  export const GET: RequestHandler = async () => {
114
- return await ImageResponse(template, {
115
- height: 250,
116
- width: 500,
117
- fonts: [
118
- {
119
- name: 'Inter Latin',
120
- data: fontData,
121
- weight: 400
122
- }
123
- ]
124
- });
48
+ return await ImageResponse(template, {
49
+ height: 630,
50
+ width: 1200,
51
+ fonts: [
52
+ {
53
+ name: 'Inter Latin',
54
+ data: fontData,
55
+ weight: 400
56
+ }
57
+ ]
58
+ });
125
59
  };
126
60
  ```
127
61
 
128
- Then run `pnpm dev` and access localhost:5173/og, the api/route endpoint be rendered and responded as a PNG from that api/endpoint:
62
+ 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.
63
+
64
+ ## Example Output
129
65
 
130
66
  ![Rendered OG image](static/demo.png)
131
67
 
132
- Read more about the API, supported features and check out the examples on Satori Playground.
68
+ ## Headers
69
+
70
+ 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.
133
71
 
134
- ## Examples:
72
+
73
+ ## Styling
74
+
75
+ 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).
76
+
77
+ 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.
78
+
79
+ ## Fonts
80
+
81
+ Satori supports `ttf`, `otf`, and `woff` font formats. To maximize the font parsing speed, `ttf` or `otf` are recommended over `woff`.
82
+
83
+ 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.
84
+
85
+ ## Examples
135
86
 
136
87
  - `ImageResponse` · [_source_](/src/routes/new/+server.ts) · [_demo_](https://sveltekit-og-five.vercel.app/new)
137
88
  - `componentToImageResponse` · [_source_](/src/routes/component-og/) · [_demo_](https://sveltekit-og-five.vercel.app/component-og)
@@ -148,59 +99,76 @@ import {SvelteComponent} from "svelte";
148
99
  ImageResponse(
149
100
  element : string,
150
101
  options : {
151
- width ? : number = 1200
152
- height ? : number = 630
153
- fonts ? : {
154
- name: string,
155
- data: ArrayBuffer,
156
- weight: number,
157
- style: 'normal' | 'italic'
158
- }[]
159
- debug ? : boolean = false
160
- graphemeImages ? : Record<string, string>;
161
- loadAdditionalAsset ? : (languageCode: string, segment: string) => Promise<SatoriOptions["fonts"] | string | undefined>;
162
- // Options that will be passed to the HTTP response
163
- status ? : number = 200
164
- statusText ? : string
165
- headers ? : Record<string, string>
102
+ width ? : number = 1200
103
+ height ? : number = 630,
104
+ backgroundColor ? : string = "#fff"
105
+ fonts ? : {
106
+ name: string,
107
+ data: ArrayBuffer,
108
+ weight: number,
109
+ style: 'normal' | 'italic'
110
+ }[]
111
+ debug ? : boolean = false
112
+ graphemeImages ? : Record<string, string>;
113
+ loadAdditionalAsset ? : (languageCode: string, segment: string) => Promise<SatoriOptions["fonts"] | string | undefined>;
114
+ // Options that will be passed to the HTTP response
115
+ status ? : number = 200
116
+ statusText ? : string
117
+ headers ? : Record<string, string>
166
118
  })
167
119
 
168
120
  componentToImageResponse(
169
121
  component : typeof SvelteComponent,
170
122
  props : {}, // All export let example inside prop dictionary
171
123
  options : {
172
- width ? : number = 1200
173
- height ? : number = 630
174
- fonts ? : {
175
- name: string,
176
- data: ArrayBuffer,
177
- weight: number,
178
- style: 'normal' | 'italic'
179
- }[]
180
- debug ? : boolean = false
181
- graphemeImages ? : Record<string, string>;
182
- loadAdditionalAsset ? : (languageCode: string, segment: string) => Promise<SatoriOptions["fonts"] | string | undefined>;
183
- // Options that will be passed to the HTTP response
184
- status ? : number = 200
185
- statusText ? : string
186
- headers ? : Record<string, string>
124
+ width ? : number = 1200
125
+ height ? : number = 630
126
+ fonts ? : {
127
+ name: string,
128
+ data: ArrayBuffer,
129
+ weight: number,
130
+ style: 'normal' | 'italic'
131
+ }[]
132
+ debug ? : boolean = false
133
+ graphemeImages ? : Record<string, string>;
134
+ loadAdditionalAsset ? : (languageCode: string, segment: string) => Promise<SatoriOptions["fonts"] | string | undefined>;
135
+ // Options that will be passed to the HTTP response
136
+ status ? : number = 200
137
+ statusText ? : string
138
+ headers ? : Record<string, string>
187
139
  })
188
140
  ```
189
141
 
190
- When running in production, these headers will be included by `@ethercorps/sveltekit-og`:
142
+ ## Changelog
191
143
 
192
- ```typescript
193
- 'content-type': 'image/png',
194
- 'cache-control': 'public, immutable, no-transform, max-age=31536000',
144
+ ### v1.2.3 Update (Breaking Changes)
145
+ > Now you have to install dependency by yourself which will make it easier to build for all plateforms.
146
+
147
+ ```
148
+ npm i @resvg/resvg-js
149
+ ```
150
+
151
+ ```
152
+ npm i satori
195
153
  ```
196
154
 
197
- During development, the `cache-control: no-cache, no-store` header is used instead.
155
+ > From now on their will be no issues related to build, and soon this library going to have its own documentation.
156
+
157
+ ### v1.2.2 Update (Breaking Change)
158
+
159
+ - We don't provide access to satori from `@ethercorps/sveltekit-og`.
198
160
 
199
- ### Supported HTML and CSS Features
161
+ ### v1.0.0 Update (Breaking Changes)
162
+
163
+ Finally, We have added html to react like element like object converter out of the box and with svelte compiler.
164
+ Now you can use `{ toReactElement }` with `"@ethercorps/sveltekit-og"` like:
200
165
 
201
- Please refer to [Satori’s documentation](https://github.com/vercel/satori#documentation) for a list of supported HTML and CSS features.
166
+ - We have changed to function based instead of class based ImageResponse and componentToImageResponse.
167
+ - Removed `@resvg/resvg-wasm` with `@resvg/resvg-js` because of internal errors.
168
+ - Removed `satori-html` because now we have `toReactElement` out of the box with svelte compiler.
169
+ > If you find a problem related to undefined a please check [_vite.config.js_](/vite.config.ts) and add ` define: { _a: 'undefined' } in config.`
202
170
 
203
- By default, `@ethercorps/sveltekit-og` only has the 'Noto Sans' font included. If you need to use other fonts, you can pass them in the `fonts` option.
171
+ > 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.
204
172
 
205
173
  ## Acknowledgements
206
174
 
@@ -208,9 +176,13 @@ This project will not be possible without the following projects:
208
176
 
209
177
  - [Satori & @vercel/og](https://github.com/vercel/satori)
210
178
  - [Noto by Google Fonts](https://fonts.google.com/noto)
211
- - [Resvg.js](https://github.com/yisibl/resvg-js)
179
+ - [svg2png-wasm](https://github.com/ssssota/svg2png-wasm)
212
180
 
213
181
  ## Authors
214
182
 
215
183
  - [@theetherGit](https://www.github.com/theetherGit)
216
184
  - [@etherCorps](https://www.github.com/etherCorps)
185
+
186
+ ## Contributors
187
+
188
+ - [@jasongitmail](https://github.com/jasongitmail)
package/index.d.ts CHANGED
@@ -9,8 +9,9 @@ type ImageOptions = {
9
9
  height?: number;
10
10
  debug?: boolean;
11
11
  fonts?: SatoriOptions['fonts'];
12
+ backgroundColor?: string;
12
13
  graphemeImages?: Record<string, string>;
13
14
  loadAdditionalAsset?: (languageCode: string, segment: string) => Promise<SatoriOptions['fonts'] | string | undefined>;
14
15
  };
15
- type ImageResponseType = typeof ImageResponse;
16
- export { componentToImageResponse, ImageResponse, toReactElement, type ImageResponseType };
16
+ export type ImageResponseType = typeof ImageResponse;
17
+ export { componentToImageResponse, ImageResponse, toReactElement };
package/index.js CHANGED
@@ -1,8 +1,15 @@
1
1
  import satori, {} from 'satori';
2
- import { Resvg } from '@resvg/resvg-js';
3
2
  import toReactElement from './toReactElement';
3
+ import { svg2png, initialize } from 'svg2png-wasm';
4
+ let initialized = false;
4
5
  const fontFile = await fetch('https://sveltekit-og.ethercorps.io/noto-sans.ttf');
5
6
  const fontData = await fontFile.arrayBuffer();
7
+ const indexWasmRes = await fetch('https://unpkg.com/svg2png-wasm/svg2png_wasm_bg.wasm');
8
+ const svg2PngWasmBuffer = await indexWasmRes.arrayBuffer();
9
+ const initSvgToPng = async () => {
10
+ await initialize(svg2PngWasmBuffer).catch((e) => console.log(e));
11
+ initialized = true;
12
+ };
6
13
  const ImageResponse = async (htmlTemplate, optionsByUser) => {
7
14
  const options = Object.assign({ width: 1200, height: 630, debug: !1 }, optionsByUser);
8
15
  const svg = await satori(toReactElement(htmlTemplate), {
@@ -18,15 +25,19 @@ const ImageResponse = async (htmlTemplate, optionsByUser) => {
18
25
  }
19
26
  ]
20
27
  });
21
- const reSvgOptions = {
22
- fitTo: {
23
- mode: 'width',
24
- value: options.width
25
- }
28
+ if (!initialized) {
29
+ await initSvgToPng();
30
+ initialized = true;
31
+ }
32
+ const defaultConfig = {
33
+ width: options.width,
34
+ height: options.height, // optional
26
35
  };
27
- const reSvgObject = new Resvg(svg, reSvgOptions);
28
- const pngData = await reSvgObject.render().asPng();
29
- return new Response(pngData, {
36
+ if (Object.hasOwn(options, 'backgroundColor')) {
37
+ defaultConfig.backgroundColor = options.backgroundColor;
38
+ }
39
+ const png = await svg2png(svg, defaultConfig);
40
+ return new Response(png, {
30
41
  headers: {
31
42
  'Content-Type': 'image/png',
32
43
  'cache-control': 'public, immutable, no-transform, max-age=31536000',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ethercorps/sveltekit-og",
3
- "version": "1.2.3",
3
+ "version": "2.0.0",
4
4
  "private": false,
5
5
  "devDependencies": {
6
6
  "@playwright/test": "^1.34.3",
@@ -29,9 +29,8 @@
29
29
  },
30
30
  "type": "module",
31
31
  "dependencies": {
32
- "@resvg/resvg-js": "^2.4.1",
33
32
  "satori": "^0.10.1",
34
- "svelte": "^3.59.1"
33
+ "svg2png-wasm": "^1.4.0"
35
34
  },
36
35
  "keywords": [
37
36
  "open graph image",