|
| 1 | +import type { Nuxt } from '@nuxt/schema' |
| 2 | +import type { HubConfig, ResolvedBlobConfig } from '@nuxthub/core' |
| 3 | +import { resolvePath } from '@nuxt/kit' |
| 4 | +import { defu } from 'defu' |
| 5 | +import { resolve, logWhenReady } from '../utils' |
| 6 | + |
| 7 | +export async function setupImage(nuxt: Nuxt, hub: HubConfig, deps: Record<string, string>) { |
| 8 | + if (!hub.blob) return |
| 9 | + |
| 10 | + const blobConfig = hub.blob as ResolvedBlobConfig |
| 11 | + const imagePath = blobConfig.image?.path |
| 12 | + if (!imagePath) return |
| 13 | + |
| 14 | + const imageVersion = deps['@nuxt/image'] |
| 15 | + if (!imageVersion) { |
| 16 | + logWhenReady(nuxt, 'Install @nuxt/image v2+ to enable NuxtHub image optimization', 'warn') |
| 17 | + return |
| 18 | + } |
| 19 | + |
| 20 | + // Check if @nuxt/image v2+ by trying to resolve runtime path (v1 doesn't export it) |
| 21 | + try { |
| 22 | + await resolvePath('@nuxt/image/runtime') |
| 23 | + } catch { |
| 24 | + logWhenReady(nuxt, '@nuxt/image v2+ is required for NuxtHub integration. Please upgrade to @nuxt/image@^2.0.0', 'warn') |
| 25 | + return |
| 26 | + } |
| 27 | + |
| 28 | + const normalizedPath = (imagePath.startsWith('/') ? imagePath : `/${imagePath}`) |
| 29 | + .replace(/\/+$/, '') || '/' |
| 30 | + |
| 31 | + // Register nuxthub provider for @nuxt/image |
| 32 | + // @ts-expect-error image options from @nuxt/image |
| 33 | + nuxt.options.image ||= {} |
| 34 | + // @ts-expect-error image options from @nuxt/image |
| 35 | + nuxt.options.image.providers ||= {} |
| 36 | + |
| 37 | + // Respect any existing user config while ensuring required defaults. |
| 38 | + // @ts-expect-error image options from @nuxt/image |
| 39 | + const existingProvider = nuxt.options.image.providers.nuxthub as any | undefined |
| 40 | + const providerPath = resolve('image/runtime/provider') |
| 41 | + |
| 42 | + // If user configured a different provider under the "nuxthub" key, respect it. |
| 43 | + const isCustomProvider = existingProvider?.provider && existingProvider.provider !== providerPath |
| 44 | + if (!isCustomProvider) { |
| 45 | + // @ts-expect-error image options from @nuxt/image |
| 46 | + nuxt.options.image.providers.nuxthub = defu(existingProvider || {}, { |
| 47 | + provider: providerPath, |
| 48 | + options: { driver: blobConfig.driver, path: normalizedPath } |
| 49 | + }) |
| 50 | + } |
| 51 | + |
| 52 | + // Set as default provider if not already set |
| 53 | + // @ts-expect-error image options from @nuxt/image |
| 54 | + if (!nuxt.options.image.provider || nuxt.options.image.provider === 'auto') { |
| 55 | + // @ts-expect-error image options from @nuxt/image |
| 56 | + nuxt.options.image.provider = 'nuxthub' |
| 57 | + } |
| 58 | + |
| 59 | + logWhenReady(nuxt, `\`@nuxt/image\` nuxthub provider registered (${blobConfig.driver})`) |
| 60 | +} |
0 commit comments