Skip to content

Commit

Permalink
feat(endo): Add import
Browse files Browse the repository at this point in the history
The import function most directly models the Node.js command line:
pass the path to the entry module and the capability to read files on
the corresponding file system.
Importing a module creates a compartment graph and executes the entry
module of the root compartment.
  • Loading branch information
kriskowal committed Jun 19, 2020
1 parent 6af7973 commit fe3fc5d
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions packages/endo/src/import.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/* global StaticModuleRecord */
/* eslint no-shadow: 0 */

import { compartmentMapForNodeModules } from "./compartmap.js";
import { search } from "./search.js";
import { assemble } from "./assemble.js";

const decoder = new TextDecoder();

const resolve = (rel, abs) => new URL(rel, abs).toString();

const makeImportHookMaker = (read, rootLocation) => packagePath => {
const packageLocation = resolve(packagePath, rootLocation);
return async moduleSpecifier => {
const moduleLocation = resolve(moduleSpecifier, packageLocation);
const moduleBytes = await read(moduleLocation);
const moduleSource = decoder.decode(moduleBytes);
return new StaticModuleRecord(moduleSource, moduleLocation);
};
};

export const loadPath = async (read, modulePath) => {
const { packagePath, packageDescriptorText, moduleSpecifier } = await search(
read,
modulePath
);

const packageDescriptor = JSON.parse(packageDescriptorText);
const compartmentMap = await compartmentMapForNodeModules(
read,
packagePath,
[],
packageDescriptor
);

const { compartments, main } = compartmentMap;

const makeImportHook = makeImportHookMaker(read, packagePath);

const execute = async (endowments, modules) => {
const compartment = assemble({
name: main,
compartments,
makeImportHook,
endowments,
modules
});
return compartment.import(moduleSpecifier);
};

return { execute };
};

export const importPath = async (read, modulePath, endowments, modules) => {
const application = await loadPath(read, modulePath, endowments, modules);
return application.execute(endowments, modules);
};

0 comments on commit fe3fc5d

Please sign in to comment.