nuxt-og-image 7.0.7 → 7.1.1

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 (40) 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/context.js +1 -1
  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/shared/urlEncoding.js +13 -5
  35. package/dist/shared/{nuxt-og-image.CS4ArVpM.mjs → nuxt-og-image.Dr6blNqj.mjs} +225 -99
  36. package/package.json +65 -56
  37. package/skills/nuxt-og-image/SKILL.md +2 -1
  38. package/types/virtual.d.ts +5 -0
  39. package/dist/runtime/server/og-image/bindings/takumi/resource-urls.d.ts +0 -2
  40. 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' {
@@ -5404,6 +5465,7 @@ Or pin to a specific version in package.json:
5404
5465
  const { detectCssProvider } = await Promise.resolve().then(function () { return cssProvider; });
5405
5466
  const cssFramework = detectCssProvider(nuxt);
5406
5467
  let cssProvider$1;
5468
+ const cssDependencies = /* @__PURE__ */ new Set();
5407
5469
  if (cssFramework === "unocss") {
5408
5470
  logger.debug("UnoCSS detected, using UnoCSS provider for OG image styling");
5409
5471
  const { setUnoConfig, setUnoRootDir, createUnoProvider } = await import('../chunks/uno.mjs');
@@ -5434,6 +5496,7 @@ Or pin to a specific version in package.json:
5434
5496
  });
5435
5497
  if (!resolved || !existsSync(resolved))
5436
5498
  continue;
5499
+ cssDependencies.add(resolved);
5437
5500
  return resolved;
5438
5501
  }
5439
5502
  }
@@ -5496,10 +5559,11 @@ Or pin to a specific version in package.json:
5496
5559
  if (!resolvedColors)
5497
5560
  resolvedColors = { ...nuxt.options.appConfig.ui?.colors };
5498
5561
  for (const configPath of userConfigPaths) {
5562
+ cssDependencies.add(configPath);
5499
5563
  const hadShim = "defineAppConfig" in globalThis;
5500
5564
  if (!hadShim)
5501
5565
  globalThis.defineAppConfig = (config2) => config2;
5502
- 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(() => ({}));
5503
5567
  if (!hadShim)
5504
5568
  delete globalThis.defineAppConfig;
5505
5569
  if (cfg?.ui?.colors)
@@ -5514,8 +5578,10 @@ Or pin to a specific version in package.json:
5514
5578
  cssProvider$1 = createTw4Provider({
5515
5579
  async resolveCssPath() {
5516
5580
  const aliasPath = nuxt.options.alias["#tailwindcss"];
5517
- if (aliasPath && existsSync(aliasPath))
5581
+ if (aliasPath && existsSync(aliasPath)) {
5582
+ cssDependencies.add(aliasPath);
5518
5583
  return aliasPath;
5584
+ }
5519
5585
  for (const cssEntry of nuxt.options.css) {
5520
5586
  const cssPath = typeof cssEntry === "string" ? cssEntry : cssEntry?.src;
5521
5587
  if (!cssPath || !cssPath.endsWith(".css"))
@@ -5526,8 +5592,10 @@ Or pin to a specific version in package.json:
5526
5592
  if (!resolved || !existsSync(resolved))
5527
5593
  continue;
5528
5594
  const content = await readFile(resolved, "utf-8");
5529
- if (content.includes('@import "tailwindcss"') || content.includes("@import 'tailwindcss'"))
5595
+ if (content.includes('@import "tailwindcss"') || content.includes("@import 'tailwindcss'")) {
5596
+ cssDependencies.add(resolved);
5530
5597
  return resolved;
5598
+ }
5531
5599
  }
5532
5600
  },
5533
5601
  loadNuxtUiColors
@@ -5540,6 +5608,7 @@ Or pin to a specific version in package.json:
5540
5608
  if (!_cssDirty && !_cssConfigDirty)
5541
5609
  return;
5542
5610
  cssProvider$1?.clearCache?.();
5611
+ cachedNuxtUiColors = void 0;
5543
5612
  cssMetadataPromise = void 0;
5544
5613
  Object.assign(cssMetadata, { fontVars: {}, breakpoints: {}, colors: {} });
5545
5614
  _cssConfigDirty = false;
@@ -5585,6 +5654,10 @@ Or pin to a specific version in package.json:
5585
5654
  srcDir: nuxt.options.srcDir,
5586
5655
  publicDir: isAbsolute(nuxt.options.dir.public) ? nuxt.options.dir.public : join(nuxt.options.srcDir, nuxt.options.dir.public || "public"),
5587
5656
  cssProvider: cssProvider$1,
5657
+ cssDependencies: () => [...cssDependencies],
5658
+ onCssDependencyChange: () => {
5659
+ _cssDirty = true;
5660
+ },
5588
5661
  beforeCssResolve: flushCssDirtyState,
5589
5662
  onNestedTransform: (filePath) => ogImageTransformedFiles.add(filePath),
5590
5663
  onFontRequirements(id, reqs) {
@@ -5761,6 +5834,11 @@ ${familyInfo}`);
5761
5834
  route: "/_og/r/**",
5762
5835
  handler: resolve("./runtime/server/routes/resolve")
5763
5836
  });
5837
+ addServerHandler({
5838
+ lazy: true,
5839
+ route: "/_og/r.png",
5840
+ handler: resolve("./runtime/server/routes/resolve")
5841
+ });
5764
5842
  if (!nuxt.options.dev) {
5765
5843
  nuxt.options.routeRules = nuxt.options.routeRules || {};
5766
5844
  const ttl = config.cacheMaxAgeSeconds ?? config.defaults?.cacheMaxAgeSeconds ?? 60 * 60 * 24 * 3;
@@ -5773,12 +5851,14 @@ ${familyInfo}`);
5773
5851
  { headers: { "cache-control": dynamicCacheControl } }
5774
5852
  );
5775
5853
  }
5776
- const ogResolveRule = nuxt.options.routeRules["/_og/r/**"];
5777
- if (!ogResolveRule?.swr && !ogResolveRule?.isr && !ogResolveRule?.cache && !ogResolveRule?.headers) {
5778
- nuxt.options.routeRules["/_og/r/**"] = defu(
5779
- nuxt.options.routeRules["/_og/r/**"] || {},
5780
- { headers: { "cache-control": dynamicCacheControl } }
5781
- );
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
+ }
5782
5862
  }
