Created
October 24, 2021 14:57
-
-
Save ridheshcybe/5e74b75c6f32e8700790adcb8f1ca2af to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { JSDOM } from 'jsdom'; | |
import { readFile } from 'node:fs'; | |
import { resolve } from 'path'; | |
function sleep(ms = 1000) { | |
return new Promise((l, r) => { | |
setTimeout(() => { | |
l(); | |
}, ms); | |
}) | |
} | |
var options = { | |
url: `http://localhost:2021`, | |
referrer: `http://localhost:2021`, | |
contentType: "text/html", | |
includeNodeLocations: true, | |
storageQuota: 5000000 | |
} | |
var __dirname = new URL( | |
import.meta.url).pathname.split(''); | |
__dirname.shift(); | |
__dirname = __dirname.join('').replaceAll('%20', ' ') | |
var frontend = resolve(__dirname, '../../frontend') | |
export default async(path) => { | |
var erra = []; | |
var urls = []; | |
var scripts = ''; | |
var styles = ''; | |
var dom = await JSDOM.fromFile(path, options); | |
var { document } = dom.window; | |
document.querySelectorAll('script').forEach(e => { | |
urls.push({ src: e.src, type: 'script' }); | |
e.remove(); | |
}); | |
document.querySelectorAll('link').forEach(e => { | |
if (e.type == "style") { | |
urls.push({ src: e.href, type: 'style' }); | |
e.remove(); | |
} | |
if (e.type == "manifest") { | |
urls.push({ src: e.src, type: 'manifest' }) | |
} | |
}); | |
urls.forEach(url => { | |
if (url.src) { | |
if (url.type == 'script') { | |
url.src = new URL(url.src).pathname.split('') | |
url.src.shift(); | |
readFile( | |
resolve(frontend, url.src.join('')), | |
"utf-8", | |
(err, data) => { | |
if (err) { | |
erra.push(err) | |
console.log(erra) | |
return | |
}; | |
var script = `<script>${data.trim()}</script>` | |
scripts += script | |
} | |
) | |
}; | |
if (url.type == 'style') { | |
url.src = new URL(url.src).pathname.split('') | |
url.src.shift(); | |
readFile( | |
resolve(frontend, url.src.join('')), | |
"utf-8", | |
(err, data) => { | |
if (err) { | |
erra.push(err) | |
console.log(erra) | |
return; | |
}; | |
var style = `<style>${data.trim()}</style>` | |
styles += style | |
} | |
) | |
}; | |
}; | |
}); | |
await sleep(50); | |
if (erra.length > 0) throw new Error(erra); | |
var html = `<!DOCTYPE html><html lang="en"><head>${document.head.innerHTML}${styles}</head><body>${document.body.innerHTML}${scripts}</body></html>` | |
return html.replace(/^\s+|\s+$/gm, '').replaceAll('\n', ''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment