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

refactor(joinURL): rewrite with clear syntax and relative ../ support #218

Merged
merged 5 commits into from Mar 11, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
60 changes: 41 additions & 19 deletions src/utils.ts
Expand Up @@ -13,8 +13,6 @@ const PROTOCOL_REGEX = /^[\s\w\0+.-]{2,}:([/\\]{2})?/;
const PROTOCOL_RELATIVE_REGEX = /^([/\\]\s*){2,}[^/\\]/;
const PROTOCOL_SCRIPT_RE = /^[\s\0]*(blob|data|javascript|vbscript):$/i;
const TRAILING_SLASH_RE = /\/$|\/\?|\/#/;
const JOIN_LEADING_SLASH_RE = /^\.?\//;
const JOIN_LAST_SEGMENT_RE = /(?:^|\/)[^/]*\/?$/;

/**
* Check if a path starts with `./` or `../`.
Expand Down Expand Up @@ -319,27 +317,51 @@ export function isNonEmptyURL(url: string) {
*
* @group utils
*/
export function joinURL(base: string, ...input: string[]): string {
let url = base || "";

for (const segment of input.filter((url) => isNonEmptyURL(url))) {
if (url) {
const hasAbsoluteBase = url.startsWith("/");
let _segment = segment;
_segment = _segment.replace(JOIN_LEADING_SLASH_RE, "");
while (url.length > 0 && _segment.startsWith("../")) {
url = url.replace(JOIN_LAST_SEGMENT_RE, "");
_segment = _segment.slice(3).replace(JOIN_LEADING_SLASH_RE, "");
export function joinURL(..._input: string[]): string {
const input = _input.filter(Boolean);

const segments: string[] = [];

let segmentsDepth = 0;

for (const i of input) {
if (!i || i === "/") {
continue;
}
for (const s of i.split("/")) {
if (!s || s === ".") {
continue;
}
if (s === "..") {
segments.pop();
segmentsDepth--;
continue;
}
url =
!url && (!hasAbsoluteBase || _segment.startsWith("../"))
? _segment
: withTrailingSlash(url) + _segment;
} else {
url = segment;
segments.push(s);
segmentsDepth++;
}
}

let url = segments.join("/");

if (segmentsDepth >= 0) {
// Preserve leading slash
if (input[0]?.startsWith("/") && !url.startsWith("/")) {
url = "/" + url;
} else if (input[0]?.startsWith("./") && !url.startsWith("./")) {
url = "./" + url;
}
} else {
// Add relative prefix
url = "../".repeat(-1 * segmentsDepth) + url;
}

// Preserve trailing slash
// eslint-disable-next-line unicorn/prefer-at
if (input[input.length - 1]?.endsWith("/") && !url.endsWith("/")) {
url += "/";
}

return url;
}

Expand Down
33 changes: 15 additions & 18 deletions test/join.test.ts
Expand Up @@ -5,38 +5,35 @@ describe("joinURL", () => {
const tests = [
{ input: [], out: "" },
{ input: ["/"], out: "/" },
// eslint-disable-next-line unicorn/no-null
{ input: [null, "./"], out: "./" },
{ input: [undefined, "./"], out: "./" },
{ input: ["./", "a"], out: "./a" },
{ input: ["./a", "./b"], out: "./a/b" },
{ input: ["/a"], out: "/a" },
{ input: ["a", "b"], out: "a/b" },
{ input: ["/", "/b"], out: "/b" },
{ input: ["/a", "../b"], out: "/b" },
{ input: ["../a", "../b"], out: "../b" },
{ input: ["../a", "./../b"], out: "../b" },
{ input: ["../a", "./../../b"], out: "b" },
{ input: ["../a", "../../../b"], out: "../b" },
{ input: ["../a", "../../../../b"], out: "../../b" },
{ input: ["../a/", "../b"], out: "../b" },
{ input: ["/a/b/c", "../../d"], out: "/a/d" },
{ input: ["/c", "../../d"], out: "../d" },
{ input: ["/c", ".././../d"], out: "../d" },
{ input: ["a", "b/", "c"], out: "a/b/c" },
{ input: ["a", "b/", "/c"], out: "a/b/c" },
{ input: ["/", "./"], out: "/" },
{ input: ["/", "./foo"], out: "/foo" },
{ input: ["/", "./foo/"], out: "/foo/" },
{ input: ["/", "./foo", "bar"], out: "/foo/bar" },

// Relative with ../
{ input: ["/a", "../b"], out: "/b" },
{ input: ["/a/b/c", "../../d"], out: "/a/d" },
{ input: ["/c", "../../d"], out: "/d" },
Copy link
Member Author

@pi0 pi0 Mar 11, 2024

Choose a reason for hiding this comment

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

Updated behavior from #217 (was ../d). Confirming with two similar references:

new URL("../../d", 'http://test.com/c').pathname
// ~> "/d"

path.join("/c", "../../d")
// ~> "/d"

pathe.join("/c", "../../d")
// ~> "/d"

It is hard to decide if we should make a new 3rd behavior with ufo (which is really hard to break later)

ufo (1.4.0) behavior:

ufo.joinURL("/c", "../../d")
// "/c/../../d"

(with current behavior, we don't resolve, nor loose information but also we don't have a 3rd behavior by returning ../d)

Copy link
Member

Choose a reason for hiding this comment

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

I think existing behaviour is not to coerce a URL segment to be absolute, so joinURL('./a', 'b') resolves to ./a/b. Likewise, I think joinURL('../a', 'b') should also resolve to ../a/b and joinURL('../a', '../b') should resolve to ../b.

The key difference between new URL and joinURL is that joinURL is useable for URL segments and this is quite a useful feature. It's also important when generating relative URLs, which is something that the native URL can't do.

I would advise keeping this behaviour.

// { input: ["/c", ".././../d"], out: "../d" },
// { input: ["../a", "../b"], out: "../b" },
// { input: ["../a", "./../b"], out: "../b" },
// { input: ["../a", "./../../b"], out: "b" },
// { input: ["../a", "../../../b"], out: "../b" },
// { input: ["../a", "../../../../b"], out: "../../b" },
// { input: ["../a/", "../b"], out: "../b" },
];

for (const t of tests) {
test(JSON.stringify(t.input), () => {
expect(joinURL(...t.input)).toBe(t.out);
test(`joinURL(${t.input.map((i) => JSON.stringify(i)).join(", ")}) === ${JSON.stringify(t.out)}`, () => {
expect(joinURL(...(t.input as string[]))).toBe(t.out);
});
}

test("no arguments", () => {
expect(joinURL()).toBe("");
});
});