import { invokeHelper , getValue } from '../environment' ; import type { Resource } from './resource' ; import type { TemplateArgs , Cache } from './types' ; type Args = TemplateArgs | TemplateArgs [ 'positional' ] | TemplateArgs [ 'named' ] ; function normalizeArgs ( args ) { if ( Array . isArray ( args ) ) { return { positional : args , named : { } } ; } if ( 'positional' in args || 'named' in args ) { return { positional : ( args . positional as TemplateArgs [ 'positional' ] ) || [ ] , named : ( args . named as TemplateArgs [ 'named' ] ) || { } } ; } if ( typeof args === 'object' ) { return { named : args as TemplateArgs [ 'named' ] , positional : [ ] } ; } return args ; } export function useUnproxiedResource < TArgs = Args , T extends Resource < TemplateArgs > = Resource < TemplateArgs > > ( destroyable , definition , args ? ) { let resource ; return { get value ( ) : T { if ( ! resource ) { resource = invokeHelper ( destroyable , definition , ( ) => { return normalizeArgs ( args ?. ( ) || { } ) ; } ) as Cache < T > ; } return getValue < T > ( resource ) ! ; } } ; } export function useResource < TArgs = Args , T extends Resource < TemplateArgs > = Resource < TemplateArgs > > ( destroyable , definition , args ? ) { const target = useUnproxiedResource < TArgs , T > ( destroyable , definition , args ) ; return new Proxy ( target , { get ( target , key ) { const instance = target . value ; const value = Reflect . get ( instance , key , instance ) ; return typeof value === 'function' ? value . bind ( instance ) : value ; } , ownKeys ( target ) { return Reflect . ownKeys ( target . value ) ; } , getOwnPropertyDescriptor ( target , key ) { return Reflect . getOwnPropertyDescriptor ( target . value , key ) ; } } ) as never as T ; }