diff --git a/packages/entity/trait/registrar.js b/packages/entity/trait/registrar.js index 40128be..685f472 100644 --- a/packages/entity/trait/registrar.js +++ b/packages/entity/trait/registrar.js @@ -1,16 +1,20 @@ const {all, idFrom: idFromRaw} = require('./traits.scwp'); +const {registerHooks} = require('scwp'); let hasMapped = false; const traitTo = new Map(); const typeTo = new Map(); -function mapTypesToTraits() { - const entries = Object.entries(all()); - for (let i = 0; i < entries.length; i++) { - const [, M] = entries[i]; - const {default: Trait} = M; - typeTo.set(Trait.type(), Trait); - traitTo.set(Trait, M); +function ensureTypeMap() { + if (!hasMapped) { + const entries = Object.entries(all()); + for (let i = 0; i < entries.length; i++) { + const [, M] = entries[i]; + const {default: Trait} = M; + typeTo.set(Trait.type(), Trait); + traitTo.set(Trait, M); + } + hasMapped = true; } } @@ -19,19 +23,21 @@ export function idFrom(Trait) { } export function hasTrait(type) { - if (!hasMapped) { - mapTypesToTraits(); - hasMapped = true; - } + ensureTypeMap(); return typeTo.has(type); } export function lookupTrait(type) { - if (!hasMapped) { - mapTypesToTraits(); - hasMapped = true; - } + ensureTypeMap(); return typeTo.get(type); } +registerHooks({ + autoreg$accept: (type, M) => { + const {default: Trait} = M; + typeTo.set(Trait.type(), Trait); + traitTo.set(Trait, M); + }, +}, '@avocado/entity/trait/registrar'); + module.hot?.accept(['./traits.scwp'], () => hasMapped = false);