Skip to content

Commit

Permalink
feat: add .mapping(dep) shorthand method to resolve mapped bare impor…
Browse files Browse the repository at this point in the history
…ts directly
  • Loading branch information
digitalsadhu committed Sep 20, 2022
1 parent cfd5178 commit a557cfd
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 10 deletions.
31 changes: 21 additions & 10 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-restricted-syntax */
import { request } from 'undici';
import { join } from 'path';
import loader from '@eik/common-config-loader';
Expand All @@ -6,16 +7,15 @@ import Asset from './asset.js';
const trimSlash = (value = '') => {
if (value.endsWith('/')) return value.substring(0, value.length - 1);
return value;
}
};

const fetchImportMaps = async (urls = []) => {
try{
try {
const maps = urls.map(async (map) => {
const {
statusCode,
body
} = await request(map, { maxRedirections: 2 });

const { statusCode, body } = await request(map, {
maxRedirections: 2,
});

if (statusCode === 404) {
throw new Error('Import map could not be found on server');
} else if (statusCode >= 400 && statusCode < 500) {
Expand All @@ -31,7 +31,7 @@ const fetchImportMaps = async (urls = []) => {
`Unable to load import map file from server: ${err.message}`,
);
}
}
};

export default class NodeClient {
#development;
Expand Down Expand Up @@ -83,7 +83,8 @@ export default class NodeClient {
}

get pathname() {
if (this.#config.type && this.#config.name && this.#config.version) return join('/', this.type, this.name, this.version);
if (this.#config.type && this.#config.name && this.#config.version)
return join('/', this.type, this.name, this.version);
throw new Error('Eik config was not loaded before calling .pathname');
}

Expand All @@ -101,6 +102,16 @@ export default class NodeClient {

maps() {
if (this.#config.version && this.#loadMaps) return this.#maps;
throw new Error('Eik config was not loaded or "loadMaps" is "false" when calling .maps()');
throw new Error(
'Eik config was not loaded or "loadMaps" is "false" when calling .maps()',
);
}

mapping(dependency) {
let mapping = null;
for (const map of this.maps()) {
if (map?.imports[dependency]) mapping = map.imports[dependency];
}
return mapping;
}
}
13 changes: 13 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -255,3 +255,16 @@ tap.test('Client - Retrieve a base - Development mode is set to "false"', async
t.equal(resolved, `${t.context.address}/pkg/eik-fixture/1.0.2`);
t.end();
});

tap.test('Client - Resolve a mapping', async (t) => {
const client = new NodeClient({
path: t.context.fixture,
loadMaps: true,
});
await client.load();

const mapping = client.mapping('eik');

t.equal(mapping, '/src/eik.js');
t.end();
});

0 comments on commit a557cfd

Please sign in to comment.