Skip to content

Instantly share code, notes, and snippets.

@caridy
Forked from dherman/a.js
Last active February 3, 2017 23:28
Show Gist options
  • Save caridy/c906097b44acb6c24e104d3ad19c22f4 to your computer and use it in GitHub Desktop.
Save caridy/c906097b44acb6c24e104d3ad19c22f4 to your computer and use it in GitHub Desktop.
a tiny userland registry, using a "parse" and "link" primitive
import {b} from "./b.js";
import $ from "jquery";
export function a() {
// ...
}
import {a} from "./a.js";
import $ from "jquery";
export function b() {
// ...
}
class TinyLittleRegistry {
constructor(realm, jquery) {
this.#realm = realm;
this.#jquery = jquery;
this.links = {
"a": {
"./b.js": "b",
},
"b": {
"./a.js": a
},
};
}
@lazy records() {
return Promise.all([fetch("a.js"), fetch("b.js")])
.then(sources => sources.map(s => this.#realm.parseModule(s)));
}
@lazy async graph() {
const { a, b } = await this.records();
const { jquery } = this;
return { a, b, jquery };
}
getDependencyOf(referrer, specifier) {
const modules = await this.#registry.graph();
const name = Object.keys(modules).findIndex(name => modules[name] === referrer);
if (!name) {
// must be a top level
return module[specifier];
}
const depName = this.link[name][specifier];
return depName ? modules[depName] : Promise.resolve(new ReferenceError(`unrecognized module: ${depName} from referrer ${name}`));
}
getTopLevelModule(name) {
return this.#registry.graph().then(graph => graph[name]);
}
}
import * as jquery from "jquery";
class TinyLittleRealm extends Realm {
constructor() {
super();
this.#registry = new TinyLittleRegistry(this, jquery);
}
[Realm.import](name, referrer) {
if (!referrer) {
return this.#registry.getTopLevelModule(name);
}
return this.#registry.getDependencyOf(referrer, name)
}
}
let realm = new TinyLittleRealm();
realm.eval("import('a')").then(m => m.a());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment