nuxt-og-image 2.0.5 → 2.0.7

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 (32) hide show
  1. package/dist/client/200.html +2 -2
  2. package/dist/client/404.html +2 -2
  3. package/dist/client/_nuxt/{IconCSS.c66ac96c.js → IconCSS.444dbaf2.js} +1 -1
  4. package/dist/client/_nuxt/{ImageLoader.eea58cf7.js → ImageLoader.3238b676.js} +1 -1
  5. package/dist/client/_nuxt/{entry.db904b01.js → entry.fd330f13.js} +3 -3
  6. package/dist/client/_nuxt/{error-404.3fd437f7.js → error-404.01ee9ac3.js} +1 -1
  7. package/dist/client/_nuxt/{error-500.48bc2fce.js → error-500.f700afa0.js} +1 -1
  8. package/dist/client/_nuxt/{index.62ad0f4a.js → index.4bbde254.js} +1 -1
  9. package/dist/client/_nuxt/{options.8bd8132d.js → options.ed57f98c.js} +1 -1
  10. package/dist/client/_nuxt/{png.8fd55f17.js → png.31a238a6.js} +1 -1
  11. package/dist/client/_nuxt/{shiki.eca11a4d.js → shiki.87c664fb.js} +1 -1
  12. package/dist/client/_nuxt/{svg.6552a6ca.js → svg.45bd4aa7.js} +1 -1
  13. package/dist/client/_nuxt/{vnodes.5bb613d8.js → vnodes.f494cd39.js} +1 -1
  14. package/dist/client/index.html +2 -2
  15. package/dist/module.json +1 -1
  16. package/dist/module.mjs +19 -14
  17. package/dist/runtime/cache.d.ts +12 -0
  18. package/dist/runtime/cache.mjs +42 -0
  19. package/dist/runtime/composables/defineOgImage.mjs +2 -2
  20. package/dist/runtime/nitro/middleware/og.png.mjs +21 -23
  21. package/dist/runtime/nitro/middleware/playground.mjs +2 -2
  22. package/dist/runtime/nitro/plugins/prerender.mjs +25 -16
  23. package/dist/runtime/nitro/routes/html.mjs +2 -2
  24. package/dist/runtime/nitro/routes/options.d.ts +2 -2
  25. package/dist/runtime/nitro/routes/options.mjs +5 -12
  26. package/dist/runtime/nitro/routes/svg.mjs +2 -2
  27. package/dist/runtime/nitro/routes/vnode.mjs +2 -2
  28. package/dist/runtime/nitro/utils-pure.d.ts +1 -1
  29. package/dist/runtime/nitro/utils-pure.mjs +16 -11
  30. package/dist/runtime/nitro/utils.d.ts +1 -0
  31. package/dist/runtime/nitro/utils.mjs +33 -34
  32. package/package.json +4 -4
@@ -1,20 +1,20 @@
1
1
  import { Buffer } from "node:buffer";
2
2
  import { createError, defineEventHandler, sendRedirect, setHeader } from "h3";
3
- import { joinURL, parseURL, withoutTrailingSlash } from "ufo";
4
- import { prefixStorage } from "unstorage";
3
+ import { joinURL, parseURL, withoutLeadingSlash, withoutTrailingSlash } from "ufo";
5
4
  import { hash } from "ohash";
6
- import { fetchOptions } from "../utils.mjs";
5
+ import { fetchOptionsCached } from "../utils.mjs";
6
+ import { useNitroCache } from "../../cache.mjs";
7
7
  import { useProvider } from "#nuxt-og-image/provider";
