nuxt-og-image 7.0.6 → 7.1.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 (42) hide show
  1. package/dist/chunks/tw4.mjs +1 -2
  2. package/dist/chunks/uno.mjs +5 -3
  3. package/dist/content-valibot.d.mts +9 -0
  4. package/dist/content-valibot.d.ts +9 -0
  5. package/dist/content-valibot.mjs +11 -0
  6. package/dist/module.json +1 -1
  7. package/dist/module.mjs +1 -2
  8. package/dist/runtime/app/client-utils.d.ts +1 -1
  9. package/dist/runtime/app/client-utils.js +27 -9
  10. package/dist/runtime/app/composables/_defineOgImageRaw.js +2 -3
  11. package/dist/runtime/app/utils.js +13 -5
  12. package/dist/runtime/server/og-image/bindings/font-assets/dev-prerender.js +4 -3
  13. package/dist/runtime/server/og-image/bindings/takumi/node-dev.d.ts +0 -2
  14. package/dist/runtime/server/og-image/bindings/takumi/node-dev.js +84 -59
  15. package/dist/runtime/server/og-image/bindings/takumi/node.d.ts +0 -2
  16. package/dist/runtime/server/og-image/bindings/takumi/node.js +1 -3
  17. package/dist/runtime/server/og-image/bindings/takumi/wasm.d.ts +0 -2
  18. package/dist/runtime/server/og-image/bindings/takumi/wasm.js +1 -3
  19. package/dist/runtime/server/og-image/core/plugins/imageSrc.js +5 -3
  20. package/dist/runtime/server/og-image/dev-font-state.d.ts +11 -0
  21. package/dist/runtime/server/og-image/dev-font-state.js +18 -0
  22. package/dist/runtime/server/og-image/devtools.js +2 -1
  23. package/dist/runtime/server/og-image/fonts.d.ts +9 -6
  24. package/dist/runtime/server/og-image/fonts.js +69 -38
  25. package/dist/runtime/server/og-image/satori/renderer.js +3 -3
  26. package/dist/runtime/server/og-image/satori/vnodes.js +2 -2
  27. package/dist/runtime/server/og-image/takumi/instances.d.ts +0 -2
  28. package/dist/runtime/server/og-image/takumi/instances.js +0 -3
  29. package/dist/runtime/server/og-image/takumi/renderer.js +89 -168
  30. package/dist/runtime/server/og-image/templates/html.js +2 -2
  31. package/dist/runtime/server/routes/debug.json.js +6 -6
  32. package/dist/runtime/server/routes/static-font.js +3 -3
  33. package/dist/runtime/server/signing-secret.js +19 -7
  34. package/dist/runtime/server/util/cloudflareAssets.js +1 -1
  35. package/dist/runtime/server/util/fetchLocalAsset.d.ts +1 -1
  36. package/dist/runtime/server/util/fetchLocalAsset.js +16 -10
  37. package/dist/shared/{nuxt-og-image.C4hc520M.mjs → nuxt-og-image.Dr6blNqj.mjs} +232 -100
  38. package/package.json +65 -52
  39. package/skills/nuxt-og-image/SKILL.md +2 -1
  40. package/types/virtual.d.ts +5 -0
  41. package/dist/runtime/server/og-image/bindings/takumi/resource-urls.d.ts +0 -2
  42. package/dist/runtime/server/og-image/bindings/takumi/resource-urls.js +0 -91
@@ -1,12 +1,11 @@
1
1
  import * as fs from 'node:fs';
2
2
  import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, rmSync } from 'node:fs';
3
- import { readFile, mkdir, writeFile, readdir } from 'node:fs/promises';
4
- import { findPackageJSON } from 'node:module';
3
+ import { readFile, mkdir, writeFile, readdir, rename, stat } from 'node:fs/promises';
5
4
  import { pathToFileURL, fileURLToPath } from 'node:url';
6
5
  import { resolvePath, useNuxt, getNuxtVersion, addTemplate, updateTemplates, directoryToURL, tryResolveModule, addTypeTemplate, defineNuxtModule, createResolver, addImports, hasNuxtModule, hasNuxtModuleCompatibility, getNuxtModuleVersion, addVitePlugin, addServerHandler, addServerImports, addPlugin, getLayerDirectories, addComponentsDir, addServerPlugin, getNitroVersion } from '@nuxt/kit';
7
6
  import { defu } from 'defu';
8
7
  import { fnv1a64Base36 } from 'fnv1a-64';
9
- import { resolveNitroPreset, renderNitroTypeAugmentations, setupRuntimeAliases, setupNitroRuntimeCompatibility, getNuxtModuleOptions, isNuxtGenerate } from 'nuxtseo-shared/kit';
8
+ import { resolveNitroPreset, renderNitroTypeAugmentations, findPackageJSON, setupRuntimeAliases, setupNitroRuntimeCompatibility, getNuxtModuleOptions, isNuxtGenerate } from 'nuxtseo-shared/kit';
10
9
  import { join, basename, dirname, relative, isAbsolute, resolve } from 'pathe';
11
10
  import { createHash } from 'node:crypto';
12
11
  import MagicString from 'magic-string';
@@ -221,6 +220,22 @@ function parseComponentName(name) {
221
220
  }
222
221
  return { baseName: name, renderer: null };
223
222
  }
223
+ function getComponentHashes(components) {
224
+ const hashes = {};
225
+ for (const { pascalName, kebabName, hash } of components) {
226
+ if (!hash)
227
+ continue;
228
+ hashes[pascalName] ??= hash;
229
+ hashes[kebabName] ??= hash;
230
+ }
231
+ return hashes;
232
+ }
233
+ function getAppComponents(components) {
234
+ return components.map(({ pascalName, kebabName, hash, renderer, propNames }) => ({ pascalName, kebabName, hash, renderer, propNames }));
235
+ }
236
+ function getServerComponents(components) {
237
+ return components.map(({ path: _path, credits: _credits, ...component }) => component);
238
+ }
224
239
 
