UNPKG

@bitblit/ratchet-common

Version:

Common tools for general use

65 lines 2.55 kB
import url from 'url'; import { ErrorRatchet } from './error-ratchet.js'; import { Logger } from '../logger/logger.js'; import { StringRatchet } from './string-ratchet.js'; export class EsmRatchet { static DYNAMIC_IMPORT_CACHE = new Map(); static fetchDirName(root) { if (!root) { throw new Error('Need to provide root (should be import.meta.url)'); } const rval = url.fileURLToPath(new URL('.', root)); return rval; } static fetchFileName(root) { if (!root) { throw new Error('Need to provide root (should be import.meta.url)'); } const rval = url.fileURLToPath(root); return rval; } static async cachedTypedDynamicImport(libPath, importName, requiredKeys, swallowErrorIfMissing) { const cacheKey = StringRatchet.trimToNull(importName) ? libPath + '__' + importName : libPath; let rval = EsmRatchet.DYNAMIC_IMPORT_CACHE.get(cacheKey); if (!rval) { rval = EsmRatchet.typedDynamicImport(libPath, importName, requiredKeys, swallowErrorIfMissing); if (rval) { EsmRatchet.DYNAMIC_IMPORT_CACHE.set(cacheKey, rval); } } return rval; } static async typedDynamicImport(libPath, importName, requiredKeys, swallowErrorIfMissing) { let rval; try { rval = await import(__rewriteRelativeImportExtension(libPath)); } catch (err) { if (swallowErrorIfMissing) { Logger.debug('Cannot find library %s but swallow specified, returning null', libPath); rval = null; } else { throw ErrorRatchet.fErr('Could not find the "%s" library : %s', libPath, err); } } if (StringRatchet.trimToNull(importName)) { if (rval[importName]) { rval = rval[importName]; } else { throw ErrorRatchet.fErr('Imported library %s, tried to load name %s but only found %j', libPath, importName, Object.keys(rval)); } } if (requiredKeys?.length && rval) { const keys = Object.keys(rval); requiredKeys.forEach((k) => { if (!keys.includes(k)) { throw ErrorRatchet.fErr('Failed to import "%s" - required keys are %j, but found %j', libPath, requiredKeys, keys); } }); } return rval; } } //# sourceMappingURL=esm-ratchet.js.map