|
| 1 | +import type { NuxtConfigLayer } from "@nuxt/schema"; |
| 2 | +import { defu } from "defu"; |
| 3 | + |
| 4 | +type GetModuleOptions< |
| 5 | + T, |
| 6 | + K extends keyof NuxtConfigLayer["config"], |
| 7 | +> = [T] extends [never] ? NuxtConfigLayer["config"][K] : T; |
| 8 | + |
| 9 | +/** |
| 10 | + * Get module options from a given Nuxt layer |
| 11 | + * |
| 12 | + * This takes into account both inline module options specified in the `modules` array |
| 13 | + * and options specified in the layer's config under a specific key. |
| 14 | + * |
| 15 | + * Returns the merged options if both are provided, or the first available option. |
| 16 | + * |
| 17 | + * @param layer - a {@link NuxtConfigLayer | Nuxt Layer} from `nuxt.options._layers` |
| 18 | + * @param configKey - the key used to configure module options in nuxt.config |
| 19 | + * @param name - the module name as it would be specified in the `modules` array |
| 20 | + * @returns |
| 21 | + */ |
| 22 | +export function getLayerModuleOptions< |
| 23 | + T = never, |
| 24 | + K extends keyof NuxtConfigLayer["config"] = keyof NuxtConfigLayer["config"], |
| 25 | +>( |
| 26 | + layer: NuxtConfigLayer, |
| 27 | + configKey: K, |
| 28 | + name: string, |
| 29 | +): GetModuleOptions<T, K> | undefined { |
| 30 | + type Options = GetModuleOptions<T, K>; |
| 31 | + |
| 32 | + const matchInlineOptions = (mod: any): mod is [string, Options] => |
| 33 | + Array.isArray(mod) && typeof mod[0] === "string" && mod[0] === name; |
| 34 | + |
| 35 | + const modules = (layer.config.modules || []) as [ |
| 36 | + string, |
| 37 | + unknown | undefined, |
| 38 | + ][]; |
| 39 | + const inlineOptions = modules.find(matchInlineOptions)?.[1]; |
| 40 | + const keyOptions = layer.config[configKey] as Options | undefined; |
| 41 | + |
| 42 | + if (inlineOptions == null && keyOptions == null) { |
| 43 | + return undefined; |
| 44 | + } |
| 45 | + |
| 46 | + return defu(keyOptions || {}, inlineOptions || {}) as Options; |
| 47 | +} |
0 commit comments