225
240
  const NodeRuntime = {
226
241
  // node-server runtime
@@ -476,9 +491,6 @@ async function ensureDependencies(dep, nuxt = useNuxt()) {
476
491
  const RE_REFLECT_HAS_MINIFIED = /Reflect\.has\(([\w$]+),([\w$]+)\)\?Reflect\.get\(\1,\2,([\w$]+)\):Reflect\.get\(([\w$]+),\2,\3\)/g;
477
492
  const RE_WASM_IMPORT = /import\("(\.\/wasm\/[^"]+\.wasm)"\)/g;
478
493
  async function setupBuildHandler(config, resolve, getDetectedRenderers, nuxt = useNuxt()) {
479
- nuxt.options.nitro.storage = nuxt.options.nitro.storage || {};
480
- if (typeof config.runtimeCacheStorage === "object")
481
- nuxt.options.nitro.storage["nuxt-og-image"] = config.runtimeCacheStorage;
482
494
  const nitroConfig = nuxt.options.nitro;
483
495
  const mockCode = `import proxy from 'mocked-exports/proxy';export default proxy;export * from 'mocked-exports/proxy';`;
484
496
  nitroConfig.virtual = nitroConfig.virtual || {};
@@ -1114,22 +1126,29 @@ async function extractVarsFromCss(css) {
1114
1126
  }
1115
1127
  const MAX_VAR_SUBSTITUTIONS = 100;
1116
1128
  function resolveCssVars(css, vars) {
1129
+ return resolveCssVarsWithBudget(css, vars).value;
1130
+ }
1131
+ function resolveCssVarsWithBudget(css, vars) {
1132
+ const budget = { left: MAX_VAR_SUBSTITUTIONS };
1133
+ const value = expandVars(css, vars, /* @__PURE__ */ new Set(), budget);
1134
+ return { value, exhausted: budget.left <= 0 };
1135
+ }
1136
+ function expandVars(css, vars, expanding, budget) {
1117
1137
  let result = css;
1118
1138
  let cursor = result.length;
1119
- for (let substitutions = 0; substitutions < MAX_VAR_SUBSTITUTIONS; ) {
1139
+ while (budget.left > 0) {
1120
1140
  const idx = result.lastIndexOf("var(", cursor);
1121
1141
  if (idx === -1)
1122
1142
  break;
1123
- const resolved = substituteVar(result, idx, vars);
1124
- if (resolved === void 0) {
1125
- if (idx === 0)
1126
- break;
1127
- cursor = idx - 1;
1128
- continue;
1143
+ const resolved = substituteVar(result, idx, vars, expanding);
1144
+ if (resolved !== void 0) {
1145
+ budget.left--;
1146
+ const replacement = resolved.name === void 0 ? resolved.value : expandVars(resolved.value, vars, new Set(expanding).add(resolved.name), budget);
1147
+ result = result.substring(0, idx) + replacement + result.substring(resolved.end);
1129
1148
  }
1130
- result = result.substring(0, idx) + resolved.value + result.substring(resolved.end);
1131
- cursor = idx + resolved.value.length;
1132
- substitutions++;
1149
+ if (idx === 0)
1150
+ break;
1151
+ cursor = idx - 1;
1133
1152
  }
1134
1153
  return result;
1135
1154
  }
@@ -1145,7 +1164,7 @@ function findClosingParen(str, startIdx) {
1145
1164
  }
1146
1165
  return -1;
1147
1166
  }
1148
- function substituteVar(css, idx, vars) {
1167
+ function substituteVar(css, idx, vars, expanding) {
1149
1168
  const closeIdx = findClosingParen(css, idx + 4);
1150
1169
  if (closeIdx === -1)
1151
1170
  return void 0;
@@ -1153,11 +1172,12 @@ function substituteVar(css, idx, vars) {
1153
1172
  const comma = content.indexOf(",");
1154
1173
  const name = (comma >= 0 ? content.substring(0, comma) : content).trim();
1155
1174
  const fallback = comma >= 0 ? content.substring(comma + 1).trim() : void 0;
1156
- const value = vars.get(name);
1157
- const resolved = value !== void 0 && value.trim() !== "initial" ? value : fallback;
1158
- if (resolved === void 0)
1175
+ const value = expanding.has(name) ? void 0 : vars.get(name);
1176
+ if (value !== void 0 && value.trim() !== "initial")
1177
+ return { name, value, end: closeIdx + 1 };
1178
+ if (fallback === void 0)
1159
1179
  return void 0;
1160
- return { value: resolved, end: closeIdx + 1 };
1180
+ return { value: fallback, end: closeIdx + 1 };
1161
1181
  }
1162
1182
  function decodeCssClassName(selector) {
1163
1183
  let className = selector.startsWith(".") ? selector.slice(1) : selector;
@@ -1248,8 +1268,8 @@ async function resolveVarsDeep(value, vars, depth = 0) {
1248
1268
  }
1249
1269
  }
1250
1270
  }
1251
- const result = resolveCssVars(value, vars);
1252
- return result.includes("var(") && depth < 10 ? resolveVarsDeep(result, vars, depth + 1) : evaluateCalc(result);
1271
+ const { value: result, exhausted } = resolveCssVarsWithBudget(value, vars);
1272
+ return exhausted && result.includes("var(") && depth < 10 ? resolveVarsDeep(result, vars, depth + 1) : evaluateCalc(result);
1253
1273
  }
1254
1274
  async function downlevelColor(prop, value) {
1255
1275
  if (!value || value.includes("var("))
@@ -1691,7 +1711,7 @@ ${content}`, "utf-8");
1691
1711
  const templatePath = join(communityTemplatesDir, dotNotationName);
1692
1712
  const template = (await readFile(templatePath, "utf-8")).replace("{{ title }}", `{{ title }} - Ejected!`);
1693
1713
  await writeFile(newPath, template, { encoding: "utf-8" });
1694
- await updateTemplates({ filter: (t) => t.filename.includes("nuxt-og-image/components.mjs") });
1714
+ await updateTemplates({ filter: (t) => t.filename.includes("nuxt-og-image/components.mjs") || t.filename.includes("nuxt-og-image/component-hashes.mjs") });
1695
1715
  const nitro = await useNitro;
1696
1716
  await nitro.hooks.callHook("rollup:reload");
1697
1717
  return newPath;
@@ -1713,7 +1733,7 @@ ${content}`, "utf-8");
1713
1733
  const template = getStarterTemplate(renderer, cssFramework);
1714
1734
  await writeFile(outputPath, template, { encoding: "utf-8" });
1715
1735
  await insertDefineOgImage(name, pageFile);
1716
- await updateTemplates({ filter: (t) => t.filename.includes("nuxt-og-image/components.mjs") });
1736
+ await updateTemplates({ filter: (t) => t.filename.includes("nuxt-og-image/components.mjs") || t.filename.includes("nuxt-og-image/component-hashes.mjs") });
1717
1737
  const nitro = await useNitro;
1718
1738
  await nitro.hooks.callHook("rollup:reload");
1719
1739
  return outputPath;
@@ -1837,7 +1857,6 @@ async function extractFontFaces(css) {
1837
1857
  if (family && sources.length > 0) {
1838
1858
  fonts.push({ family, sources, weight, style, unicodeRange });
1839
1859
  }
1840
- return rule;
1841
1860
  }
1842
1861
  }
1843
1862
  }
@@ -1912,7 +1931,11 @@ async function cacheResolvedFontFiles(files, dir) {
1912
1931
  const data = await readFont();
1913
1932
  await mkdir(dir, { recursive: true });
1914
1933
  const path = join(dir, createHash("sha256").update(url).update(data).digest("hex"));
1915
- await writeFile(path, data);
1934
+ if (!existsSync(path)) {
1935
+ const tmpPath = `${path}.${process.pid}.tmp`;
1936
+ await writeFile(tmpPath, data);
1937
+ await rename(tmpPath, path);
1938
+ }
1916
1939
  paths[url] = path;
1917
1940
  }
1918
1941
  return paths;
@@ -2830,7 +2853,7 @@ async function resolveOgImageFonts(options) {
2830
2853
  const nuxtFontFamilies = new Set(
2831
2854
  hasNuxtFonts ? (await getResolvedNuxtFonts(nuxt, { fontState, requiredWeights: fontRequirements.weights })).map((f) => f.family) : []
2832
2855
  );
2833
- const fonts = !(fontRequirements.hasDynamicBindings || fontRequirements.scanned === false) ? allFonts.filter(
2856
+ const fonts = !(fontRequirements.hasDynamicBindings || fontRequirements.scanned === false || nuxt.options.dev && !hasNuxtFonts) ? allFonts.filter(
2834
2857
  (f) => nuxtFontFamilies.has(f.family) ? fontRequirements.styles.includes(f.style) : matchesFontRequirements(f, fontRequirements)
2835
2858
  ) : allFonts;
2836
2859
  const fontsByFamily = /* @__PURE__ */ new Map();
@@ -2925,6 +2948,7 @@ function setupPrerenderHandler(options, resolve, getDetectedRenderers, nuxt = us
2925
2948
  if (Array.isArray(nitroConfig.prerender.ignore)) {
2926
2949
  nitroConfig.prerender.ignore.push("/_og/d/");
2927
2950
  nitroConfig.prerender.ignore.push("/_og/r/");
2951
+ nitroConfig.prerender.ignore.push("/_og/r.png");
2928
2952
  }
2929
2953
  });
2930
2954
  let prerenderedImageCount = 0;
@@ -3027,26 +3051,30 @@ async function resolveRuntimeCacheDriver(storage, nitro, rootDir) {
3027
3051
  nitro.alias ||= {};
3028
3052
  nitro.alias["lru-cache"] = library;
3029
3053
  }
3030
- function findStorageMount(nitro, prefix) {
3031
- return Object.entries(nitro.storage || {}).map(([key, storage]) => ({ mount: key.replaceAll(":", "/").replace(/^\/+|\/+$/g, ""), storage })).filter(({ mount }) => prefix === mount || prefix.startsWith(`${mount}/`)).sort((a, b) => b.mount.length - a.mount.length)[0]?.storage;
3054
+ function findStorageMount(mounts, prefix) {
3055
+ return Object.entries(mounts || {}).map(([key, storage]) => ({ mount: key.replaceAll(":", "/").replace(/^\/+|\/+$/g, ""), storage })).filter(({ mount }) => prefix === mount || prefix.startsWith(`${mount}/`)).sort((a, b) => b.mount.length - a.mount.length)[0]?.storage;
3032
3056
  }
3033
- function configureRuntimeCacheStorage(config, nitro) {
3034
- if (typeof config.runtimeCacheStorage === "object")
3057
+ function configureRuntimeCacheStorage(config, nitro, nitroVersion) {
3058
+ const storageKey = nitroVersion === 3 ? "kv" : "storage";
3059
+ if (typeof config.runtimeCacheStorage === "object") {
3060
+ nitro[storageKey] ||= {};
3061
+ nitro[storageKey]["nuxt-og-image"] = config.runtimeCacheStorage;
3035
3062
  return config.runtimeCacheStorage;
3063
+ }
3036
3064
  if (typeof config.runtimeCacheStorage === "string")
3037
- return findStorageMount(nitro, `${config.runtimeCacheStorage.replaceAll(":", "/").replace(/^\/+|\/+$/g, "")}/nuxt-og-image`);
3065
+ return findStorageMount(nitro[storageKey], `${config.runtimeCacheStorage.replaceAll(":", "/").replace(/^\/+|\/+$/g, "")}/nuxt-og-image`);
3038
3066
  if (config.runtimeCacheStorage !== true)
3039
3067
  return;
3040
- const configuredStorage = findStorageMount(nitro, DEFAULT_CACHE_MOUNT);
3068
+ const configuredStorage = findStorageMount(nitro[storageKey], DEFAULT_CACHE_MOUNT);
3041
3069
  if (configuredStorage)
3042
3070
  return configuredStorage;
3043
- nitro.storage ||= {};
3044
- nitro.storage[DEFAULT_CACHE_MOUNT] = {
3071
+ nitro[storageKey] ||= {};
3072
+ nitro[storageKey][DEFAULT_CACHE_MOUNT] = {
3045
3073
  driver: "lru-cache",
3046
3074
  max: 0,
3047
3075
  maxSize: 64 * 1024 * 1024
3048
3076
  };
3049
- return nitro.storage[DEFAULT_CACHE_MOUNT];
3077
+ return nitro[storageKey][DEFAULT_CACHE_MOUNT];
3050
3078
  }
3051
3079
 
3052
3080
  const RE_NAMED_CALL = /\b(defineOgImage(?:Component)?)\s*\(\s*(['"`])([\w.-]+)\2/g;
@@ -3920,9 +3948,23 @@ function getOuterTemplateBounds(code) {
3920
3948
  }
3921
3949
  const AssetTransformPlugin = createUnplugin((options) => {
3922
3950
  let emojiIcons = null;
3951
+ let preprocessStyle;
3923
3952
  return {
3924
3953
  name: "nuxt-og-image:asset-transform",
3925
3954
  enforce: "pre",
3955
+ vite: {
3956
+ configResolved(config) {
3957
+ let vite;
3958
+ preprocessStyle = async (source, filename) => {
3959
+ vite ??= resolveOptionalModulePath("@nuxt/vite-builder", config.root, ["nuxt"]).then((builder) => resolveOptionalModulePath("vite", builder ? dirname(builder) : config.root)).then((path) => importOptionalPeer("vite", path, "OG component style preprocessing"));
3960
+ return (await vite).preprocessCSS(source, filename, config);
3961
+ };
3962
+ }
3963
+ },
3964
+ watchChange(id) {
3965
+ if (options.cssDependencies?.().includes(id))
3966
+ options.onCssDependencyChange?.(id);
3967
+ },
3926
3968
  transform: {
3927
3969
  filter: {
3928
3970
  id: RE_VUE_ID$1
@@ -4141,6 +4183,8 @@ const AssetTransformPlugin = createUnplugin((options) => {
4141
4183
  const componentName = id.split("/").pop();
4142
4184
  logger.warn(`[nuxt-og-image] ${componentName}: CSS template transform failed, using original template`, err.message);
4143
4185
  }
4186
+ for (const file of options.cssDependencies?.() ?? [])
4187
+ this.addWatchFile(file);
4144
4188
  }
4145
4189
  if (template.includes("var(")) {
4146
4190
  const vars = options.cssProvider?.getVars ? await options.cssProvider.getVars(rootAttrs) : /* @__PURE__ */ new Map();
@@ -4265,7 +4309,15 @@ const AssetTransformPlugin = createUnplugin((options) => {
4265
4309
  const { descriptor } = parse(code);
4266
4310
  if (descriptor.styles.length > 0) {
4267
4311
  for (const styleBlock of descriptor.styles) {
4268
- const rawCss = styleBlock.content;
4312
+ let rawCss = styleBlock.content;
4313
+ if (styleBlock.lang && styleBlock.lang !== "css") {
4314
+ if (!preprocessStyle)
4315
+ throw new Error(`Style preprocessing requires the resolved Vite configuration: ${id}`);
4316
+ const result = await preprocessStyle(rawCss, `${id}.${styleBlock.lang}`);
4317
+ rawCss = result.code;
4318
+ for (const dependency of result.deps ?? [])
4319
+ this.addWatchFile(dependency);
4320
+ }
4269
4321
  const scopeId = styleBlock.scoped ? rawCss.match(RE_SCOPED_DATA_V)?.[0] ?? null : null;
4270
4322
  const cleanCss = scopeId ? rawCss.replaceAll(scopeId, "") : rawCss;
4271
4323
  const simplified = await simplifyCss(cleanCss);
@@ -5052,11 +5104,16 @@ declare module '#og-image/fonts' {
5052
5104
  import type { FontConfig } from '${typesPath}'
5053
5105
  const fonts: FontConfig[]
5054
5106
  export default fonts
5107
+ /** The current list: in dev it follows fonts that resolve after Nitro was built */
5108
+ export function getFonts(): FontConfig[]
5055
5109
  }
5056
5110
 
5057
5111
  declare module '#og-image/fonts-available' {
5058
- const fonts: Array<{ family: string, src: string, weight: number, style: string, satoriSrc?: string, unicodeRange?: string }>
5112
+ type AvailableFont = { family: string, src: string, weight: number, style: string, satoriSrc?: string, unicodeRange?: string }
5113
+ const fonts: AvailableFont[]
5059
5114
  export default fonts
5115
+ /** The current list: in dev it follows fonts that resolve after Nitro was built */
5116
+ export function getAvailableFonts(): AvailableFont[]
5060
5117
  }
5061
5118
 
5062
5119
  declare module '#og-image/font-requirements' {
@@ -5073,6 +5130,8 @@ declare module '#og-image/font-requirements' {
5073
5130
  hasDynamicBindings: boolean
5074
5131
  category?: 'app' | 'community' | 'pro'
5075
5132
  }>
5133
+ /** The current requirements: in dev they follow components analysed after Nitro was built */
5134
+ export function getFontRequirements(): typeof fontRequirements
5076
5135
  export const hasNuxtFonts: boolean
5077
5136
  }
5078
5137
 
@@ -5108,6 +5167,8 @@ declare module '#og-image-virtual/build-dir.mjs' {
5108
5167
  export const rootDir: string
5109
5168
  export const staticFontCacheDir: string
5110
5169
  export const resolvedFontPaths: Record<string, string>
5170
+ /** The current map: in dev it follows fonts that resolve after Nitro was built */
5171
+ export function getResolvedFontPaths(): Record<string, string>
5111
5172
  }
5112
5173
 
5113
5174
  declare module '#og-image/compatibility' {
@@ -5212,12 +5273,18 @@ _ogImagePrerenderPaths?: Map<string, string>`
5212
5273
  /// <reference path="./og-image-bindings.d.ts" />
5213
5274
  import type { OgImageIconsData, OgImageOptions, OgImageRenderEventContext, OgImageRuntimeConfig, VNode } from '${typesPath}'
5214
5275
 
5276
+ declare module '@nuxt/schema' {
5277
+ interface AppRouteRulesExtensions {
5278
+ ogImage?: false | OgImageOptions & Record<string, any>
5279
+ }
5280
+ }
5281
+
5215
5282
  ${nitroAugmentations}
5216
5283
 
5217
5284
  export {}
5218
5285
  `;
5219
5286
  }
5220
- }, { nitro: true, nuxt: true });
5287
+ }, { nitro: true, node: true, nuxt: true });
5221
5288
  }
5222
5289
 
5223
5290
  const RE_INLINE_CONFIG = /const\s+inlineConfig\s*=\s*(\{[\s\S]*?\n\})/;
@@ -5398,6 +5465,7 @@ Or pin to a specific version in package.json:
5398
5465
  const { detectCssProvider } = await Promise.resolve().then(function () { return cssProvider; });
5399
5466
  const cssFramework = detectCssProvider(nuxt);
5400
5467
  let cssProvider$1;
5468
+ const cssDependencies = /* @__PURE__ */ new Set();
5401
5469
  if (cssFramework === "unocss") {
5402
5470
  logger.debug("UnoCSS detected, using UnoCSS provider for OG image styling");
5403
5471
  const { setUnoConfig, setUnoRootDir, createUnoProvider } = await import('../chunks/uno.mjs');
@@ -5428,6 +5496,7 @@ Or pin to a specific version in package.json:
5428
5496
  });
5429
5497
  if (!resolved || !existsSync(resolved))
5430
5498
  continue;
5499
+ cssDependencies.add(resolved);
5431
5500
  return resolved;
5432
5501
  }
5433
5502
  }
@@ -5490,10 +5559,11 @@ Or pin to a specific version in package.json:
5490
5559
  if (!resolvedColors)
5491
5560
  resolvedColors = { ...nuxt.options.appConfig.ui?.colors };
5492
5561
  for (const configPath of userConfigPaths) {
5562
+ cssDependencies.add(configPath);
5493
5563
  const hadShim = "defineAppConfig" in globalThis;
5494
5564
  if (!hadShim)
5495
5565
  globalThis.defineAppConfig = (config2) => config2;
5496
- const cfg = await import(pathToFileURL(configPath).href).then((m) => m.default || m).catch(() => ({}));
5566
+ const cfg = await stat(configPath).then(({ mtimeMs }) => import(`${pathToFileURL(configPath).href}?t=${mtimeMs}`)).then((m) => m.default || m).catch(() => ({}));
5497
5567
  if (!hadShim)
5498
5568
  delete globalThis.defineAppConfig;
5499
5569
  if (cfg?.ui?.colors)
@@ -5508,8 +5578,10 @@ Or pin to a specific version in package.json:
5508
5578
  cssProvider$1 = createTw4Provider({
5509
5579
  async resolveCssPath() {
5510
5580
  const aliasPath = nuxt.options.alias["#tailwindcss"];
5511
- if (aliasPath && existsSync(aliasPath))
5581
+ if (aliasPath && existsSync(aliasPath)) {
5582
+ cssDependencies.add(aliasPath);
5512
5583
  return aliasPath;
5584
+ }
5513
5585
  for (const cssEntry of nuxt.options.css) {
5514
5586
  const cssPath = typeof cssEntry === "string" ? cssEntry : cssEntry?.src;
5515
5587
  if (!cssPath || !cssPath.endsWith(".css"))
@@ -5520,8 +5592,10 @@ Or pin to a specific version in package.json:
5520
5592
  if (!resolved || !existsSync(resolved))
5521
5593
  continue;
5522
5594
  const content = await readFile(resolved, "utf-8");
5523
- if (content.includes('@import "tailwindcss"') || content.includes("@import 'tailwindcss'"))
5595
+ if (content.includes('@import "tailwindcss"') || content.includes("@import 'tailwindcss'")) {
5596
+ cssDependencies.add(resolved);
5524
5597
  return resolved;
5598
+ }
5525
5599
  }
5526
5600
  },
5527
5601
  loadNuxtUiColors
@@ -5534,6 +5608,7 @@ Or pin to a specific version in package.json:
5534
5608
  if (!_cssDirty && !_cssConfigDirty)
5535
5609
  return;
5536
5610
  cssProvider$1?.clearCache?.();
5611
+ cachedNuxtUiColors = void 0;
5537
5612
  cssMetadataPromise = void 0;
5538
5613
  Object.assign(cssMetadata, { fontVars: {}, breakpoints: {}, colors: {} });
5539
5614
  _cssConfigDirty = false;
@@ -5579,6 +5654,10 @@ Or pin to a specific version in package.json:
5579
5654
  srcDir: nuxt.options.srcDir,
5580
5655
  publicDir: isAbsolute(nuxt.options.dir.public) ? nuxt.options.dir.public : join(nuxt.options.srcDir, nuxt.options.dir.public || "public"),
5581
5656
  cssProvider: cssProvider$1,
5657
+ cssDependencies: () => [...cssDependencies],
5658
+ onCssDependencyChange: () => {
5659
+ _cssDirty = true;
5660
+ },
5582
5661
  beforeCssResolve: flushCssDirtyState,
5583
5662
  onNestedTransform: (filePath) => ogImageTransformedFiles.add(filePath),
5584
5663
  onFontRequirements(id, reqs) {
@@ -5755,6 +5834,11 @@ ${familyInfo}`);
5755
5834
  route: "/_og/r/**",
5756
5835
  handler: resolve("./runtime/server/routes/resolve")
5757
5836
  });
5837
+ addServerHandler({
5838
+ lazy: true,
5839
+ route: "/_og/r.png",
5840
+ handler: resolve("./runtime/server/routes/resolve")
5841
+ });
5758
5842
  if (!nuxt.options.dev) {
5759
5843
  nuxt.options.routeRules = nuxt.options.routeRules || {};
5760
5844
  const ttl = config.cacheMaxAgeSeconds ?? config.defaults?.cacheMaxAgeSeconds ?? 60 * 60 * 24 * 3;
@@ -5767,12 +5851,14 @@ ${familyInfo}`);
5767
5851
  { headers: { "cache-control": dynamicCacheControl } }
5768
5852
  );
5769
5853
  }
5770
- const ogResolveRule = nuxt.options.routeRules["/_og/r/**"];
5771
- if (!ogResolveRule?.swr && !ogResolveRule?.isr && !ogResolveRule?.cache && !ogResolveRule?.headers) {
5772
- nuxt.options.routeRules["/_og/r/**"] = defu(
5773
- nuxt.options.routeRules["/_og/r/**"] || {},
5774
- { headers: { "cache-control": dynamicCacheControl } }
5775
- );
5854
+ for (const route of ["/_og/r/**", "/_og/r.png"]) {
5855
+ const ogResolveRule = nuxt.options.routeRules[route];
5856
+ if (!ogResolveRule?.swr && !ogResolveRule?.isr && !ogResolveRule?.cache && !ogResolveRule?.headers) {
5857
+ nuxt.options.routeRules[route] = defu(
5858
+ nuxt.options.routeRules[route] || {},
5859
+ { headers: { "cache-control": dynamicCacheControl } }
5860
+ );
5861
+ }
5776
5862
  }
5777
5863
  }
5778
5864
  const ogStaticRule = nuxt.options.routeRules["/_og/s/**"];
@@ -6042,10 +6128,20 @@ Run: npx nuxt-og-image migrate v6`;
6042
6128
  addTemplate({
6043
6129
  filename: "nuxt-og-image/components.mjs",
6044
6130
  getContents() {
6045
- return `export const componentNames = ${JSON.stringify(ogImageComponentCtx.components)}`;
6131
+ return `export const componentNames = ${JSON.stringify(getAppComponents(ogImageComponentCtx.components))}`;
6046
6132
  },
6047
6133
  options: { mode: "server" }
6048
6134
  });
6135
+ addTemplate({
6136
+ filename: "nuxt-og-image/component-hashes.mjs",
6137
+ dependsOn: [],
6138
+ getContents() {
6139
+ return [
6140
+ `export const defaultComponentName = ${JSON.stringify(ogImageComponentCtx.components[0]?.pascalName)}`,
6141
+ `export const componentHashes = ${JSON.stringify(getComponentHashes(ogImageComponentCtx.components))}`
6142
+ ].join("\n");
6143
+ }
6144
+ });
6049
6145
  addTemplate({
6050
6146
  filename: "nuxt-og-image/client-config.mjs",
6051
6147
  getContents() {
@@ -6055,7 +6151,8 @@ Run: npx nuxt-og-image migrate v6`;
6055
6151
  });
6056
6152
  nuxt.options.nitro.virtual = nuxt.options.nitro.virtual || {};
6057
6153
  nuxt.options.nitro.virtual["#og-image-virtual/component-names.mjs"] = () => {
6058
- return `export const componentNames = ${JSON.stringify(ogImageComponentCtx.components)}`;
6154
+ const components = nuxt.options.dev ? ogImageComponentCtx.components : getServerComponents(ogImageComponentCtx.components);
6155
+ return `export const componentNames = ${JSON.stringify(components)}`;
6059
6156
  };
6060
6157
  nuxt.options.nitro.virtual["#og-image/island-hash"] = () => {
6061
6158
  const islandHashFile = join(nuxt.options.appDir, "island-hash.js");
@@ -6076,26 +6173,13 @@ Run: npx nuxt-og-image migrate v6`;
6076
6173
  fallthrough: nuxt.options.dev,
6077
6174
  maxAge: 60 * 60 * 24 * 365
6078
6175
  });
6079
- nuxt.options.nitro.virtual["#og-image-virtual/public-assets.mjs"] = async () => {
6176
+ function getFontAssetsModule(readsFilesystem) {
6080
6177
  const normalizedPreset2 = preset.replace(RE_LEGACY_SUFFIX, "");
6081
6178
  const isCloudflare = normalizedPreset2 === "cloudflare" || normalizedPreset2.startsWith("cloudflare-");
6082
- if (isCloudflare) {
6083
- const devBinding2 = resolver.resolve("./runtime/server/og-image/bindings/font-assets/dev-prerender");
6084
- const cfBinding = resolver.resolve("./runtime/server/og-image/bindings/font-assets/cloudflare");
6085
- return `
6086
- import { resolve as devResolve } from '${devBinding2}'
6087
- import { resolve as cfResolve } from '${cfBinding}'
6088
- export const resolve = (import.meta.dev || import.meta.prerender) ? devResolve : cfResolve
6089
- `;
6090
- }
6091
- const devBinding = resolver.resolve("./runtime/server/og-image/bindings/font-assets/dev-prerender");
6092
- const nodeBinding = resolver.resolve("./runtime/server/og-image/bindings/font-assets/node");
6093
- return `
6094
- import { resolve as devResolve } from '${devBinding}'
6095
- import { resolve as nodeResolve } from '${nodeBinding}'
6096
- export const resolve = (import.meta.dev || import.meta.prerender) ? devResolve : nodeResolve
6097
- `;
6098
- };
6179
+ const binding = readsFilesystem ? "dev-prerender" : isCloudflare ? "cloudflare" : "node";
6180
+ return `export { resolve } from '${resolver.resolve(`./runtime/server/og-image/bindings/font-assets/${binding}`)}'`;
6181
+ }
6182
+ nuxt.options.nitro.virtual["#og-image-virtual/public-assets.mjs"] = () => getFontAssetsModule(nuxt.options.dev);
6099
6183
  const hasSatoriRenderer = () => ogImageComponentCtx.detectedRenderers.has("satori");
6100
6184
  const hasTakumiRenderer = () => ogImageComponentCtx.detectedRenderers.has("takumi");
6101
6185
  const nuxtFontFiles = /* @__PURE__ */ new Map();
@@ -6105,25 +6189,57 @@ export const resolve = (import.meta.dev || import.meta.prerender) ? devResolve :
6105
6189
  const currentFontKey = () => JSON.stringify([
6106
6190
  getResolvedFontStateKey(fontState),
6107
6191
  fontRequirementsState.weights,
6108
- fontRequirementsState.styles
6192
+ fontRequirementsState.styles,
6193
+ fontRequirementsState.families,
6194
+ fontRequirementsState.hasDynamicBindings
6109
6195
  ]);
6110
- let reloadNitro;
6196
+ const globalFontRequirements = () => ({
6197
+ weights: fontRequirementsState.weights,
6198
+ styles: fontRequirementsState.styles,
6199
+ families: fontRequirementsState.families,
6200
+ // Unanalysed components (webpack, rspack) may use any font, like dynamic bindings
6201
+ hasDynamicBindings: fontRequirementsState.hasDynamicBindings || !fontRequirementsState.scanned
6202
+ });
6203
+ const devFontStatePath = join(nuxt.options.buildDir, "cache", "og-image", "dev-font-state.json");
6204
+ if (nuxt.options.dev)
6205
+ fs.rmSync(devFontStatePath, { force: true });
6206
+ let devFontStateWrite;
6207
+ let devFontStateStale = false;
6208
+ let publishedFontKey;
6209
+ async function writeDevFontState() {
6210
+ const key = currentFontKey();
6211
+ const fonts = await getFontList();
6212
+ const [available, resolvedFontPaths] = await Promise.all([getAvailableFontList(), getResolvedFontPaths()]);
6213
+ const state = JSON.stringify({ fonts, available, resolvedFontPaths, requirements: globalFontRequirements() });
6214
+ await mkdir(dirname(devFontStatePath), { recursive: true });
6215
+ const tmpPath = `${devFontStatePath}.${process.pid}.tmp`;
6216
+ await writeFile(tmpPath, state);
6217
+ await rename(tmpPath, devFontStatePath);
6218
+ publishedFontKey = key;
6219
+ }
6111
6220
  function refreshDevFonts() {
6112
- if (!reloadNitro || builtFontKey === void 0 || builtFontKey === currentFontKey())
6221
+ if (!nuxt.options.dev || !hasNuxtFonts || builtFontKey === void 0 || (publishedFontKey ?? builtFontKey) === currentFontKey())
6222
+ return;
6223
+ if (devFontStateWrite) {
6224
+ devFontStateStale = true;
6113
6225
  return;
6114
- reloadNitro().catch((error) => {
6115
- logger.warn(`Could not rebuild the OG image font list: ${error.message}`);
6226
+ }
6227
+ fontProcessingDone = false;
6228
+ devFontStateWrite = writeDevFontState().catch((error) => {
6229
+ logger.warn(`Could not refresh the OG image font list: ${error.message}`);
6230
+ }).finally(() => {
6231
+ devFontStateWrite = void 0;
6232
+ if (devFontStateStale) {
6233
+ devFontStateStale = false;
6234
+ refreshDevFonts();
6235
+ }
6116
6236
  });
6117
6237
  }
6118
- if (nuxt.options.dev) {
6119
- nuxt.hook("nitro:init", (nitro) => {
6120
- let pending;
6121
- reloadNitro = () => pending ||= Promise.resolve().then(async () => {
6122
- pending = void 0;
6123
- fontProcessingDone = false;
6124
- await nitro.hooks.callHook("rollup:reload");
6125
- });
6126
- });
6238
+ function fontStateGetter(getter, field) {
6239
+ if (!nuxt.options.dev)
6240
+ return `export function ${getter}() { return _value }`;
6241
+ return `import { readDevFontState } from ${JSON.stringify(resolve("./runtime/server/og-image/dev-font-state"))}
6242
+ export function ${getter}() { return readDevFontState(${JSON.stringify(devFontStatePath)})?.${field} ?? _value }`;
6127
6243
  }
6128
6244
  async function resolveFontList() {
6129
6245
  builtFontKey = currentFontKey();
@@ -6162,21 +6278,39 @@ export const resolve = (import.meta.dev || import.meta.prerender) ? devResolve :
6162
6278
  builtFontList = { key, fonts: resolveFontList() };
6163
6279
  return builtFontList.fonts;
6164
6280
  }
6165
- nuxt.options.nitro.virtual["#og-image/fonts"] = async () => `export default ${JSON.stringify(await getFontList())}`;
6281
+ async function getFontsModule(readsFilesystem) {
6282
+ const fonts = await getFontList();
6283
+ return `const _value = ${JSON.stringify(readsFilesystem ? fonts : fonts.map(({ absolutePath: _absolutePath, ...font }) => font))}
6284
+ export default _value
6285
+ ${fontStateGetter("getFonts", "fonts")}`;
6286
+ }
6287
+ function getAvailableFontList() {
6288
+ return hasNuxtFonts ? getResolvedNuxtFonts(nuxt, { fontState, requiredWeights: fontRequirementsState.weights }) : Promise.resolve([]);
6289
+ }
6290
+ function getResolvedFontPaths() {
6291
+ return cacheResolvedFontFiles(nuxtFontFiles, join(nuxt.options.buildDir, "cache", "og-image", "resolved-fonts"));
6292
+ }
6293
+ nuxt.options.nitro.virtual["#og-image/fonts"] = () => getFontsModule(nuxt.options.dev);
6294
+ nuxt.hook("nitro:init", (nitro) => {
6295
+ nitro.hooks.hook("prerender:config", (prerenderConfig) => {
6296
+ prerenderConfig.virtual = {
6297
+ ...prerenderConfig.virtual,
6298
+ "#og-image/fonts": () => getFontsModule(true),
6299
+ "#og-image-virtual/public-assets.mjs": () => getFontAssetsModule(true)
6300
+ };
6301
+ });
6302
+ });
6166
6303
  nuxt.options.nitro.virtual["#og-image/fonts-available"] = async () => {
6167
- const fonts = hasNuxtFonts ? await getResolvedNuxtFonts(nuxt, { fontState, requiredWeights: fontRequirementsState.weights }) : [];
6168
- return `export default ${JSON.stringify(fonts)}`;
6304
+ return `const _value = ${JSON.stringify(await getAvailableFontList())}
6305
+ export default _value
6306
+ ${fontStateGetter("getAvailableFonts", "available")}`;
6169
6307
  };
6170
6308
  nuxt.options.nitro.virtual["#og-image/font-requirements"] = async () => {
6171
6309
  if (pendingFontRequirements.length > 0)
6172
6310
  await Promise.all(pendingFontRequirements);
6173
- const baseExports = `export const fontRequirements = ${JSON.stringify({
6174
- weights: fontRequirementsState.weights,
6175
- styles: fontRequirementsState.styles,
6176
- families: fontRequirementsState.families,
6177
- // Unanalysed components (webpack, rspack) may use any font, like dynamic bindings
6178
- hasDynamicBindings: fontRequirementsState.hasDynamicBindings || !fontRequirementsState.scanned
6179
- })}
6311
+ const baseExports = `const _value = ${JSON.stringify(globalFontRequirements())}
6312
+ export const fontRequirements = _value
6313
+ ${fontStateGetter("getFontRequirements", "requirements")}
6180
6314
  export const hasNuxtFonts = ${JSON.stringify(hasNuxtFonts)}`;
6181
6315
  if (nuxt.options.dev) {
6182
6316
  const mapPath = join(nuxt.options.buildDir, "cache", "og-image", "component-font-map.json");
@@ -6199,10 +6333,12 @@ export const tw4Breakpoints = ${JSON.stringify(cssMetadata.breakpoints)}
6199
6333
  export const tw4Colors = ${JSON.stringify(cssMetadata.colors)}`;
6200
6334
  };
6201
6335
  nuxt.options.nitro.virtual["#og-image-virtual/build-dir.mjs"] = async () => {
6202
- const resolvedFontPaths = await cacheResolvedFontFiles(nuxtFontFiles, join(nuxt.options.buildDir, "cache", "og-image", "resolved-fonts"));
6336
+ const resolvedFontPaths = await getResolvedFontPaths();
6203
6337
  return `export const buildDir = ${JSON.stringify(nuxt.options.buildDir)}
6204
6338
  export const rootDir = ${JSON.stringify(nuxt.options.rootDir)}
6205
- export const resolvedFontPaths = ${JSON.stringify(resolvedFontPaths)}
6339
+ const _value = ${JSON.stringify(resolvedFontPaths)}
6340
+ export const resolvedFontPaths = _value
6341
+ ${fontStateGetter("getResolvedFontPaths", "resolvedFontPaths")}
6206
6342
  export const staticFontCacheDir = ${JSON.stringify(getStaticFontCacheDir(nuxt.options.buildDir))}`;
6207
6343
  };
6208
6344
  if (hasNuxtFonts) {
@@ -6274,10 +6410,6 @@ export const staticFontCacheDir = ${JSON.stringify(getStaticFontCacheDir(nuxt.op
6274
6410
  baseCacheKey = `/${config.runtimeCacheStorage}/nuxt-og-image${versionSuffix}`;
6275
6411
  } else if (typeof config.runtimeCacheStorage === "object") {
6276
6412
  baseCacheKey = `/nuxt-og-image${versionSuffix}`;
6277
- if (!nuxt.options.dev) {
6278
- nuxt.options.nitro.storage = nuxt.options.nitro.storage || {};
6279
- nuxt.options.nitro.storage["nuxt-og-image"] = config.runtimeCacheStorage;
6280
- }
6281
6413
  } else {
6282
6414
  baseCacheKey = false;
6283
6415
  }
@@ -6285,7 +6417,7 @@ export const staticFontCacheDir = ${JSON.stringify(getStaticFontCacheDir(nuxt.op
6285
6417
  baseCacheKey = false;
6286
6418
  let hasUnboundedRuntimeCache = false;
6287
6419
  nuxt.hooks.hook("nitro:config", async (nitroConfig) => {
6288
- const storage = configureRuntimeCacheStorage(config, nitroConfig);
6420
+ const storage = configureRuntimeCacheStorage(config, nitroConfig, nitroCompatibility._tag === "nitro-v3" ? 3 : 2);
6289
6421
  await resolveRuntimeCacheDriver(storage, nitroConfig, nuxt.options.rootDir);
6290
6422
  hasUnboundedRuntimeCache = storage?.driver === "memory";
6291
6423
  });