提交 b83b711d 编写于 作者: P Pavel Feldman

Initial commit

上级
/node_modules/
.DS_Store
*.swp
*.pyc
.vscode
package-lock.json
# repeats from .gitignore
node_modules
.DS_Store
.vscode
package-lock.json
/examples
CONTRIBUTING.md
.npmignore
# How to Contribute
We'd love to accept your patches and contributions to this project. There are
just a few small guidelines you need to follow.
## Contributor License Agreement
Contributions to this project must be accompanied by a Contributor License
Agreement. You (or your employer) retain the copyright to your contribution;
this simply gives us permission to use and redistribute your contributions as
part of the project. Head over to <https://cla.developers.google.com/> to see
your current agreements on file or to sign a new one.
You generally only need to submit a CLA once, so if you've already submitted one
(even if it was for a different project), you probably don't need to do it
again.
## Code reviews
All submissions, including submissions by project members, require review. We
use GitHub pull requests for this purpose. Consult
[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
information on using pull requests.
## Community Guidelines
This project follows [Google's Open Source Community
Guidelines](https://opensource.google.com/conduct/).
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
# Carlo
###### [Contributing](https://github.com/GoogleChromeLabs/carlo/blob/master/CONTRIBUTING.md)
> Carlo provides your Node application with the rich rendering capabilities powered by the Google Chrome browser.
![image](https://user-images.githubusercontent.com/883973/47678948-34a00800-db80-11e8-8275-d376145d2f6a.png)
<!-- [START usecases] -->
###### What can I do?
With Carlo, you can create hybrid applications that use Web stack for rendering and Node for capabilities:
- For Node applications, you can visualize dynamic state of your Node app using web rendering stack
- For Web applications, you can expose additional system capabilities accessible from Node
###### How does it work?
- Carlo locates Google Chrome installed locally
- Launches it and establishes connection to Chrome over the process pipe
- Exposes high level API for rendering in Chrome in Node environment
- Carlo is based on the [Puppeteer](https://github.com/GoogleChrome/puppeteer/) project
<!-- [END usecases] -->
<!-- [START getstarted] -->
## Getting Started
### Installation
To use Carlo in your project, run:
```bash
npm i carlo
# or "yarn add carlo"
```
### Usage
Note: Carlo requires at least Node v7.6.0.
**Example** - Visualize local environment:
Save file as **example.js**
```js
const carlo = require('carlo');
(async () => {
const app = await carlo.launch();
app.serveFolder(__dirname);
await app.exposeFunction('env', _ => process.env);
await app.load('example.html');
})();
```
Save file as **example.html**
```html
<script>
async function run() {
const data = await env();
const grids = document.getElementById('body');
for (const type in data) {
const div = document.createElement('div');
div.textContent = `${type}: ${data[type]}`;
document.body.appendChild(div);
}
}
</script>
<body onload="run()">
```
Execute script on the command line
```bash
node example.js
```
Check out more examples with richer UI and RPC-based communication between the Web and Node componenets under the `examples` folder.
<!-- [END getstarted] -->
## Contributing to Carlo
Check out [contributing guide](https://github.com/GoogleChromeLabs/carlo/blob/master/CONTRIBUTING.md) to get an overview of Puppeteer development.
<!-- [START faq] -->
# FAQ
<!-- [END faq] -->
/**
* Copyright 2018 Google Inc., PhantomJS Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const carlo = require('carlo');
const si = require('systeminformation');
(async () => {
const app = await carlo.launch(
{
bgcolor: '#2b2e3b',
width: 800,
height: 800
});
app.serveFolder(__dirname + '/www');
await app.exposeFunction('systeminfo', systeminfo);
await app.load('index.html');
})();
async function systeminfo() {
const info = {};
await Promise.all([
si.system().then(r => info.system = r),
si.battery().then(r => info.battery = r),
si.cpu().then(r => info.cpu = r),
si.osInfo().then(r => info.osInfo = r),
]);
return info;
}
{
"name": "systeminfo-app",
"version": "0.9.0",
"description": "System info example",
"main": "main.js",
"scripts": {
"pack": "pkg package.json",
"run": "node main.js"
},
"bin": {
"systeminfo-app": "./main.js"
},
"pkg": {
"scripts": "*.js",
"assets": "www/**/*"
},
"keywords": [],
"author": "The Chromium Authors",
"license": "Apache-2.0",
"dependencies": {
"carlo": "^0.9.0",
"systeminformation": "^3.45.9"
},
"devDependencies": {
"pkg": "^4.3.4"
}
}
<!--
Copyright 2018 Google Inc., PhantomJS Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html>
<style>
body {
color: #ddd;
display: flex;
justify-content: center;
background-color: #2b2e3b;
opacity: 0;
transition: opacity 2s;
}
.content {
display: flex;
flex-direction: column;
flex: auto;
justify-content: center;
}
.heading {
font-size: 36px;
text-align: center;
margin: 25px 0;
}
#grids {
margin-top: 30px;
color: #ddd;
display: grid;
grid-template-columns: 50% 50%;
grid-gap: 40px;
margin: 25px 100px;
}
.grid-placeholder {
display: flex;
flex-direction: column;
}
.grid {
flex: auto;
display: grid;
grid-template-columns: 1fr 4fr;
grid-gap: 4px;
}
.header {
font-weight: bold;
grid-column: span 2;
border-bottom: 1px solid #999;
}
</style>
<title>Systeminfo App</title>
<script>
async function onload() {
const data = await systeminfo();
const grids = document.getElementById('grids');
for (const type in data) {
const info = data[type];
const placeholder = createChild(grids, 'div', 'grid-placeholder');
const grid = createChild(placeholder, 'div', 'grid');
createChild(grid, 'div', 'header').textContent = type;
for (const key in info) {
if (typeof info[key] === 'object') continue;
createChild(grid, 'div').textContent = key;
createChild(grid, 'div').textContent = info[key];
}
}
document.body.style.opacity = 1;
}
function createChild(parent, tag, className) {
const elem = document.createElement(tag);
if (className)
elem.className = className;
parent.appendChild(elem);
return elem;
}
</script>
<body onload="onload()">
<div class="content">
<div class="heading">Welcome to Carlo!</div>
<div id="grids"></div>
</div>
</body>
</html>
#!/usr/bin/env node
/**
* Copyright 2018 Google Inc., PhantomJS Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const EventEmitter = require('events');
const child_process = require('child_process');
const os = require('os');
const pty = require('ndb-node-pty-prebuilt');
const carlo = require('carlo');
if (!process.env.CARLO) {
child_process.spawn(process.argv[0], [__filename], {
detached: true,
env: { CARLO: 1, ...process.env }
});
process.exit(0);
return;
}
(async () => {
const app = await carlo.launch({ bgcolor: '#2b2e3b' });
app.serveFolder(__dirname + '/www');
app.serveFolder(__dirname + '/node_modules', 'node_modules');
await app.exposeService(Terminal);
await app.load('index.html');
})();
class Terminal extends EventEmitter {
constructor() {
super();
const shell = os.platform() === 'win32' ? 'powershell.exe' : 'bash';
this.term_ = pty.spawn(shell, [], {
name: 'xterm-color',
cwd: process.env.PWD,
env: process.env
});
this.term_.on('data', data => this.emit('data', data));
}
resize(cols, rows) {
this.term_.resize(cols, rows);
}
write(data) {
this.term_.write(data);
}
dispose() {
process.kill(this._term.pid);
}
}
{
"name": "xterm-app",
"version": "0.9.0",
"description": "Terminal example",
"main": "main.js",
"scripts": {
"pack": "pkg package.json",
"run": "node main.js"
},
"bin": {
"xterm-app": "./main.js"
},
"keywords": [],
"author": "The Chromium Authors",
"license": "Apache-2.0",
"dependencies": {
"carlo": "^0.9.0",
"ndb-node-pty-prebuilt": "^0.8.0",
"xterm": "^3.8.0"
},
"devDependencies": {
"pkg": "^4.3.4"
}
}
<!--
Copyright 2018 Google Inc., PhantomJS Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html>
<link rel="stylesheet" href="node_modules/xterm/dist/xterm.css" />
<title>Carlo Terminal</title>
<style>
body, #terminal {
display: flex;
flex: auto;
}
</style>
<script src="node_modules/xterm/dist/xterm.js"></script>
<script src="node_modules/xterm/dist/addons/fit/fit.js"></script>
<script>
Terminal.applyAddon(fit);
async function start() {
// Create service.
const term = await rpc.create('Terminal');
// Create ui control.
const termUI = new Terminal({cursorBlink: true});
termUI.open(document.getElementById('terminal'));
window.onresize = () => termUI.fit();
// Wire them together.
termUI.on('data', data => term.write(data));
term.on('data', data => termUI.write(data));
termUI.on('resize', size => term.resize(size.cols, size.rows));
// Init.
termUI.fit();
termUI.focus();
}
</script>
<body onload="start()">
<div id="terminal"></div>
</body>
</html>
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
module.exports = require('./lib/carlo');
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const puppeteer = require('puppeteer-core');
const findChrome = require('./find-chrome');
const rpc = require('./rpc');
const {Color} = require('./color');
const fs = require('fs');
const util = require('util');
const {URL} = require('url');
const fsReadFile = util.promisify(fs.readFile);
class App {
/**
* @param {!Page} page Puppeteer page
* @param {!RpcServer} rpcServer
*/
constructor(page, rpcServer) {
this.www_ = new Map();
this.page_ = page;
this.page_.on('request', this.requestIntercepted_.bind(this));
this.page_.on('close', () => process.exit());
this.rpcServer_ = rpcServer;
}
/**
* @param {string} name
* @param {function} func
* @return {!Promise}
*/
exposeFunction(name, func) {
return this.page_.exposeFunction(name, func);
}
/**
* @param {function(new:EventEmitter)} c Constructor of the remotely accessible
* service object.
*/
exposeService(c) {
this.rpcServer_.registerService(c);
}
/**
* @param {function()|string} pageFunction
* @param {!Array<*>} args
* @return {!Promise<*>}
*/
evaluate(pageFunction, ...args) {
return this.page_.evaluate(pageFunction, ...args);
}
/**
* @param {string} www Folder with the web content.
* @param {string=} path Only serve folder for requests with given prefix.
*/
serveFolder(folder, prefix) {
this.www_.set(prefix || '', folder);
}
/**
* @param {string} uri
* @return {!Promise}
*/
load(uri) {
return this.page_.goto(`https://domain/${uri}`, {timeout: 0});
}
/**
* @param {!Request} request Intercepted request.
*/
async requestIntercepted_(request) {
const url = new URL(request.url());
if (url.hostname !== 'domain') {
request.continue();
return;
}
for (const [prefix, folder] of this.www_) {
let pathname = url.pathname.substr(1);
if (!pathname.startsWith(prefix))
continue;
pathname = pathname.substr(prefix.length);
const fileName = folder + '/' + pathname;
if (!fs.existsSync(fileName))
continue;
const buffer = await fsReadFile(fileName);
request.respond({
status: 200,
body: buffer
});
return;
}
request.continue();
}
}
/**
* @param {!Object=} options
* @return {!Browser}
*/
async function launch(options = {}) {
if (!options.bgcolor)
options.bgcolor = '#ffffff';
const bgcolor = Color.parse(options.bgcolor);
const bgcolorHex = bgcolor.asString(Color.Format.HEX);
const bgcolorRGBA = bgcolor.canonicalRGBA();
const executablePath = findChrome().pop();
if (!executablePath) {
console.error('Could not find Chrome installation, please make sure Chrome browser is installed.')
process.exit(0);
return;
}
const args = [
`--app=data:text/html,<style>html{background:${bgcolorHex};}</style>`,
`--enable-features=NetworkService`,
];
if (options.width && options.height)
args.push(`--window-size=800,800`);
const browser = await puppeteer.launch({
executablePath,
pipe: true,
defaultViewport: null,
headless: false,
userDataDir: '.profile',
args });
const page = (await browser.pages()).find(page => page.url().startsWith('data:text/html,'));
page.setRequestInterception(true);
page.target().createCDPSession().then(async session => {
await session.send('Emulation.setDefaultBackgroundColorOverride',
{color: {r: bgcolorRGBA[0], g: bgcolorRGBA[1],
b: bgcolorRGBA[2], a: bgcolorRGBA[3] * 255}});
session.detach();
});
const rpcServer = new rpc.Server(page);
await rpcServer.init(page);
return new App(page, rpcServer);
}
module.exports = { launch };
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
class Color {
/**
* @param {!Array.<number>} rgba
* @param {!Color.Format} format
* @param {string=} originalText
*/
constructor(rgba, format, originalText) {
this._rgba = rgba;
this._originalText = originalText || null;
this._originalTextIsValid = !!this._originalText;
this._format = format;
if (typeof this._rgba[3] === 'undefined')
this._rgba[3] = 1;
for (let i = 0; i < 4; ++i) {
if (this._rgba[i] < 0) {
this._rgba[i] = 0;
this._originalTextIsValid = false;
}
if (this._rgba[i] > 1) {
this._rgba[i] = 1;
this._originalTextIsValid = false;
}
}
}
/**
* @param {string} text
* @return {?Color}
*/
static parse(text) {
// Simple - #hex, nickname
const value = text.toLowerCase().replace(/\s+/g, '');
const simple = /^(?:#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8}))$/i;
let match = value.match(simple);
if (match) {
if (match[1]) { // hex
let hex = match[1].toLowerCase();
let format;
if (hex.length === 3) {
format = Color.Format.ShortHEX;
hex = hex.charAt(0) + hex.charAt(0) + hex.charAt(1) + hex.charAt(1) + hex.charAt(2) + hex.charAt(2);
} else if (hex.length === 4) {
format = Color.Format.ShortHEXA;
hex = hex.charAt(0) + hex.charAt(0) + hex.charAt(1) + hex.charAt(1) + hex.charAt(2) + hex.charAt(2) +
hex.charAt(3) + hex.charAt(3);
} else if (hex.length === 6) {
format = Color.Format.HEX;
} else {
format = Color.Format.HEXA;
}
const r = parseInt(hex.substring(0, 2), 16);
const g = parseInt(hex.substring(2, 4), 16);
const b = parseInt(hex.substring(4, 6), 16);
let a = 1;
if (hex.length === 8)
a = parseInt(hex.substring(6, 8), 16) / 255;
return new Color([r / 255, g / 255, b / 255, a], format, text);
}
return null;
}
// rgb/rgba(), hsl/hsla()
match = text.toLowerCase().match(/^\s*(?:(rgba?)|(hsla?))\((.*)\)\s*$/);
if (match) {
const components = match[3].trim();
let values = components.split(/\s*,\s*/);
if (values.length === 1) {
values = components.split(/\s+/);
if (values[3] === '/') {
values.splice(3, 1);
if (values.length !== 4)
return null;
} else if ((values.length > 2 && values[2].indexOf('/') !== -1) || (values.length > 3 && values[3].indexOf('/') !== -1)) {
const alpha = values.slice(2, 4).join('');
values = values.slice(0, 2).concat(alpha.split(/\//)).concat(values.slice(4));
} else if (values.length >= 4) {
return null;
}
}
if (values.length !== 3 && values.length !== 4 || values.indexOf('') > -1)
return null;
const hasAlpha = (values[3] !== undefined);
if (match[1]) { // rgb/rgba
const rgba = [
Color._parseRgbNumeric(values[0]), Color._parseRgbNumeric(values[1]),
Color._parseRgbNumeric(values[2]), hasAlpha ? Color._parseAlphaNumeric(values[3]) : 1
];
if (rgba.indexOf(null) > -1)
return null;
return new Color(rgba, hasAlpha ? Color.Format.RGBA : Color.Format.RGB, text);
}
if (match[2]) { // hsl/hsla
const hsla = [
Color._parseHueNumeric(values[0]), Color._parseSatLightNumeric(values[1]),
Color._parseSatLightNumeric(values[2]), hasAlpha ? Color._parseAlphaNumeric(values[3]) : 1
];
if (hsla.indexOf(null) > -1)
return null;
const rgba = [];
Color.hsl2rgb(hsla, rgba);
return new Color(rgba, hasAlpha ? Color.Format.HSLA : Color.Format.HSL, text);
}
}
return null;
}
/**
* @param {string} value
* return {number}
*/
static _parsePercentOrNumber(value) {
if (isNaN(value.replace('%', '')))
return null;
const parsed = parseFloat(value);
if (value.indexOf('%') !== -1) {
if (value.indexOf('%') !== value.length - 1)
return null;
return parsed / 100;
}
return parsed;
}
/**
* @param {string} value
* return {number}
*/
static _parseRgbNumeric(value) {
const parsed = Color._parsePercentOrNumber(value);
if (parsed === null)
return null;
if (value.indexOf('%') !== -1)
return parsed;
return parsed / 255;
}
/**
* @param {string} value
* return {number}
*/
static _parseHueNumeric(value) {
const angle = value.replace(/(deg|g?rad|turn)$/, '');
if (isNaN(angle) || value.match(/\s+(deg|g?rad|turn)/))
return null;
const number = parseFloat(angle);
if (value.indexOf('turn') !== -1)
return number % 1;
else if (value.indexOf('grad') !== -1)
return (number / 400) % 1;
else if (value.indexOf('rad') !== -1)
return (number / (2 * Math.PI)) % 1;
return (number / 360) % 1;
}
/**
* @param {string} value
* return {number}
*/
static _parseSatLightNumeric(value) {
if (value.indexOf('%') !== value.length - 1 || isNaN(value.replace('%', '')))
return null;
const parsed = parseFloat(value);
return Math.min(1, parsed / 100);
}
/**
* @param {string} value
* return {number}
*/
static _parseAlphaNumeric(value) {
return Color._parsePercentOrNumber(value);
}
/**
* @param {!Array.<number>} hsl
* @param {!Array.<number>} out_rgb
*/
static hsl2rgb(hsl, out_rgb) {
const h = hsl[0];
let s = hsl[1];
const l = hsl[2];
function hue2rgb(p, q, h) {
if (h < 0)
h += 1;
else if (h > 1)
h -= 1;
if ((h * 6) < 1)
return p + (q - p) * h * 6;
else if ((h * 2) < 1)
return q;
else if ((h * 3) < 2)
return p + (q - p) * ((2 / 3) - h) * 6;
else
return p;
}
if (s < 0)
s = 0;
let q;
if (l <= 0.5)
q = l * (1 + s);
else
q = l + s - (l * s);
const p = 2 * l - q;
const tr = h + (1 / 3);
const tg = h;
const tb = h - (1 / 3);
out_rgb[0] = hue2rgb(p, q, tr);
out_rgb[1] = hue2rgb(p, q, tg);
out_rgb[2] = hue2rgb(p, q, tb);
out_rgb[3] = hsl[3];
}
/**
* @return {!Color.Format}
*/
format() {
return this._format;
}
/**
* @return {!Array.<number>} HSLA with components within [0..1]
*/
hsla() {
if (this._hsla)
return this._hsla;
const r = this._rgba[0];
const g = this._rgba[1];
const b = this._rgba[2];
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const diff = max - min;
const add = max + min;
let h;
if (min === max)
h = 0;
else if (r === max)
h = ((1 / 6 * (g - b) / diff) + 1) % 1;
else if (g === max)
h = (1 / 6 * (b - r) / diff) + 1 / 3;
else
h = (1 / 6 * (r - g) / diff) + 2 / 3;
const l = 0.5 * add;
let s;
if (l === 0)
s = 0;
else if (l === 1)
s = 0;
else if (l <= 0.5)
s = diff / add;
else
s = diff / (2 - add);
this._hsla = [h, s, l, this._rgba[3]];
return this._hsla;
}
/**
* @return {boolean}
*/
hasAlpha() {
return this._rgba[3] !== 1;
}
/**
* @return {!Color.Format}
*/
detectHEXFormat() {
let canBeShort = true;
for (let i = 0; i < 4; ++i) {
const c = Math.round(this._rgba[i] * 255);
if (c % 17) {
canBeShort = false;
break;
}
}
const hasAlpha = this.hasAlpha();
const cf = Color.Format;
if (canBeShort)
return hasAlpha ? cf.ShortHEXA : cf.ShortHEX;
return hasAlpha ? cf.HEXA : cf.HEX;
}
/**
* @return {?string}
*/
asString(format) {
if (format === this._format && this._originalTextIsValid)
return this._originalText;
if (!format)
format = this._format;
/**
* @param {number} value
* @return {number}
*/
function toRgbValue(value) {
return Math.round(value * 255);
}
/**
* @param {number} value
* @return {string}
*/
function toHexValue(value) {
const hex = Math.round(value * 255).toString(16);
return hex.length === 1 ? '0' + hex : hex;
}
/**
* @param {number} value
* @return {string}
*/
function toShortHexValue(value) {
return (Math.round(value * 255) / 17).toString(16);
}
switch (format) {
case Color.Format.Original:
return this._originalText;
case Color.Format.RGB:
if (this.hasAlpha())
return null;
return String.sprintf(
'rgb(%d, %d, %d)', toRgbValue(this._rgba[0]), toRgbValue(this._rgba[1]), toRgbValue(this._rgba[2]));
case Color.Format.RGBA:
return String.sprintf(
'rgba(%d, %d, %d, %f)', toRgbValue(this._rgba[0]), toRgbValue(this._rgba[1]), toRgbValue(this._rgba[2]),
this._rgba[3]);
case Color.Format.HSL:
if (this.hasAlpha())
return null;
const hsl = this.hsla();
return String.sprintf(
'hsl(%d, %d%, %d%)', Math.round(hsl[0] * 360), Math.round(hsl[1] * 100), Math.round(hsl[2] * 100));
case Color.Format.HSLA:
const hsla = this.hsla();
return String.sprintf(
'hsla(%d, %d%, %d%, %f)', Math.round(hsla[0] * 360), Math.round(hsla[1] * 100), Math.round(hsla[2] * 100),
hsla[3]);
case Color.Format.HEXA:
return String
.sprintf(
'#%s%s%s%s', toHexValue(this._rgba[0]), toHexValue(this._rgba[1]), toHexValue(this._rgba[2]),
toHexValue(this._rgba[3]))
.toLowerCase();
case Color.Format.HEX:
if (this.hasAlpha())
return null;
return String
.sprintf('#%s%s%s', toHexValue(this._rgba[0]), toHexValue(this._rgba[1]), toHexValue(this._rgba[2]))
.toLowerCase();
case Color.Format.ShortHEXA:
const hexFormat = this.detectHEXFormat();
if (hexFormat !== Color.Format.ShortHEXA && hexFormat !== Color.Format.ShortHEX)
return null;
return String
.sprintf(
'#%s%s%s%s', toShortHexValue(this._rgba[0]), toShortHexValue(this._rgba[1]),
toShortHexValue(this._rgba[2]), toShortHexValue(this._rgba[3]))
.toLowerCase();
case Color.Format.ShortHEX:
if (this.hasAlpha())
return null;
if (this.detectHEXFormat() !== Color.Format.ShortHEX)
return null;
return String
.sprintf(
'#%s%s%s', toShortHexValue(this._rgba[0]), toShortHexValue(this._rgba[1]),
toShortHexValue(this._rgba[2]))
.toLowerCase();
}
return this._originalText;
}
/**
* @return {!Array<number>}
*/
rgba() {
return this._rgba.slice();
}
/**
* @return {!Array.<number>}
*/
canonicalRGBA() {
const rgba = new Array(4);
for (let i = 0; i < 3; ++i)
rgba[i] = Math.round(this._rgba[i] * 255);
rgba[3] = this._rgba[3];
return rgba;
}
};
/** @type {!RegExp} */
Color.Regex = /((?:rgb|hsl)a?\([^)]+\)|#[0-9a-fA-F]{8}|#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3,4}|\b[a-zA-Z]+\b(?!-))/g;
/**
* @enum {string}
*/
Color.Format = {
Original: 'original',
HEX: 'hex',
ShortHEX: 'shorthex',
HEXA: 'hexa',
ShortHEXA: 'shorthexa',
RGB: 'rgb',
RGBA: 'rgba',
HSL: 'hsl',
HSLA: 'hsla'
};
module.exports = { Color };
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const fs = require('fs');
const path = require('path');
const execSync = require('child_process').execSync;
const execFileSync = require('child_process').execFileSync;
const newLineRegex = /\r?\n/;
function darwin() {
const suffixes = ['/Contents/MacOS/Google Chrome Canary', '/Contents/MacOS/Google Chrome'];
const LSREGISTER = '/System/Library/Frameworks/CoreServices.framework' +
'/Versions/A/Frameworks/LaunchServices.framework' +
'/Versions/A/Support/lsregister';
const installations = [];
const customChromePath = resolveChromePath();
if (customChromePath)
installations.push(customChromePath);
execSync(
`${LSREGISTER} -dump` +
' | grep -i \'google chrome\\( canary\\)\\?.app$\'' +
' | awk \'{$1=""; print $0}\'')
.toString()
.split(newLineRegex)
.forEach((inst) => {
suffixes.forEach(suffix => {
const execPath = path.join(inst.trim(), suffix);
if (canAccess(execPath)) {
installations.push(execPath);
}
});
});
// Retains one per line to maintain readability.
// clang-format off
const priorities = [
{regex: new RegExp(`^${process.env.HOME}/Applications/.*Chrome.app`), weight: 50},
{regex: new RegExp(`^${process.env.HOME}/Applications/.*Chrome Canary.app`), weight: 51},
{regex: /^\/Applications\/.*Chrome.app/, weight: 100},
{regex: /^\/Applications\/.*Chrome Canary.app/, weight: 101},
{regex: /^\/Volumes\/.*Chrome.app/, weight: -2},
{regex: /^\/Volumes\/.*Chrome Canary.app/, weight: -1},
];
if (process.env.CHROME_PATH) {
priorities.unshift({regex: new RegExp(`${process.env.CHROME_PATH}`), weight: 151});
}
// clang-format on
return sort(installations, priorities);
}
function resolveChromePath() {
if (canAccess(`${process.env.CHROME_PATH}`)) {
return process.env.CHROME_PATH;
}
return '';
}
/**
* Look for linux executables in 3 ways
* 1. Look into CHROME_PATH env variable
* 2. Look into the directories where .desktop are saved on gnome based distro's
* 3. Look for google-chrome-stable & google-chrome executables by using the which command
*/
function linux() {
let installations = [];
// 1. Look into CHROME_PATH env variable
const customChromePath = resolveChromePath();
if (customChromePath) {
installations.push(customChromePath);
}
// 2. Look into the directories where .desktop are saved on gnome based distro's
const desktopInstallationFolders = [
path.join(require('os').homedir(), '.local/share/applications/'),
'/usr/share/applications/',
];
desktopInstallationFolders.forEach(folder => {
installations = installations.concat(findChromeExecutables(folder));
});
// Look for google-chrome(-stable) & chromium(-browser) executables by using the which command
const executables = [
'google-chrome-stable',
'google-chrome',
'chromium-browser',
'chromium',
];
executables.forEach((executable) => {
try {
const chromePath =
execFileSync('which', [executable], {stdio: 'pipe'}).toString().split(newLineRegex)[0];
if (canAccess(chromePath)) {
installations.push(chromePath);
}
} catch (e) {
// Not installed.
}
});
if (!installations.length) {
throw new Error('The environment variable CHROME_PATH must be set to executable of a build of Chromium version 54.0 or later.');
}
const priorities = [
{regex: /chrome-wrapper$/, weight: 51},
{regex: /google-chrome-stable$/, weight: 50},
{regex: /google-chrome$/, weight: 49},
{regex: /chromium-browser$/, weight: 48},
{regex: /chromium$/, weight: 47},
];
if (process.env.CHROME_PATH) {
priorities.unshift({regex: new RegExp(`${process.env.CHROME_PATH}`), weight: 101});
}
return sort(uniq(installations.filter(Boolean)), priorities);
}
function win32() {
const installations = [];
const suffixes = [
`${path.sep}Google${path.sep}Chrome SxS${path.sep}Application${path.sep}chrome.exe`,
`${path.sep}Google${path.sep}Chrome${path.sep}Application${path.sep}chrome.exe`
];
const prefixes = [
process.env.LOCALAPPDATA, process.env.PROGRAMFILES, process.env['PROGRAMFILES(X86)']
].filter(Boolean);
const customChromePath = resolveChromePath();
if (customChromePath) {
installations.push(customChromePath);
}
prefixes.forEach(prefix => suffixes.forEach(suffix => {
const chromePath = path.join(prefix, suffix);
if (canAccess(chromePath)) {
installations.push(chromePath);
}
}));
return installations;
}
function sort(installations, priorities) {
const defaultPriority = 10;
return installations
// assign priorities
.map((inst) => {
for (const pair of priorities) {
if (pair.regex.test(inst)) {
return {path: inst, weight: pair.weight};
}
}
return {path: inst, weight: defaultPriority};
})
// sort based on priorities
.sort((a, b) => (b.weight - a.weight))
// remove priority flag
.map(pair => pair.path);
}
function canAccess(file) {
if (!file) {
return false;
}
try {
fs.accessSync(file);
return true;
} catch (e) {
return false;
}
}
function uniq(arr) {
return Array.from(new Set(arr));
}
function findChromeExecutables(folder) {
const argumentsRegex = /(^[^ ]+).*/; // Take everything up to the first space
const chromeExecRegex = '^Exec=\/.*\/(google-chrome|chrome|chromium)-.*';
let installations = [];
if (canAccess(folder)) {
// Output of the grep & print looks like:
// /opt/google/chrome/google-chrome --profile-directory
// /home/user/Downloads/chrome-linux/chrome-wrapper %U
let execPaths;
// Some systems do not support grep -R so fallback to -r.
// See https://github.com/GoogleChrome/chrome-launcher/issues/46 for more context.
try {
execPaths = execSync(`grep -ER "${chromeExecRegex}" ${folder} | awk -F '=' '{print $2}'`);
} catch (e) {
execPaths = execSync(`grep -Er "${chromeExecRegex}" ${folder} | awk -F '=' '{print $2}'`);
}
execPaths = execPaths.toString()
.split(newLineRegex)
.map((execPath) => execPath.replace(argumentsRegex, '$1'));
execPaths.forEach((execPath) => canAccess(execPath) && installations.push(execPath));
}
return installations;
}
function getLocalAppDataPath(path) {
const userRegExp = /\/mnt\/([a-z])\/Users\/([^\/:]+)\/AppData\//;
const results = userRegExp.exec(path) || [];
return `/mnt/${results[1]}/Users/${results[2]}/AppData/Local`;
}
function installations() {
if (process.platform === 'linux')
return linux();
if (process.platform === 'win32')
return win32();
if (process.platform === 'darwin')
return darwin();
return [];
}
module.exports = installations;
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const EventEmitter = require('events');
class Server {
constructor() {
this.lastObjectId_ = 0;
this.services_ = new Map();
this.objects_ = new Map();
}
/**
* @param {!Page} page
* @return {!Promise}
*/
async init(page) {
this.page_ = page;
await Promise.all([
this.page_.exposeFunction('rpcSend', this.onMessage_.bind(this)),
this.page_.evaluateOnNewDocument(installClient)
]);
}
registerService(c) {
this.services_.set(c.prototype.constructor.name, c);
}
async onMessage_(message) {
if (message.create) {
const c = this.services_.get(message.create);
const object = new c();
const nextId = ++this.lastObjectId_;
this.objects_.set(nextId, object);
object.emit = (method, ...args) => { this.sendMessage_({objectId: nextId, method, args})};
this.sendMessage_({
id: message.id,
result: { methods: this.describe_(object), objectId: nextId }
});
return;
}
if (message.dispose) {
this.objects_.delete(message.objectId);
return;
}
const object = this.objects_.get(message.objectId);
const result = await object[message.method](...message.args);
this.sendMessage_({id: message.id, objectId: message.objectId, result});
}
sendMessage_(message) {
this.page_.evaluate(message => self.rpc.dispatchMessage(message), message);
}
/**
* @param {!Object} o
*/
describe_(o) {
const proto = o.__proto__;
const methods = [];
for (const name in Object.getOwnPropertyDescriptors(proto)) {
if (name === 'constructor')
continue;
if (typeof proto[name] === 'function')
methods.push(name);
}
return methods;
}
}
function installClient() {
class EventEmitter {
constructor(objectId) {
this.objectId_ = objectId;
this.listeners_ = new Map();
}
on(event, handler) {
let listeners = this.listeners_.get(event);
if (!listeners) {
listeners = [];
this.listeners_.set(event, listeners);
}
listeners.push(handler);
}
off(event, handler) {
let listeners = this.listeners_.get(event);
if (!listeners)
return;
listeners = listeners.filter(a => a !== handler);
}
emit_(event, ...args) {
let listeners = this.listeners_.get(event);
if (!listeners)
return;
for (const listener of listeners)
listener(...args);
}
}
class Client {
constructor() {
this.lastId_ = 0;
this.callbacks_ = new Map();
this.objects_ = new Map();
}
async create(service) {
const result = await this.sendMessage_({create: service});
const object = new EventEmitter(result.objectId);
this.objects_.set(object.objectId_, object);
for (const method of result.methods)
object[method] = (...args) => this.sendMessage_({method, objectId: object.objectId_, args});
object.dispose = async () => {
this.sendMessage_({dispose: service, objectId: object.objectId_});
this.objects_.delete(nextId);
};
return object;
}
sendMessage_(message) {
message.id = ++this.lastId_;
let callback;
const result = new Promise(fulfil => this.callbacks_.set(message.id, fulfil));
rpcSend(message);
return result;
}
onMessage_(message) {
if (typeof message.id === 'number') {
this.callbacks_.get(message.id)(message.result);
return;
}
this.objects_.get(message.objectId).emit_(message.method, ...message.args);
}
}
const client = new Client();
self.rpc = {
create: service => client.create(service),
dispatchMessage: message => client.onMessage_(message),
};
}
module.exports = { Server };
{
"name": "carlo",
"version": "0.9.4",
"description": "Carlo is a framework for rendering Node data structures using Chrome browser.",
"repository": "github:GoogleChromeLabs/carlo",
"engines": {
"node": ">=7.6.0"
},
"directories": {
"lib": "lib"
},
"scripts": {
},
"keywords": [],
"author": "The Chromium Authors",
"license": "Apache-2.0",
"dependencies": {
"puppeteer-core": "^1.9.0"
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册