-
Notifications
You must be signed in to change notification settings - Fork 7
/
fix_urls.js
72 lines (66 loc) · 2.63 KB
/
fix_urls.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
62
63
64
65
66
67
68
69
70
71
72
const fs = require('fs');
const path = require('path');
const jsdom = require('jsdom');
const { JSDOM } = jsdom;
function relativeVersion( filename, baseDir ) {
"use strict";
const onLoad = dom => {
const window = dom.window;
const document = window.document;
makeLinksRelative( document, baseDir );
const html = '<!DOCTYPE html>\n' + document.documentElement.outerHTML
fs.writeFile( filename, html, (err) => err?console.log({err}):false );
}
const jsdom_init = ( dom ) => {
const window = dom.window;
window.addEventListener("load",()=>onLoad(dom));
}
const config = { runScripts: "dangerously", resources: "usable" };
return JSDOM.fromFile( filename, config ).then(jsdom_init).catch( err => console.log(err) );
}
function makeLinkRelative( elt, attributeName, baseDir ) {
const oldLink = elt.getAttribute( attributeName );
const newLink = path.relative( baseDir, oldLink ) || ".";
elt.setAttribute( attributeName, newLink );
}
function makeLinksRelative( document, baseDir ) {
"use strict";
for (const elt of document.querySelectorAll('a[href^="/"]')) {
makeLinkRelative( elt, "href", baseDir );
}
for (const elt of document.querySelectorAll('link[href^="/"]')) {
makeLinkRelative( elt, "href", baseDir );
}
for (const elt of document.querySelectorAll('script[src^="/"]')) {
makeLinkRelative( elt, "src", baseDir );
}
for (const elt of document.querySelectorAll('img[src^="/"]')) {
makeLinkRelative( elt, "src", baseDir );
}
}
function recurse( dir, htmlBaseDir, realBaseDir ) {
for (const dirEnt of fs.readdirSync( realBaseDir, {withFileTypes:true})) {
if (typeof dirEnt === "string") { // node 8, EOL Jan 2020
if (fs.statSync( path.join( realBaseDir, dirEnt ) ).isDirectory()) {
const newDir = dirEnt;
if (newDir==="dev") continue;
const newHtmlBaseDir = path.join( htmlBaseDir, newDir );
const newRealBaseDir = path.join( realBaseDir, newDir );
recurse( newDir, newHtmlBaseDir, newRealBaseDir );
} else if (dirEnt.endsWith(".html")) {
const file = path.join( realBaseDir, dirEnt );
relativeVersion( file, htmlBaseDir );
}
} else if (dirEnt.isDirectory()) { // node 10+
const newDir = dirEnt.name;
if (newDir==="dev") continue;
const newHtmlBaseDir = path.join( htmlBaseDir, newDir );
const newRealBaseDir = path.join( realBaseDir, newDir );
recurse( newDir, newHtmlBaseDir, newRealBaseDir );
} else if (dirEnt.name.endsWith(".html")) {
const file = path.join( realBaseDir, dirEnt.name );
relativeVersion( file, htmlBaseDir );
}
}
}
recurse( ".", "/", "./dist" );