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

feat(endo): Module specifier and URL math #342

Merged
merged 7 commits into from
Jun 24, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,6 @@
"import/extensions": "off",
"import/prefer-default-export": "off",
"eslint-comments/no-unused-disable": "error"
}
},
"ignorePatterns": ["**/dist/**"]
}
2 changes: 0 additions & 2 deletions packages/endo/REMOVEME.js

This file was deleted.

7 changes: 5 additions & 2 deletions packages/endo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
"scripts": {
"depcheck": "depcheck",
"lint": "eslint '**/*.js'",
"lint-fix": "eslint --fix '**/*.js'"
"lint-fix": "eslint --fix '**/*.js'",
"test": "tap --no-esm --no-coverage --reporter spec 'test/**/*.test.js'"
},
"dependencies": {
"jszip": "^3.4.0",
Expand All @@ -20,7 +21,9 @@
"eslint-config-prettier": "^6.9.0",
"eslint-plugin-eslint-comments": "^3.1.2",
"eslint-plugin-import": "^2.19.1",
"eslint-plugin-prettier": "^3.1.2"
"eslint-plugin-prettier": "^3.1.2",
"tap": "14.10.5",
"tape": "4.12.1"
},
"files": [
"LICENSE*",
Expand Down
120 changes: 120 additions & 0 deletions packages/endo/src/node-module-specifier.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
// q, as in quote, for error messages.
const q = JSON.stringify;

// Advances a partial module specifier solution by following the path
// components in the given problem.
// The problem may not produce a path that escapes the solution, that is, the
// problem may not traverse up from an empty solution.
// `Solve` returns false if the problem attempts to escape.
// Advanding a partial solution is the core of `resolve`, `join`, and
// `relativize`, which have different invariants.
const solve = (solution, problem) => {
for (const part of problem) {
if (part === "." || part === "") {
// no-op
} else if (part === "..") {
if (solution.length === 0) {
return false;
}
solution.pop();
} else {
solution.push(part);
}
}
return true;
};

// `Resolve` computes the full module specifier for a given imported module specifier
// relative to the referrer module specifier.
// In Node.js compartments, the referrer must be an internal module specifier
// in the context of a compartment, and all internal module specifiers begin
// with a "." path component.
// The referent may be either internal or external.
// In Node.js, fully qualified paths are valid module specifiers, but these
// paths that begin with / are disallowed as they could be used to defeat
// compartment containment.
export const resolve = (spec, referrer) => {
spec = String(spec || "");
referrer = String(referrer || "");

if (spec.startsWith("/")) {
throw new Error(`Module specifier ${q(spec)} must not begin with "/"`);
}
if (!referrer.startsWith("./")) {
throw new Error(`Module referrer ${q(referrer)} must begin with "./"`);
}

const specParts = spec.split("/");
const solution = [];
const problem = [];
if (specParts[0] === "." || specParts[0] === "..") {
const referrerParts = referrer.split("/");
problem.push(...referrerParts);
problem.pop();
solution.push(".");
}
problem.push(...specParts);

if (!solve(solution, problem)) {
throw new Error(
`Module specifier ${q(spec)} via referrer ${q(
referrer
)} must not traverse behind an empty path`
);
}

return solution.join("/");
};

// To construct a module map from a node_modules package, inter-package linkage
// requires connecting a full base module specifier like "dependency-package"
// to the other package's full internal module specifier like "." or
// "./utility", to form a local full module specifier like "dependency-package"
// or "dependency-package/utility".
// This type of join may assert that the base is absolute and the referrent is
// relative.
export const join = (base, spec) => {
spec = String(spec || "");
base = String(base || "");

const specParts = spec.split("/");
const baseParts = base.split("/");

if (specParts.length > 1 && specParts[0] === "") {
throw new Error(`Module specifier ${q(spec)} must not start with "/"`);
}
if (baseParts[0] === "." || baseParts[0] === "..") {
throw new Error(`External module specifier ${q(base)} must be absolute`);
}
if (specParts[0] !== ".") {
throw new Error(`Internal module specifier ${q(spec)} must be relative`);
}

const solution = [];
if (!solve(solution, specParts)) {
throw new Error(
`Module specifier ${q(spec)} via base ${q(
base
)} must not refer to a module outside of the base`
);
}

return [base, ...solution].join("/");
};

// Relativize turns absolute identifiers into relative identifiers.
// In package.json, internal module identifiers can be either relative or
// absolute, but Endo compartments backed by node_modules always use relative
// module specifiers for internal linkage.
export const relativize = spec => {
spec = String(spec || "");

const solution = [];
if (!solve(solution, spec.split("/"))) {
throw Error(
`Module specifier ${q(spec)} must not traverse behind an empty path`
);
}

return [".", ...solution].join("/");
};
78 changes: 78 additions & 0 deletions packages/endo/src/url.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Derrived from https://github.com/junosuarez/url-relative
//
// Copyright (c) MMXV jden jason@denizac.org
//
// ISC License
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

export const relative = (referrer, location) => {
referrer = String(referrer || "");
location = String(location || "");

if (referrer === location) {
return "";
}

const referrerURL = new URL(referrer);
const locationURL = new URL(location);

if (referrerURL.host !== locationURL.host) {
return location;
}

if (referrerURL.protocol !== locationURL.protocol) {
return location;
}

if (referrerURL.auth !== locationURL.auth) {
return location;
}

// left location right, look for closest common path segment
const referrerParts = referrerURL.pathname.substr(1).split("/");
const locationParts = locationURL.pathname.substr(1).split("/");

if (referrerURL.pathname === locationURL.pathname) {
if (locationURL.pathname[locationURL.pathname.length - 1] === "/") {
return ".";
}
return locationParts[locationParts.length - 1];
}

while (referrerParts[0] === locationParts[0]) {
referrerParts.shift();
locationParts.shift();
}

let length = referrerParts.length - locationParts.length;
if (length > 0) {
if (referrer.endsWith("/")) {
locationParts.unshift("..");
}
while (length > 0) {
length -= 1;
locationParts.unshift("..");
}
return locationParts.join("/");
}
if (length < 0) {
return locationParts.join("/");
}
length = locationParts.length - 1;
while (length > 0) {
length -= 1;
locationParts.unshift("..");
}
return locationParts.join("/");
};
69 changes: 69 additions & 0 deletions packages/endo/test/join.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import tape from "tape";
import { join } from "../src/node-module-specifier.js";

const { test } = tape;

const q = JSON.stringify;

[
// { via: "", rel: "./", res: "" },
{ via: "external", rel: "./main.js", res: "external/main.js" },
{
via: "external",
rel: "./internal/main.js",
res: "external/internal/main.js"
},
{ via: "@org/lib", rel: "./lib/app.js", res: "@org/lib/lib/app.js" },
{ via: "external", rel: "./internal/../main.js", res: "external/main.js" }
].forEach(c => {
test(`join(${q(c.via)}, ${q(c.rel)}) -> ${q(c.res)}`, t => {
t.plan(1);
const res = join(c.via, c.rel);
t.equal(res, c.res, `join(${q(c.via)}, ${q(c.rel)}) === ${q(c.res)}`);
t.end();
});
});

test("throws if the specifier is a fully qualified path", t => {
t.throws(
() => {
join("", "/");
},
undefined,
"throws if the specifier is a fully qualified path"
);
t.end();
});

test("throws if the specifier is absolute", t => {
t.throws(
() => {
join("from", "to");
},
undefined,
"throws if the specifier is absolute"
);
t.end();
});

test("throws if the referrer is relative", t => {
t.throws(
() => {
join("./", "foo");
},
undefined,
"throws if the referrer is relative"
);
t.end();
});

test("throws if specifier reaches outside of base", t => {
t.throws(
() => {
join("path/to/base", "./deeper/../..");
},
undefined,
"throw if specifier reaches outside of base"
);
t.end();
});
Loading