-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathtransform.js
61 lines (50 loc) · 1.32 KB
/
transform.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import path from "path";
import {URL} from "url";
import {mapping} from "./mapping.js";
const lowercaseMapping = {};
for(let key in mapping) {
lowercaseMapping[key.toLowerCase()] = mapping[key];
}
function isFullUrl(url) {
try {
new URL(url);
return true;
} catch(e) {
return false;
}
}
function parseSource(source) {
let urlObject = new URL(source);
if(urlObject.hostname === "twitter.com") {
let [noop, username, statusStr, statusId] = urlObject.pathname.split("/");
return {
// normalize to lower case
username: username.toLowerCase(),
url: source,
status: statusId,
}
}
return {
url: source
};
}
export function normalizeUrlSlashes(...args) {
let joined = path.join(...args.filter(entry => !!entry));
return joined.split(path.sep).join("/");
}
// source can be a path or a full tweet URL
export function transform(source) {
// passthrough
if(!isFullUrl(source)) {
return source;
}
let { username, status } = parseSource(source);
if(username && lowercaseMapping[username]) {
let urlObject = new URL(lowercaseMapping[username]);
urlObject.pathname = normalizeUrlSlashes(urlObject.pathname, status);
let urlString = urlObject.toString();
let hasTrailingSlash = source.endsWith("/");
return urlString + (!urlString.endsWith("/") && hasTrailingSlash ? "/" : "");
}
return source;
}