Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support resolve hook #146

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 24 additions & 10 deletions src/es-module-shims.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@ async function importShim (id, parentUrl = pageBaseUrl, _assertion) {
await featureDetectionPromise;
// Make sure all the "in-flight" import maps are loaded and applied.
await importMapPromise;
return topLevelLoad(resolve(id, parentUrl).r || throwUnresolved(id, parentUrl), { credentials: 'same-origin' });
const resolved = await resolve(id, parentUrl);
return topLevelLoad(resolved.r || throwUnresolved(id, parentUrl), { credentials: 'same-origin' });
}

self.importShim = importShim;
Expand All @@ -102,7 +103,8 @@ const edge = navigator.userAgent.match(/Edge\/\d\d\.\d+$/);

async function importMetaResolve (id, parentUrl = this.url) {
await importMapPromise;
return resolve(id, `${parentUrl}`).r || throwUnresolved(id, parentUrl);
const resolved = await resolve(id, `${parentUrl}`);
return resolved.r || throwUnresolved(id, parentUrl);
}

self._esmsm = meta;
Expand Down Expand Up @@ -142,7 +144,7 @@ function resolveDeps (load, seen) {
const source = load.S;

// edge doesnt execute sibling in order, so we fix this up by ensuring all previous executions are explicit dependencies
let resolvedSource = edge && lastLoad ? `import '${lastLoad}';` : '';
let resolvedSource = edge && lastLoad ? `import '${lastLoad}';` : '';

if (!imports.length) {
resolvedSource += source;
Expand Down Expand Up @@ -279,13 +281,13 @@ function getOrCreateLoad (url, fetchOpts, source) {

load.L = load.f.then(async () => {
let childFetchOpts = fetchOpts;
load.d = await Promise.all(load.a[0].map(({ n, d, a }) => {
load.d = (await Promise.all(load.a[0].map(async ({ n, d, a }) => {
if (d >= 0 && !supportsDynamicImport ||
d === 2 && (!supportsImportMeta || source.slice(end, end + 8) === '.resolve') ||
a && !supportsJsonAssertions)
load.n = true;
if (!n) return;
const { r, m } = resolve(n, load.r || load.u);
const { r, m } = await resolve(n, load.r || load.u);
if (m && (!supportsImportMaps || importMapSrcOrLazy))
load.n = true;
if (d !== -1) return;
Expand All @@ -295,7 +297,7 @@ function getOrCreateLoad (url, fetchOpts, source) {
if (childFetchOpts.integrity)
childFetchOpts = Object.assign({}, childFetchOpts, { integrity: undefined });
return getOrCreateLoad(r, childFetchOpts).f;
}).filter(l => l));
}))).filter(l => l);
});

return load;
Expand Down Expand Up @@ -386,14 +388,26 @@ function processPreload (link) {
link.ep = true;
// prepopulate the load record
const fetchOpts = getFetchOpts(link);
// save preloaded fetch options for later load
// save preloaded fetch options for later load
fetchOptsMap.set(link.href, fetchOpts);
fetch(link.href, fetchOpts);
}

function resolve (id, parentUrl) {
const urlResolved = resolveIfNotPlainOrUrl(id, parentUrl);
const resolved = resolveImportMap(importMap, urlResolved || id, parentUrl);
function defaultResolve(id, parentUrl) {
return resolveImportMap(importMap, resolveIfNotPlainOrUrl(id, parentUrl) || id, parentUrl);
}

async function resolve(id, parentUrl) {
let urlResolved = resolveIfNotPlainOrUrl(id, parentUrl);

let resolved;
if (esmsInitOptions.resolve) {
resolved = await esmsInitOptions.resolve(id, parentUrl, defaultResolve);
}
else {
resolved = resolveImportMap(importMap, urlResolved || id, parentUrl);
}

return { r: resolved, m: urlResolved !== resolved };
guybedford marked this conversation as resolved.
Show resolved Hide resolved
}

Expand Down
18 changes: 18 additions & 0 deletions test/resolve-hook.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@

suite('Resolve hook', () => {
test('Should hook resolve', async function () {
globalThis.esmsInitOptions = {
resolve: async function (id, parentUrl, defaultResolve) {
if (id === 'resolveTestModule') {
return defaultResolve('./fixtures/es-modules/es6.js', parentUrl);
// OR just resolve by yourself like this:
// return new URL('./fixtures/es-modules/es6.js', location.href).href;
}
}
};

await import('../src/es-module-shims.js');
var m = await importShim('resolveTestModule');
assert(m.p);
});
});
48 changes: 48 additions & 0 deletions test/test-resolve-hook.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<!doctype html>
<link rel="stylesheet" type="text/css" href="../node_modules/mocha/mocha.css"/>
<script src="../node_modules/mocha/mocha.js"></script>
<script type="importmap-shim">
{
"imports": {
"test": "/test/fixtures/es-modules/es6-file.js"
}
}
</script>
<script type="module-shim">
import test from "test";
console.log(test);
</script>
<script type="module">
mocha.setup('tdd');
mocha.allowUncaught();

self.baseURL = location.href.substr(0, location.href.lastIndexOf('/') + 1);
self.rootURL = location.href.substr(0, location.href.length - 'test/test.html'.length);
self.assert = function (val) {
equal(!!val, true);
};
assert.equal = equal;
assert.ok = assert;
function equal (a, b) {
if (a !== b)
throw new Error('Expected "' + a + '" to be "' + b + '"');
}
self.fail = function (msg) {
throw new Error(msg);
};

const suites = ['resolve-hook'];
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than having a separate test-resolve-hook, can we just add this to the main suite in test/test.html? That will ensure it's captured by CI.

function runNextSuite () {
mocha.suite.suites = [];
const suite = suites.shift();
if (suite)
import('./' + suite + '.js')
.then(function () {
mocha.run(runNextSuite);
});
}

runNextSuite();
</script>

<div id="mocha"></div>