5783
5863
  }
5784
5864
  const ogStaticRule = nuxt.options.routeRules["/_og/s/**"];
@@ -6048,10 +6128,20 @@ Run: npx nuxt-og-image migrate v6`;
6048
6128
  addTemplate({
6049
6129
  filename: "nuxt-og-image/components.mjs",
6050
6130
  getContents() {
6051
- return `export const componentNames = ${JSON.stringify(ogImageComponentCtx.components)}`;
6131
+ return `export const componentNames = ${JSON.stringify(getAppComponents(ogImageComponentCtx.components))}`;
6052
6132
  },
6053
6133
  options: { mode: "server" }
6054
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
+ });
6055
6145
  addTemplate({
6056
6146
  filename: "nuxt-og-image/client-config.mjs",
6057
6147
  getContents() {
@@ -6061,7 +6151,8 @@ Run: npx nuxt-og-image migrate v6`;
6061
6151
  });
6062
6152
  nuxt.options.nitro.virtual = nuxt.options.nitro.virtual || {};
6063
6153
  nuxt.options.nitro.virtual["#og-image-virtual/component-names.mjs"] = () => {
6064
- 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)}`;
6065
6156
  };
6066
6157
  nuxt.options.nitro.virtual["#og-image/island-hash"] = () => {
6067
6158
  const islandHashFile = join(nuxt.options.appDir, "island-hash.js");
@@ -6082,26 +6173,13 @@ Run: npx nuxt-og-image migrate v6`;
6082
6173
  fallthrough: nuxt.options.dev,
6083
6174
  maxAge: 60 * 60 * 24 * 365
6084
6175
  });
