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

Replace PhantomJS with Puppeteer #46

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules
yarn.lock
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
2 changes: 0 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,3 @@ sudo: false
language: node_js
node_js:
- '8'
- '6'
- '4'
2 changes: 1 addition & 1 deletion fixtures/script.js
Original file line number Diff line number Diff line change
@@ -1 +1 @@
document.querySelector('.mobile-bar').style.backgroundColor = 'green';
document.querySelector('div').style.backgroundColor = 'red';
90 changes: 50 additions & 40 deletions fixtures/server.js
Original file line number Diff line number Diff line change
@@ -1,46 +1,56 @@
'use strict';
const http = require('http');
const cookie = require('cookie');
const getPort = require('get-port');
const createTestServer = require('create-test-server');
const pify = require('pify');
const toughCookie = require('tough-cookie');

module.exports = opts => {
opts = opts || {};

return getPort().then(port => {
const s = http.createServer((req, res) => {
setTimeout(() => {
s.emit(req.url, req, res);
}, (opts.delay || 0) * 1000);
});

s.port = port;
s.url = `http://localhost:${port}`;
s.close = pify(s.close);

s.on('/', (req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<html style="background-color: black;"></html>');
});

s.on('/cookies', (req, res) => {
const color = cookie.parse(req.headers.cookie).color || 'white';
const style = [
`background-color: ${color}; position: absolute;`,
'top: 0; right: 0; bottom: 0; left: 0;'
].join(' ');

res.writeHead(200, {'Content-Type': 'text/html'});
res.end(`<body><div style="${style}"></div></body>`);
});

s.on('/redirect', (req, res) => {
res.writeHead(302, {location: `http://localhost:${port}/`});
res.end();
});
module.exports = () => createTestServer().then(server => {
server.get('/', (req, res) => {
const style = `background-color: black; width: 100px; height: 100px;`;
res.send(`<body style="margin: 0;"><div style="${style}"></div></body>`);
});

server.get('/delay', (req, res) => {
const style = `width: 100px; height: 100px;`;
res.send(`
<body>
<div style="${style}"></div>
<script>
window.setTimeout(function () {
document.querySelector('div').style.display = 'block';
}, 5000);
</script>
</body>
`);
});

s.listen(port);
server.get('/cookie', (req, res) => {
const color = toughCookie.parse(req.headers.cookie).value || 'white';
const style = `
background-color: ${color};
bottom: 0;
left: 0;
position: absolute;
right: 0;
top: 0;
`;

res.send(`<body><div style="${style}"></div></body>`);
});

return s;
server.get('/headers', (req, res) => {
server.emit('headers', req);
res.end();
});
};

server.get('/redirect', (req, res) => {
res.redirect(server.url);
});

server.get('/timeout/:delay', (req, res) => {
setTimeout(() => {
res.end();
}, req.params.delay * 1000);
});

return server;
});
4 changes: 2 additions & 2 deletions fixtures/style.css
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
.mobile-bar {
background-color: green !important;
div {
background-color: red !important;
}
22 changes: 0 additions & 22 deletions fixtures/test-delay-element.html

This file was deleted.

17 changes: 0 additions & 17 deletions fixtures/test-error-script.html

This file was deleted.

20 changes: 0 additions & 20 deletions fixtures/test-hide-element.html

This file was deleted.

162 changes: 97 additions & 65 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,85 +1,117 @@
'use strict';
const fs = require('fs');
const path = require('path');
const urlMod = require('url');
const base64Stream = require('base64-stream');
const parseCookiePhantomjs = require('parse-cookie-phantomjs');
const phantomBridge = require('phantom-bridge');
const byline = require('byline');

const handleCookies = (cookies, url) => {
const parsedUrl = urlMod.parse(url);

return (cookies || []).map(x => {
const ret = typeof x === 'string' ? parseCookiePhantomjs(x) : x;

if (!ret.domain) {
ret.domain = parsedUrl.hostname;
}
const fileUrl = require('file-url');
const isUrl = require('is-url-superb');
const puppeteer = require('puppeteer');
const toughCookie = require('tough-cookie');

const parseCookie = cookie => {
if (typeof cookie === 'object') {
return cookie;
}

const ret = toughCookie.parse(cookie).toJSON();
ret.name = ret.key;
return ret;
};

if (!ret.path) {
ret.path = parsedUrl.path;
}
const hideElement = element => {
element.style.visibility = 'hidden';
};

return ret;
});
const getBoundingClientRect = element => {
const {height, width, x, y} = element.getBoundingClientRect();
return {height, width, x, y};
};

module.exports = (url, size, opts) => {
module.exports = async (url, opts) => {
opts = Object.assign({
delay: 0,
scale: 1,
format: 'png'
cookies: [],
fullPage: true,
hide: [],
width: 1920,
height: 1080
}, opts);

const args = Object.assign(opts, {
url,
width: size.split(/x/i)[0] * opts.scale,
height: size.split(/x/i)[1] * opts.scale,
cookies: handleCookies(opts.cookies, url),
format: opts.format === 'jpg' ? 'jpeg' : opts.format,
css: /\.css$/.test(opts.css) ? fs.readFileSync(opts.css, 'utf8') : opts.css,
script: /\.js$/.test(opts.script) ? fs.readFileSync(opts.script, 'utf8') : opts.script
});
const uri = isUrl(url) ? url : fileUrl(url);
const {
cookies, crop, format, headers, height, hide, keepAlive, password, scale,
script, selector, style, timeout, transparent, userAgent, username, width
} = opts;

const cp = phantomBridge(path.join(__dirname, 'stream.js'), [
'--ignore-ssl-errors=true',
'--local-to-remote-url-access=true',
'--ssl-protocol=any',
JSON.stringify(args)
]);
opts.type = format === 'jpg' ? 'jpeg' : format;

const stream = base64Stream.decode();
if (crop) {
opts.fullPage = false;
}

process.stderr.setMaxListeners(0);
if (timeout) {
opts.timeout = timeout * 1000;
}

cp.stderr.setEncoding('utf8');
cp.stdout.pipe(stream);
if (transparent) {
opts.omitBackground = true;
}

byline(cp.stderr).on('data', data => {
data = data.trim();
const browser = opts.browser || await puppeteer.launch();
const page = await browser.newPage();
const viewport = {
height,
width,
deviceScaleFactor: typeof scale === 'number' ? scale : null
};

if (/ phantomjs\[/.test(data)) {
return;
}
if (username && password) {
await page.authenticate({username, password});
}

if (/http:\/\/requirejs.org\/docs\/errors.html#mismatch/.test(data)) {
return;
}
if (Array.isArray(cookies) && cookies.length > 0) {
await Promise.all(cookies.map(x => page.setCookie(parseCookie(x))));
}

if (data.startsWith('WARN: ')) {
stream.emit('warning', data.replace(/^WARN: /, ''));
stream.emit('warn', data.replace(/^WARN: /, '')); // TODO: deprecate this event in v5
return;
}
if (typeof headers === 'object') {
await page.setExtraHTTPHeaders(headers);
}

if (userAgent) {
await page.setUserAgent(userAgent);
}

await page.setViewport(viewport);
await page.goto(uri, opts);

if (data.length > 0) {
const err = new Error(data);
err.noStack = true;
cp.stdout.unpipe(stream);
stream.emit('error', err);
if (script) {
const key = isUrl(script) ? 'url' : script.endsWith('.js') ? 'path' : 'content';
await page.addScriptTag({[key]: script});
}

if (style) {
const key = isUrl(style) ? 'url' : style.endsWith('.css') ? 'path' : 'content';
await page.addStyleTag({[key]: style});

if (isUrl(style)) {
console.log(key, style);
}
});
}

if (Array.isArray(hide) && hide.length > 0) {
await Promise.all(hide.map(x => page.$eval(x, hideElement)));
}

if (selector) {
await page.waitForSelector(selector, {visible: true});

return stream;
opts.clip = await page.$eval(selector, getBoundingClientRect);
opts.fullPage = false;
}

const buf = await page.screenshot(opts);
await page.close();

if (keepAlive !== true) {
await browser.close();
}

return buf;
};

module.exports.startBrowser = puppeteer.launch;
22 changes: 5 additions & 17 deletions license
Original file line number Diff line number Diff line change
@@ -1,21 +1,9 @@
The MIT License (MIT)
MIT License

Copyright (c) Kevin Mårtensson <[email protected]>
Copyright (c) Kevin Mårtensson <[email protected]> (github.com/kevva)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Loading