8
- import { useNitroOrigin, useRuntimeConfig, useStorage } from "#imports";
8
+ import { useNitroOrigin, useRuntimeConfig } from "#imports";
9
9
  export default defineEventHandler(async (e) => {
10
- const { runtimeBrowser, runtimeCacheStorage, version } = useRuntimeConfig()["nuxt-og-image"];
10
+ const { runtimeBrowser } = useRuntimeConfig()["nuxt-og-image"];
11
11
  const path = parseURL(e.path).pathname;
12
12
  if (!path.endsWith("__og_image__/og.png"))
13
13
  return;
14
14
  const basePath = withoutTrailingSlash(
15
15
  path.replace("__og_image__/og.png", "")
16
16
  );
17
- const options = await fetchOptions(e, basePath);
17
+ const options = await fetchOptionsCached(e, basePath);
18
18
  if (process.env.NODE_ENV === "production" && !process.env.prerender && !runtimeBrowser && options.provider === "browser")
19
19
  return sendRedirect(e, joinURL(useNitroOrigin(e), "__nuxt_og_image__/browser-provider-not-supported.png"));
20
20
  const provider = await useProvider(options.provider);
@@ -24,27 +24,25 @@ export default defineEventHandler(async (e) => {
24
24
  statusMessage: `Provider ${options.provider} is missing.`
25
25
  });
26
26
  }
27
- const useCache = runtimeCacheStorage && !process.dev && options.cacheTtl && options.cacheTtl > 0 && options.cache;
28
- const baseCacheKey = runtimeCacheStorage === "default" ? `/cache/og-image${version}` : `/og-image/${version}`;
29
- const cache = prefixStorage(useStorage(), `${baseCacheKey}/images`);
30
- const key = [options.path === "/" || !options.path ? "index" : options.path, hash(options)].join(":");
27
+ const key = [
28
+ withoutLeadingSlash(options.path === "/" || !options.path ? "index" : options.path).replaceAll("/", "-"),
29
+ `og-${hash(options)}`
30
+ ].join(":");
31
+ const { enabled: cacheEnabled, cachedItem, update } = await useNitroCache(e, "nuxt-og-image", {
32
+ key,
33
+ cacheTtl: options.cacheTtl || 0,
34
+ cache: process.dev && options.cache,
35
+ headers: true
36
+ });
31
37
  let png;
32
- if (useCache && await cache.hasItem(key)) {
33
- const { value, expiresAt } = await cache.getItem(key);
34
- if (expiresAt > Date.now()) {
35
- setHeader(e, "Cache-Control", "public, max-age=31536000");
36
- setHeader(e, "Content-Type", "image/png");
37
- png = Buffer.from(value, "base64");
38
- } else {
39
- await cache.removeItem(key);
40
- }
41
- }
38
+ if (cachedItem)
39
+ png = Buffer.from(cachedItem, "base64");
42
40
  if (!png) {
43
41
  try {
44
42
  png = await provider.createPng(options);
45
- if (useCache && png) {
43
+ if (png) {
46
44
  const base64png = Buffer.from(png).toString("base64");
47
- await cache.setItem(key, { value: base64png, expiresAt: Date.now() + (options.cacheTtl || 0) });
45
+ await update(base64png);
48
46
  }
49
47
  } catch (err) {
50
48
  throw createError({
@@ -54,7 +52,7 @@ export default defineEventHandler(async (e) => {
54
52
  }
55
53
  }
56
54
  if (png) {
57
- if (!process.dev && options.cache) {
55
+ if (cacheEnabled) {
58
56
  setHeader(e, "Cache-Control", "public, max-age=31536000");
59
57
  } else {
60
58
  setHeader(e, "Cache-Control", "no-cache, no-store, must-revalidate");
@@ -1,13 +1,13 @@
1
1
  import { defineEventHandler } from "h3";
2
2
  import { parseURL, withBase, withoutTrailingSlash } from "ufo";
3
- import { fetchOptions } from "../utils.mjs";
3
+ import { fetchOptionsCached } from "../utils.mjs";
4
4
  import { useRuntimeConfig } from "#imports";
5
5
  export default defineEventHandler(async (e) => {
6
6
  const path = withoutTrailingSlash(parseURL(e.path).pathname);
7
7
  if (!path.endsWith("/__og_image__"))
8
8
  return;
9
9
  const basePath = withBase(path.replace("/__og_image__", ""), useRuntimeConfig().app.baseURL);
10
- const options = await fetchOptions(e, basePath === "" ? "/" : basePath);
10
+ const options = await fetchOptionsCached(e, basePath === "" ? "/" : basePath);
11
11
  if (!options)
12
12
  return `The route ${basePath} has not been set up for og:image generation.`;
13
13
  return `
@@ -1,28 +1,37 @@
1
1
  import { appendHeader } from "h3";
2
- import { joinURL } from "ufo";
3
- import { prefixStorage } from "unstorage";
4
- import { extractOgImageOptions } from "../utils-pure.mjs";
5
- import { useRuntimeConfig, useStorage } from "#imports";
6
- const OgImagePrenderNitroPlugin = (nitroApp) => {
2
+ import { joinURL, withoutLeadingSlash } from "ufo";
3
+ import { extractAndNormaliseOgImageOptions } from "../utils-pure.mjs";
4
+ import { useNitroCache } from "../../cache.mjs";
5
+ import { getRouteRules } from "#internal/nitro";
6
+ const OgImagePrenderNitroPlugin = async (nitroApp) => {
7
7
  if (!process.env.prerender)
8
8
  return;
9
- const { runtimeCacheStorage } = useRuntimeConfig()["nuxt-og-image"];
10
- const baseCacheKey = runtimeCacheStorage === "default" ? "/cache/og-image" : "/og-image";
11
- const cache = prefixStorage(useStorage(), `${baseCacheKey}/options`);
9
+ const { defaults } = useRuntimeConfig()["nuxt-og-image"];
12
10
  nitroApp.hooks.hook("render:html", async (ctx, { event }) => {
13
- const url = event.node.req.url;
14
- if (url.includes(".") || url.startsWith("/__nuxt_island/"))
11
+ const path = event.node.req.url;
12
+ if (path.includes(".") || path.startsWith("/__nuxt_island/"))
15
13
  return;
16
- const options = extractOgImageOptions(ctx.head.join("\n"));
14
+ const routeRules = getRouteRules(event)?.ogImage || {};
15
+ if (routeRules === false)
16
+ return;
17
+ const options = extractAndNormaliseOgImageOptions(path, ctx.head.join("\n"), routeRules, defaults);
17
18
  if (!options)
18
19
  return;
19
- await cache.setItem(url === "/" || !url ? "index" : url, {
20
- value: JSON.stringify(options),
21
- expiresAt: Date.now() + 60 * 60 * 1e3
22
- // 60 minutes to prerender
20
+ const key = [
21
+ withoutLeadingSlash(path === "/" || !path ? "index" : path).replaceAll("/", "-"),
22
+ "options"
23
+ ].join(":");
24
+ const { update } = await useNitroCache(event, "nuxt-og-image", {
25
+ key,
26
+ // shouldn't change for the prerender, 5 min cache
27
+ cacheTtl: 5 * 60 * 1e3,
28
+ cache: true,
29
+ headers: false,
30
+ skipRestore: true
23
31
  });
32
+ await update(options);
24
33
  if (options.provider === "satori")
25
- appendHeader(event, "x-nitro-prerender", joinURL(url, "/__og_image__/og.png"));
34
+ appendHeader(event, "x-nitro-prerender", joinURL(path, "/__og_image__/og.png"));
26
35
  });
27
36
  };
28
37
  export default OgImagePrenderNitroPlugin;
@@ -5,7 +5,7 @@ import { createError, defineEventHandler, getQuery, sendRedirect } from "h3";
5
5
  import { hash } from "ohash";
6
6
  import twemoji from "twemoji";
7
7
  import { defu } from "defu";
8
- import { fetchOptions } from "../utils.mjs";
8
+ import { fetchOptionsCached } from "../utils.mjs";
9
9
  import { useNitroOrigin, useRuntimeConfig } from "#imports";
10
10
  import loadInlineCSS from "#nuxt-og-image/inline-css";
11
11
  export default defineEventHandler(async (e) => {
@@ -22,7 +22,7 @@ export default defineEventHandler(async (e) => {
22
22
  } catch {
23
23
  }
24
24
  }
25
- let options = await fetchOptions(e, path);
25
+ let options = await fetchOptionsCached(e, path);
26
26
  if (queryOptions)
27
27
  options = defu(queryOptions, options);
28
28
  if (options.provider === "browser" && !options.component) {
@@ -1,3 +1,3 @@
1
- import type { RuntimeOgImageOptions } from '../../types';
2
- declare const _default: import("h3").EventHandler<false | RuntimeOgImageOptions>;
1
+ import type { OgImageOptions } from '../../types';
2
+ declare const _default: import("h3").EventHandler<false | OgImageOptions>;
3
3
  export default _default;
@@ -1,7 +1,6 @@
1
1
  import { createError, defineEventHandler, getQuery } from "h3";
2
2
  import { withoutBase } from "ufo";
3
- import { defu } from "defu";
4
- import { extractOgImageOptions } from "../utils.mjs";
3
+ import { extractAndNormaliseOgImageOptions } from "../utils.mjs";
5
4
  import { getRouteRules } from "#internal/nitro";
6
5
  import { useRuntimeConfig } from "#imports";
7
6
  export default defineEventHandler(async (e) => {
@@ -24,19 +23,13 @@ export default defineEventHandler(async (e) => {
24
23
  e.node.req.url = e.path;
25
24
  if (routeRules === false)
26
25
  return false;
27
- const extractedPayload = extractOgImageOptions(html, routeRules);
28
- if (!extractedPayload) {
26
+ const { defaults } = useRuntimeConfig()["nuxt-og-image"];
27
+ const payload = extractAndNormaliseOgImageOptions(path, html, routeRules, defaults);
28
+ if (!payload) {
29
29
  throw createError({
30
30
  statusCode: 500,
31
31
  statusMessage: `The path ${path} is missing the og-image payload.`
32
32
  });
33
33
  }
34
- const { defaults } = useRuntimeConfig()["nuxt-og-image"];
35
- return defu(
36
- extractedPayload,
37
- routeRules,
38
- // runtime options
39
- { path },
40
- defaults
41
- );
34
+ return payload;
42
35
  });
@@ -1,12 +1,12 @@
1
1
  import { createError, defineEventHandler, getQuery, setHeader } from "h3";
2
2
  import { withBase } from "ufo";
3
- import { fetchOptions } from "../utils.mjs";
3
+ import { fetchOptionsCached } from "../utils.mjs";
4
4
  import { useProvider } from "#nuxt-og-image/provider";
5
5
  import { useRuntimeConfig } from "#imports";
6
6
  export default defineEventHandler(async (e) => {
7
7
  const query = getQuery(e);
8
8
  const path = withBase(query.path || "/", useRuntimeConfig().app.baseURL);
9
- const options = await fetchOptions(e, path);
9
+ const options = await fetchOptionsCached(e, path);
10
10
  setHeader(e, "Content-Type", "image/svg+xml");
11
11
  const provider = await useProvider(options.provider);
12
12
  if (!provider) {
@@ -1,12 +1,12 @@
1
1
  import { createError, defineEventHandler, getQuery, setHeader } from "h3";
2
2
  import { withBase } from "ufo";
3
- import { fetchOptions } from "../utils.mjs";
3
+ import { fetchOptionsCached } from "../utils.mjs";
4
4
  import { useProvider } from "#nuxt-og-image/provider";
5
5
  import { useRuntimeConfig } from "#imports";
6
6
  export default defineEventHandler(async (e) => {
7
7
  const query = getQuery(e);
8
8
  const path = withBase(query.path || "/", useRuntimeConfig().app.baseURL);
9
- const options = await fetchOptions(e, path);
9
+ const options = await fetchOptionsCached(e, path);
10
10
  setHeader(e, "Content-Type", "application/json");
11
11
  const provider = await useProvider(options.provider);
12
12
  if (!provider) {
@@ -1,3 +1,3 @@
1
1
  import type { OgImageOptions } from '../types';
2
2
  export declare function decodeHtml(html: string): string;
3
- export declare function extractOgImageOptions(html: string, routeRules: OgImageOptions): OgImageOptions | false;
3
+ export declare function extractAndNormaliseOgImageOptions(path: string, html: string, routeRules: OgImageOptions, defaults: OgImageOptions): OgImageOptions | false;
@@ -11,7 +11,7 @@ function decodeObjectHtmlEntities(obj) {
11
11
  });
12
12
  return obj;
13
13
  }
14
- export function extractOgImageOptions(html, routeRules) {
14
+ export function extractAndNormaliseOgImageOptions(path, html, routeRules, defaults) {
15
15
  const htmlPayload = html.match(/<script id="nuxt-og-image-options" type="application\/json">(.+?)<\/script>/)?.[1];
16
16
  if (!htmlPayload)
17
17
  return false;
@@ -28,15 +28,20 @@ export function extractOgImageOptions(html, routeRules) {
28
28
  if (process.dev)
29
29
  console.warn("Failed to parse #nuxt-og-image-options", e, options);
30
30
  }
31
- if (options) {
32
- if (!options.description) {
33
- const description = html.match(/<meta property="og:description" content="(.*?)">/)?.[1];
34
- if (description)
35
- options.description = description;
36
- else
37
- options.description = html.match(/<meta name="description" content="(.*?)">/)?.[1];
38
- }
39
- return decodeObjectHtmlEntities(options);
31
+ if (!options)
32
+ return false;
33
+ if (!options.description) {
34
+ const description = html.match(/<meta property="og:description" content="(.*?)">/)?.[1];
35
+ if (description)
36
+ options.description = description;
37
+ else
38
+ options.description = html.match(/<meta name="description" content="(.*?)">/)?.[1];
40
39
  }
41
- return false;
40
+ const decoded = decodeObjectHtmlEntities(options);
41
+ return defu(
42
+ decoded,
43
+ // runtime options
44
+ { path },
45
+ defaults
46
+ );
42
47
  }
@@ -5,6 +5,7 @@ import type { RuntimeOgImageOptions } from '../types';
5
5
  export declare function wasmLoader(asyncModuleLoad: Promise<any> | Buffer | string, fallback: string): {
6
6
  load(options: RuntimeOgImageOptions): Promise<any>;
7
7
  };
8
+ export declare function fetchOptionsCached(e: H3Event, path: string): Promise<RuntimeOgImageOptions>;
8
9
  export declare function fetchOptions(e: H3Event, path: string): Promise<RuntimeOgImageOptions>;
9
10
  export declare function base64ToArrayBuffer(base64: string): ArrayBuffer;
10
11
  export declare function readPublicAsset(file: string, encoding?: BufferEncoding): Promise<string | Buffer | undefined>;
@@ -2,9 +2,11 @@ import { existsSync, promises as fsp } from "node:fs";
2
2
  import { Buffer } from "node:buffer";
3
3
  import { getQuery } from "h3";
4
4
  import { join } from "pathe";
5
- import { prefixStorage } from "unstorage";
6
5
  import sizeOf from "image-size";
7
- import { useNitroOrigin, useRuntimeConfig, useStorage } from "#imports";
6
+ import { defu } from "defu";
7
+ import { withoutLeadingSlash } from "ufo";
8
+ import { useNitroCache } from "../cache.mjs";
9
+ import { useNitroOrigin, useRuntimeConfig } from "#imports";
8
10
  export function wasmLoader(asyncModuleLoad, fallback) {
9
11
  let promise;
10
12
  let wasm;
@@ -36,40 +38,37 @@ export function wasmLoader(asyncModuleLoad, fallback) {
36
38
  }
37
39
  };
38
40
  }
41
+ export async function fetchOptionsCached(e, path) {
42
+ const key = [
43
+ withoutLeadingSlash(path === "/" || !path ? "index" : path).replaceAll("/", "-"),
44
+ "options"
45
+ ].join(":");
46
+ const { cachedItem, update } = await useNitroCache(e, "nuxt-og-image", {
47
+ key,
48
+ // allow internal requests to be cached
49
+ cacheTtl: 5 * 1e3,
50
+ cache: !process.dev,
51
+ headers: false
52
+ });
53
+ if (cachedItem)
54
+ return cachedItem;
55
+ const options = await fetchOptions(e, path);
56
+ await update(options);
57
+ return options;
58
+ }
39
59
  export async function fetchOptions(e, path) {
40
- const { runtimeCacheStorage, version } = useRuntimeConfig()["nuxt-og-image"];
41
- const baseCacheKey = runtimeCacheStorage === "default" ? `/cache/og-image${version}` : `/og-image/${version}`;
42
- const cache = runtimeCacheStorage || process.env.prerender ? prefixStorage(useStorage(), `${baseCacheKey}/options`) : false;
43
- const key = [path === "/" || !path ? "index" : path].join(":");
44
- let options;
45
- if (!process.dev && cache && await cache.hasItem(key)) {
46
- const cachedValue = await cache.getItem(key);
47
- if (cachedValue && cachedValue.value && cachedValue.expiresAt < Date.now())
48
- options = cachedValue.value;
49
- else
50
- await cache.removeItem(key);
51
- }
52
- if (!options) {
53
- options = await globalThis.$fetch("/api/og-image-options", {
54
- query: {
55
- path
56
- },
57
- responseType: "json"
58
- });
59
- if (cache) {
60
- await cache.setItem(key, {
61
- value: options,
62
- // cache for 1 minute or 5 seconds, avoids subsequent internal fetches
63
- expiresAt: Date.now() + (options.cache ? 60 * 1e3 : 5 * 1e3)
64
- });
65
- }
66
- }
67
- return {
68
- ...options,
60
+ const options = await globalThis.$fetch("/api/og-image-options", {
61
+ query: {
62
+ path
63
+ },
64
+ responseType: "json"
65
+ });
66
+ return defu(
67
+ { requestOrigin: useNitroOrigin(e) },
68
+ options,
69
69
  // use query data
70
- ...getQuery(e),
71
- requestOrigin: useNitroOrigin(e)
72
- };
70
+ getQuery(e)
71
+ );
73
72
  }
74
73
  export function base64ToArrayBuffer(base64) {
75
74
  const buffer = Buffer.from(base64, "base64");
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "nuxt-og-image",
3
3
  "type": "module",
4
- "version": "2.0.5",
5
- "packageManager": "pnpm@8.6.6",
4
+ "version": "2.0.7",
5
+ "packageManager": "pnpm@8.6.7",
6
6
  "description": "Enlightened OG Image generation for Nuxt.",
7
7
  "license": "MIT",
8
8
  "funding": "https://github.com/sponsors/harlan-zw",
@@ -43,8 +43,8 @@
43
43
  "image-size": "^1.0.2",
44
44
  "inline-css": "^4.0.2",
45
45
  "launch-editor": "^2.6.0",
46
- "nuxt-site-config": "^1.0.3",
47
- "nuxt-site-config-kit": "^1.0.3",
46
+ "nuxt-site-config": "^1.0.5",
47
+ "nuxt-site-config-kit": "^1.0.5",
48
48
  "nypm": "^0.2.2",
49
49
  "ofetch": "^1.1.1",
50
50
  "ohash": "^1.1.2",