6085
- nuxt.options.nitro.virtual["#og-image-virtual/public-assets.mjs"] = async () => {
6176
+ function getFontAssetsModule(readsFilesystem) {
6086
6177
  const normalizedPreset2 = preset.replace(RE_LEGACY_SUFFIX, "");
6087
6178
  const isCloudflare = normalizedPreset2 === "cloudflare" || normalizedPreset2.startsWith("cloudflare-");
6088
- if (isCloudflare) {
6089
- const devBinding2 = resolver.resolve("./runtime/server/og-image/bindings/font-assets/dev-prerender");
6090
- const cfBinding = resolver.resolve("./runtime/server/og-image/bindings/font-assets/cloudflare");
6091
- return `
6092
- import { resolve as devResolve } from '${devBinding2}'
6093
- import { resolve as cfResolve } from '${cfBinding}'
6094
- export const resolve = (import.meta.dev || import.meta.prerender) ? devResolve : cfResolve
6095
- `;
6096
- }
6097
- const devBinding = resolver.resolve("./runtime/server/og-image/bindings/font-assets/dev-prerender");
6098
- const nodeBinding = resolver.resolve("./runtime/server/og-image/bindings/font-assets/node");
6099
- return `
6100
- import { resolve as devResolve } from '${devBinding}'
6101
- import { resolve as nodeResolve } from '${nodeBinding}'
6102
- export const resolve = (import.meta.dev || import.meta.prerender) ? devResolve : nodeResolve
6103
- `;
6104
- };
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);
6105
6183
  const hasSatoriRenderer = () => ogImageComponentCtx.detectedRenderers.has("satori");
6106
6184
  const hasTakumiRenderer = () => ogImageComponentCtx.detectedRenderers.has("takumi");
6107
6185
  const nuxtFontFiles = /* @__PURE__ */ new Map();
@@ -6111,25 +6189,57 @@ export const resolve = (import.meta.dev || import.meta.prerender) ? devResolve :
6111
6189
  const currentFontKey = () => JSON.stringify([
6112
6190
  getResolvedFontStateKey(fontState),
6113
6191
  fontRequirementsState.weights,
6114
- fontRequirementsState.styles
6192
+ fontRequirementsState.styles,
6193
+ fontRequirementsState.families,
6194
+ fontRequirementsState.hasDynamicBindings
6115
6195
  ]);
6116
- 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
+ }
6117
6220
  function refreshDevFonts() {
6118
- if (!reloadNitro || builtFontKey === void 0 || builtFontKey === currentFontKey())
6221
+ if (!nuxt.options.dev || !hasNuxtFonts || builtFontKey === void 0 || (publishedFontKey ?? builtFontKey) === currentFontKey())
6119
6222
  return;
6120
- reloadNitro().catch((error) => {
6121
- logger.warn(`Could not rebuild the OG image font list: ${error.message}`);
6223
+ if (devFontStateWrite) {
6224
+ devFontStateStale = true;
6225
+ return;
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
+ }
6122
6236
  });
6123
6237
  }
6124
- if (nuxt.options.dev) {
6125
- nuxt.hook("nitro:init", (nitro) => {
6126
- let pending;
6127
- reloadNitro = () => pending ||= Promise.resolve().then(async () => {
6128
- pending = void 0;
6129
- fontProcessingDone = false;
6130
- await nitro.hooks.callHook("rollup:reload");
6131
- });
6132
- });
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 }`;
6133
6243
  }
6134
6244
  async function resolveFontList() {
6135
6245
  builtFontKey = currentFontKey();
@@ -6168,21 +6278,39 @@ export const resolve = (import.meta.dev || import.meta.prerender) ? devResolve :
6168
6278
  builtFontList = { key, fonts: resolveFontList() };
6169
6279
  return builtFontList.fonts;
6170
6280
  }
6171
- 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
+ });
6172
6303
  nuxt.options.nitro.virtual["#og-image/fonts-available"] = async () => {
6173
- const fonts = hasNuxtFonts ? await getResolvedNuxtFonts(nuxt, { fontState, requiredWeights: fontRequirementsState.weights }) : [];
6174
- return `export default ${JSON.stringify(fonts)}`;
6304
+ return `const _value = ${JSON.stringify(await getAvailableFontList())}
6305
+ export default _value
6306
+ ${fontStateGetter("getAvailableFonts", "available")}`;
6175
6307
  };
6176
6308
  nuxt.options.nitro.virtual["#og-image/font-requirements"] = async () => {
6177
6309
  if (pendingFontRequirements.length > 0)
6178
6310
  await Promise.all(pendingFontRequirements);
6179
- const baseExports = `export const fontRequirements = ${JSON.stringify({
6180
- weights: fontRequirementsState.weights,
6181
- styles: fontRequirementsState.styles,
6182
- families: fontRequirementsState.families,
6183
- // Unanalysed components (webpack, rspack) may use any font, like dynamic bindings
6184
- hasDynamicBindings: fontRequirementsState.hasDynamicBindings || !fontRequirementsState.scanned
6185
- })}
6311
+ const baseExports = `const _value = ${JSON.stringify(globalFontRequirements())}
6312
+ export const fontRequirements = _value
6313
+ ${fontStateGetter("getFontRequirements", "requirements")}
6186
6314
  export const hasNuxtFonts = ${JSON.stringify(hasNuxtFonts)}`;
