import Debug from "./debug" ; import { importPath } from "@kosko/require" ; const debug = Debug . extend ( "module" ) ; export interface ResourceModule { readonly path : string ; readonly export : string ; } export interface ResourceKind { readonly apiVersion : string ; readonly kind : string ; } let moduleMap = { } ; function getGroup ( apiVersion ) { const arr = apiVersion . split ( "/" ) ; return arr . length === 1 ? "" : arr [ 0 ] ; } export function setResourceModule ( res , mod ) { const { apiVersion , kind } = res ; if ( ! moduleMap [ apiVersion ] ) { moduleMap [ apiVersion ] = { } ; } moduleMap [ apiVersion ] [ kind ] = mod ; debug ( "Set resource module" , res , mod ) ; } async function getKubernetesModels ( res ) { const { apiVersion , kind } = res ; const group = getGroup ( apiVersion ) ; if ( group && group . includes ( "." ) && ! group . endsWith ( ".k8s.io" ) ) { return ; } try { const path = `kubernetes-models/${ apiVersion }/${ kind }` ; const mod = await importPath ( path ) ; const ctor = mod [ kind ] ; if ( ctor ) { const mod = { path , export : kind } ; setResourceModule ( res , mod ) ; return mod ; } } catch { return ; } } export async function getResourceModule ( res ) { return ( moduleMap [ res . apiVersion ] ?. [ res . kind ] ?? ( await getKubernetesModels ( res ) ) ) ; } export function resetResourceModules ( ) { moduleMap = { } ; debug ( "Reset resource modules" ) ; }