nuxt-og-image
Version:
Enlightened OG Image generation for Nuxt.
56 lines (55 loc) • 2.19 kB
JavaScript
import { appendHeader } from "h3";
import { createError, useNuxtApp, useRequestEvent, useRoute, useState } from "nuxt/app";
import { ref, toValue } from "vue";
import { createNitroRouteRuleMatcher } from "../../server/util/kit.js";
import { getOgImagePath, useOgImageRuntimeConfig } from "../../shared.js";
import { createOgImageMeta, setHeadOgImagePrebuilt } from "../utils.js";
export function defineOgImage(_options = {}) {
const nuxtApp = useNuxtApp();
const route = useRoute();
const basePath = route.path || "/";
if (nuxtApp.payload.path === basePath) {
const state = import.meta.dev ? useState(`og-image:ssr-exists:${basePath}`, () => false) : ref(false);
if (import.meta.dev && !import.meta.server) {
if (!state.value) {
throw createError({ message: "You are using a defineOgImage() function in a client-only context. You must call this function within your root component setup, see https://github.com/nuxt-modules/og-image/pull/293." });
}
return;
}
state.value = true;
}
if (!import.meta.server) {
return;
}
const ogImageInstances = nuxtApp.ssrContext._ogImageInstances || [];
const routeRuleMatcher = createNitroRouteRuleMatcher();
const routeRules = routeRuleMatcher(basePath).ogImage;
if (!_options || nuxtApp.ssrContext?.event.context._nitro?.routeRules?.ogImage === false || typeof routeRules !== "undefined" && routeRules === false) {
ogImageInstances.forEach((e) => {
e.dispose();
});
nuxtApp.ssrContext._ogImageInstances = void 0;
return;
}
const { defaults } = useOgImageRuntimeConfig();
const options = toValue(_options);
for (const key in routeRules) {
if (options[key] === void 0)
options[key] = routeRules[key];
}
for (const key in defaults) {
if (options[key] === void 0)
options[key] = defaults[key];
}
if (route.query)
options._query = route.query;
if (options.url) {
setHeadOgImagePrebuilt(options);
return;
}
const path = getOgImagePath(basePath, options);
if (import.meta.prerender) {
appendHeader(useRequestEvent(nuxtApp), "x-nitro-prerender", path);
}
createOgImageMeta(path, options, nuxtApp.ssrContext);
}