6187
6315
  if (nuxt.options.dev) {
6188
6316
  const mapPath = join(nuxt.options.buildDir, "cache", "og-image", "component-font-map.json");
@@ -6205,10 +6333,12 @@ export const tw4Breakpoints = ${JSON.stringify(cssMetadata.breakpoints)}
6205
6333
  export const tw4Colors = ${JSON.stringify(cssMetadata.colors)}`;
6206
6334
  };
6207
6335
  nuxt.options.nitro.virtual["#og-image-virtual/build-dir.mjs"] = async () => {
6208
- const resolvedFontPaths = await cacheResolvedFontFiles(nuxtFontFiles, join(nuxt.options.buildDir, "cache", "og-image", "resolved-fonts"));
6336
+ const resolvedFontPaths = await getResolvedFontPaths();
6209
6337
  return `export const buildDir = ${JSON.stringify(nuxt.options.buildDir)}
6210
6338
  export const rootDir = ${JSON.stringify(nuxt.options.rootDir)}
6211
- export const resolvedFontPaths = ${JSON.stringify(resolvedFontPaths)}
6339
+ const _value = ${JSON.stringify(resolvedFontPaths)}
6340
+ export const resolvedFontPaths = _value
6341
+ ${fontStateGetter("getResolvedFontPaths", "resolvedFontPaths")}
6212
6342
  export const staticFontCacheDir = ${JSON.stringify(getStaticFontCacheDir(nuxt.options.buildDir))}`;
6213
6343
  };
6214
6344
  if (hasNuxtFonts) {
@@ -6280,10 +6410,6 @@ export const staticFontCacheDir = ${JSON.stringify(getStaticFontCacheDir(nuxt.op
6280
6410
  baseCacheKey = `/${config.runtimeCacheStorage}/nuxt-og-image${versionSuffix}`;
6281
6411
  } else if (typeof config.runtimeCacheStorage === "object") {
6282
6412
  baseCacheKey = `/nuxt-og-image${versionSuffix}`;
6283
- if (!nuxt.options.dev) {
6284
- nuxt.options.nitro.storage = nuxt.options.nitro.storage || {};
6285
- nuxt.options.nitro.storage["nuxt-og-image"] = config.runtimeCacheStorage;
6286
- }
6287
6413
  } else {
6288
6414
  baseCacheKey = false;
6289
6415
  }
@@ -6291,7 +6417,7 @@ export const staticFontCacheDir = ${JSON.stringify(getStaticFontCacheDir(nuxt.op
6291
6417
  baseCacheKey = false;
6292
6418
  let hasUnboundedRuntimeCache = false;
6293
6419
  nuxt.hooks.hook("nitro:config", async (nitroConfig) => {
6294
- const storage = configureRuntimeCacheStorage(config, nitroConfig);
6420
+ const storage = configureRuntimeCacheStorage(config, nitroConfig, nitroCompatibility._tag === "nitro-v3" ? 3 : 2);
6295
6421
  await resolveRuntimeCacheDriver(storage, nitroConfig, nuxt.options.rootDir);
6296
6422
  hasUnboundedRuntimeCache = storage?.driver === "memory";
6297
6423
  });