├── templates ├── skeleton │ ├── src │ │ ├── content │ │ │ ├── images │ │ │ │ ├── icon-32.png │ │ │ │ ├── icon-40.png │ │ │ │ ├── icon-48.png │ │ │ │ └── icon-128.png │ │ │ ├── popup.html │ │ │ ├── settings.html │ │ │ ├── translation.html │ │ │ ├── styles.scss │ │ │ ├── translation.jsx │ │ │ ├── popup.jsx │ │ │ └── settings.jsx │ │ ├── manifest.json │ │ └── background │ │ │ └── main.js │ ├── src-modules │ │ └── default-prefs.js │ └── locales │ │ └── en_US │ │ └── messages.json └── inspector │ ├── src │ ├── content │ │ ├── images │ │ │ ├── icon-128.png │ │ │ ├── icon-32.png │ │ │ ├── icon-40.png │ │ │ └── icon-48.png │ │ ├── inspector.html │ │ ├── settings.html │ │ ├── translation.html │ │ ├── translation.jsx │ │ ├── settings.jsx │ │ ├── styles.scss │ │ └── inspector.jsx │ ├── manifest.json │ └── background │ │ └── main.js │ ├── package.json │ ├── src-modules │ └── default-prefs.js │ └── locales │ └── en_US │ └── messages.json ├── .gitignore ├── index.js ├── src ├── weh-worker-rpc.js ├── css │ ├── weh-form-states.css │ ├── weh-header.css │ ├── weh-shf.css │ └── weh-natmsg-shell.scss ├── react │ ├── weh-header.jsx │ ├── weh-natmsg-shell.jsx │ ├── weh-prefs-settings.jsx │ └── weh-translation.jsx ├── weh.js ├── weh-i18n.js ├── weh-inspect.js ├── weh-worker.js ├── weh-content.js ├── weh-rpc.js ├── weh-background.js ├── weh-ui.js ├── weh-natmsg.js └── weh-prefs.js ├── package.json ├── README.md ├── gulpfile.js └── LICENSE.txt /templates/skeleton/src/content/images/icon-32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclap-dev/weh/HEAD/templates/skeleton/src/content/images/icon-32.png -------------------------------------------------------------------------------- /templates/skeleton/src/content/images/icon-40.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclap-dev/weh/HEAD/templates/skeleton/src/content/images/icon-40.png -------------------------------------------------------------------------------- /templates/skeleton/src/content/images/icon-48.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclap-dev/weh/HEAD/templates/skeleton/src/content/images/icon-48.png -------------------------------------------------------------------------------- /templates/inspector/src/content/images/icon-128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclap-dev/weh/HEAD/templates/inspector/src/content/images/icon-128.png -------------------------------------------------------------------------------- /templates/inspector/src/content/images/icon-32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclap-dev/weh/HEAD/templates/inspector/src/content/images/icon-32.png -------------------------------------------------------------------------------- /templates/inspector/src/content/images/icon-40.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclap-dev/weh/HEAD/templates/inspector/src/content/images/icon-40.png -------------------------------------------------------------------------------- /templates/inspector/src/content/images/icon-48.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclap-dev/weh/HEAD/templates/inspector/src/content/images/icon-48.png -------------------------------------------------------------------------------- /templates/skeleton/src/content/images/icon-128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aclap-dev/weh/HEAD/templates/skeleton/src/content/images/icon-128.png -------------------------------------------------------------------------------- /templates/inspector/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "weh-inspector", 3 | "version": "1.0.0", 4 | "dependencies": { 5 | "react-json-view": "^1.11.8" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | tmp/ 3 | npm-debug.log 4 | run-web-ext.sh 5 | inspector/ 6 | skeleton/ 7 | make-inspector.sh 8 | .DS_Store 9 | ._.DS_Store 10 | make-inspector-sign.sh 11 | inspector-tmp/ 12 | inspector-builds/ 13 | build-inspector-firefox.sh 14 | profile/ 15 | run-inspector.sh 16 | -------------------------------------------------------------------------------- /templates/skeleton/src/content/popup.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /templates/inspector/src/content/inspector.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /templates/inspector/src/content/settings.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /templates/skeleton/src/content/settings.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /templates/inspector/src/content/translation.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /templates/skeleton/src/content/translation.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | var spawn = require("child_process").spawn; 4 | 5 | var cwd = process.cwd(); 6 | process.chdir(__dirname); 7 | 8 | var gulpBin = process.platform=="win32" ? "gulp.cmd" : "gulp"; 9 | var cmd = spawn(gulpBin, process.argv.slice(2) , { 10 | env: Object.assign({},process.env,{ 11 | wehCwd: cwd 12 | }) 13 | }); 14 | 15 | cmd.stdout.on('data', function(data) { 16 | process.stdout.write(data); 17 | }); 18 | 19 | cmd.stderr.on('data', function(data) { 20 | process.stderr.write(data); 21 | }); 22 | 23 | cmd.on('close', function(code) { 24 | process.exit(code); 25 | }); 26 | -------------------------------------------------------------------------------- /templates/inspector/src-modules/default-prefs.js: -------------------------------------------------------------------------------- 1 | 2 | module.exports = [{ 3 | name: "messages_display_mode", 4 | type: "choice", 5 | defaultValue: "sync_reply", 6 | width: "20em", 7 | choices: ["async","sync_call","sync_reply"] 8 | },{ 9 | name: "display_timestamp", 10 | type: "boolean", 11 | defaultValue: false 12 | },{ 13 | name: "display_call_duration", 14 | type: "boolean", 15 | defaultValue: true 16 | },{ 17 | name: "max_messages", 18 | type: "integer", 19 | defaultValue: 100 20 | },{ 21 | name: "redux_logger", 22 | type: "boolean", 23 | defaultValue: false, 24 | hidden: true 25 | }]; 26 | -------------------------------------------------------------------------------- /src/weh-worker-rpc.js: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | /* setting up RPC */ 14 | const rpc = require('./weh-rpc'); 15 | 16 | /* connecting with main thread */ 17 | rpc.setPost(postMessage); 18 | global.onmessage = (event)=>{ 19 | rpc.receive(event.data, postMessage); 20 | }; 21 | 22 | module.exports = rpc; -------------------------------------------------------------------------------- /templates/skeleton/src/content/styles.scss: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | #root { 14 | min-width: 500px; 15 | } 16 | 17 | .sample-popup { 18 | .sample-panel { 19 | padding: 2em; 20 | font-size: 20pt; 21 | text-align: center; 22 | } 23 | .sample-toolbar { 24 | overflow: hidden; 25 | padding: 8px; 26 | background-color: #eee; 27 | a { 28 | float: right; 29 | cursor: pointer; 30 | margin: 0 8px; 31 | } 32 | } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /src/css/weh-form-states.css: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | .has-success .form-control { 14 | border-color: #5cb85c; 15 | } 16 | 17 | .has-success .col-form-label { 18 | color: #5cb85c; 19 | } 20 | 21 | .has-warning .form-control { 22 | border-color: #f0ad4e; 23 | } 24 | 25 | .has-warning .col-form-label { 26 | color: #f0ad4e; 27 | } 28 | 29 | .has-danger .form-control { 30 | border-color: #d9534f; 31 | } 32 | 33 | .has-danger .col-form-label { 34 | color: #d9534f; 35 | } 36 | -------------------------------------------------------------------------------- /templates/inspector/src/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "manifest_version": 2, 3 | "name": "Weh Inspector", 4 | "default_locale": "en_US", 5 | "version": "2.1.1", 6 | "version_name": "2.1.1", 7 | "author": "Michel Gutierrez", 8 | "description": "Trace remote procedure calls on Weh 2 addons", 9 | "background": { 10 | "scripts": [ 11 | "background/main.js" 12 | ], 13 | "persistent": true 14 | }, 15 | "icons": { 16 | "32": "content/images/icon-32.png", 17 | "40": "content/images/icon-40.png", 18 | "48": "content/images/icon-48.png", 19 | "128": "content/images/icon-128.png" 20 | }, 21 | "options_ui": { 22 | "page": "content/settings.html?panel=settings", 23 | "open_in_tab": false 24 | }, 25 | "permissions": [ 26 | "tabs", 27 | "contextMenus", 28 | "management", 29 | "storage", 30 | "downloads" 31 | ], 32 | "applications": { 33 | "gecko": { 34 | "id": "weh-inspector@downloadhelper.net" 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /templates/skeleton/src-modules/default-prefs.js: -------------------------------------------------------------------------------- 1 | 2 | module.exports = [{ 3 | name: "myparam_string", 4 | type: "string", 5 | defaultValue: "Default value", 6 | maxLength: 15, 7 | regexp: "^[a-zA-Z ]+$" 8 | },{ 9 | name: "myparam_integer", 10 | type: "integer", 11 | defaultValue: 42, 12 | minimum: -10, 13 | maximum: 100 14 | },{ 15 | name: "myparam_float", 16 | type: "float", 17 | defaultValue: 3.14159, 18 | minimum: 1.5, 19 | maximum: 10.8 20 | },{ 21 | name: "myparam_boolean", 22 | type: "boolean", 23 | defaultValue: true 24 | },{ 25 | name: "myparam_choice", 26 | type: "choice", 27 | defaultValue: "second", 28 | choices: [{ 29 | name: "First choice", 30 | value: "first" 31 | },{ 32 | name: "Second choice", 33 | value: "second" 34 | },{ 35 | name: "Third choice", 36 | value: "third" 37 | }] 38 | }]; 39 | -------------------------------------------------------------------------------- /templates/skeleton/src/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "manifest_version": 2, 3 | "name": "Skeleton React", 4 | "default_locale": "en_US", 5 | "version": "0.1", 6 | "version_name": "0.1", 7 | "author": "Michel Gutierrez", 8 | "description": "Basic add-on code to start from", 9 | "background": { 10 | "scripts": [ 11 | "background/main.js" 12 | ], 13 | "persistent": true 14 | }, 15 | "icons": { 16 | "32": "content/images/icon-32.png", 17 | "40": "content/images/icon-40.png", 18 | "48": "content/images/icon-48.png", 19 | "128": "content/images/icon-128.png" 20 | }, 21 | "browser_action": { 22 | "default_icon": { 23 | "40": "content/images/icon-40.png" 24 | }, 25 | "default_title": "WebExtensions Helper", 26 | "default_popup": "content/popup.html?panel=main" 27 | }, 28 | "options_ui": { 29 | "page": "content/settings.html?panel=settings", 30 | "open_in_tab": true 31 | }, 32 | "permissions": [ 33 | "tabs", 34 | "contextMenus", 35 | "storage" 36 | ] 37 | } -------------------------------------------------------------------------------- /src/css/weh-header.css: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | header { 14 | min-height: 42px; 15 | line-height: 42px; 16 | } 17 | 18 | header .weh-header-title { 19 | background-repeat: no-repeat; 20 | background-position: 8px center; 21 | background-size: contain; 22 | padding-left: 42px; 23 | font-weight: bold; 24 | font-size: 1.2em; 25 | } 26 | 27 | header .weh-header-close { 28 | font-weight: 100; 29 | font-size: 1.5em; 30 | line-height: 1.5em; 31 | cursor: pointer; 32 | color: #808080; 33 | padding: 0 12px 0 0; 34 | } 35 | 36 | header .weh-header-close:hover { 37 | color: #404040; 38 | } 39 | -------------------------------------------------------------------------------- /templates/skeleton/src/background/main.js: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | var weh = require('weh-background'); 14 | require('weh-inspect'); 15 | 16 | weh.rpc.listen({ 17 | openSettings: () => { 18 | console.info("openSettings"); 19 | weh.ui.open("settings",{ 20 | type: "tab", 21 | url: "content/settings.html" 22 | }); 23 | weh.ui.close("main"); 24 | }, 25 | openTranslation: () => { 26 | console.info("openTranslation"); 27 | weh.ui.open("translation",{ 28 | type: "tab", 29 | url: "content/translation.html" 30 | }); 31 | weh.ui.close("main"); 32 | }, 33 | }); 34 | 35 | weh.prefs.declare(require('default-prefs')); 36 | 37 | -------------------------------------------------------------------------------- /templates/inspector/src/content/translation.jsx: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | import React from 'react' 14 | import { render } from 'react-dom' 15 | import { Provider } from 'react-redux' 16 | import { applyMiddleware, createStore, combineReducers } from 'redux' 17 | import logger from 'redux-logger' 18 | import { reducer as translateReducer, WehTranslationForm } from 'react/weh-translation' 19 | 20 | import weh from 'weh-content'; 21 | 22 | let reducers = combineReducers({ 23 | translate: translateReducer 24 | }); 25 | 26 | let store = createStore(reducers, applyMiddleware(logger)); 27 | 28 | render( 29 | 30 | 31 | , 32 | document.getElementById('root') 33 | ); 34 | 35 | weh.setPageTitle(weh._("translation")); 36 | -------------------------------------------------------------------------------- /templates/skeleton/src/content/translation.jsx: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | import React from 'react' 14 | import { render } from 'react-dom' 15 | import { Provider } from 'react-redux' 16 | import { applyMiddleware, createStore, combineReducers } from 'redux' 17 | import logger from 'redux-logger' 18 | import { reducer as translateReducer, WehTranslationForm } from 'react/weh-translation' 19 | 20 | import weh from 'weh-content'; 21 | 22 | let reducers = combineReducers({ 23 | translate: translateReducer 24 | }); 25 | 26 | let store = createStore(reducers, applyMiddleware(logger)); 27 | 28 | render( 29 | 30 | 31 | , 32 | document.getElementById('root') 33 | ); 34 | 35 | weh.setPageTitle(weh._("translation")); 36 | -------------------------------------------------------------------------------- /src/css/weh-shf.css: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | /* 14 | * SHF = Sticky Header Footer = fixed header at top, footer at bottom with scrollable main content 15 | */ 16 | 17 | html, body { 18 | height: 100%; 19 | } 20 | 21 | body { 22 | overflow: hidden; 23 | } 24 | 25 | .weh-shf, .weh-shf > div, .weh-shf > div > div, .weh-shf > div > div > div, 26 | .weh-shf > div > div > div > div, .weh-shf > div > div > div > div > div { 27 | height: 100%; 28 | display: flex; 29 | flex-direction: column; 30 | } 31 | 32 | header { 33 | flex: 0 0 auto; 34 | background-color: #f8f8f8; 35 | } 36 | 37 | main { 38 | flex: 1 1 auto; 39 | position: relative; 40 | overflow-y: auto; 41 | height: 100%; 42 | } 43 | 44 | footer { 45 | flex: 0 0 auto; 46 | background-color: #f8f8f8; 47 | } 48 | -------------------------------------------------------------------------------- /templates/skeleton/src/content/popup.jsx: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | import React from 'react'; 14 | import { render } from 'react-dom'; 15 | 16 | import weh from 'weh-content'; 17 | 18 | class Link extends React.Component { 19 | 20 | constructor(props) { 21 | super(props); 22 | this.handleClick = this.handleClick.bind(this); 23 | } 24 | 25 | handleClick() { 26 | weh.rpc.call(this.props.messageCall); 27 | } 28 | 29 | render() { 30 | return ( 31 | {weh._(this.props.label)} 32 | ) 33 | } 34 | } 35 | 36 | render ( 37 |
38 |
{weh._("sample_panel_text")}
39 |
40 | 41 | 42 |
43 |
, 44 | document.getElementById('root') 45 | ) -------------------------------------------------------------------------------- /src/react/weh-header.jsx: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | import React from 'react'; 14 | import toolbarCss from 'css/weh-header.css'; 15 | import shfCss from 'css/weh-shf.css'; 16 | 17 | import weh from 'weh-content'; 18 | 19 | var manifest = weh.browser.runtime.getManifest(); 20 | 21 | export default class WehHeader extends React.Component { 22 | 23 | close() { 24 | weh.rpc.call("closePanel",weh.uiName); 25 | } 26 | 27 | render() { 28 | var title; 29 | if(this.props.title) 30 | title = this.props.title; 31 | else 32 | title = manifest.name; 33 | 34 | var titleStyle = { 35 | backgroundImage: "url("+(this.props.image || "images/icon-32.png")+")" 36 | } 37 | return ( 38 |
39 | 42 | {title} 43 | 44 | {"\u2297"} 45 | {this.props.children} 46 |
47 | ) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/css/weh-natmsg-shell.scss: -------------------------------------------------------------------------------- 1 | 2 | .natmsgsh { 3 | 4 | background-color: #f8f8f8; 5 | height: 100%; 6 | display: flex; 7 | flex-direction: column; 8 | 9 | .natmsgsh-result { 10 | flex: 1 1 auto; 11 | background-color: #fff; 12 | border-radius: 3px; 13 | margin: 3px 3px 0 3px; 14 | border: 1px solid #ddd; 15 | padding: 4px; 16 | overflow: auto; 17 | 18 | .natmsgsh-call { 19 | font-weight: 800; 20 | } 21 | .natmsgsh-return { 22 | color: #888; 23 | } 24 | .natmsgsh-error { 25 | color: #f88; 26 | } 27 | .natmsgsh-item { 28 | span.natmsgsh-ret-marker { 29 | margin-right: 8px; 30 | } 31 | .icon-container { 32 | font-size: 1.3em; 33 | } 34 | .object-container { 35 | font-size: .8em; 36 | } 37 | } 38 | 39 | .react-json-view.scalar-view { 40 | font-family: "Courier New", Courier, "Lucida Sans Typewriter", "Lucida Typewriter", monospace; 41 | display: inline-block; 42 | color: rgb(0, 43, 54); 43 | font-size: .9rem; 44 | } 45 | 46 | } 47 | 48 | .natmsgsh-input { 49 | flex: 0 0 auto; 50 | padding: 3px; 51 | display: flex; 52 | flex-direction: row; 53 | 54 | input { 55 | flex: 1 1 auto; 56 | } 57 | input.syntax-error { 58 | background-color: #f88; 59 | } 60 | input.syntax-ok { 61 | background-color: #8f8; 62 | } 63 | button { 64 | flex: 0 0 auto; 65 | margin-left: 3px; 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /templates/skeleton/locales/en_US/messages.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": { 3 | "message": "Weh Skeleton" 4 | }, 5 | "weh_prefs_label_myparam_string": { 6 | "message": "String parameter" 7 | }, 8 | "weh_prefs_description_myparam_string": { 9 | "message": "Only letters and spaces, 20 characters max" 10 | }, 11 | "weh_prefs_label_myparam_integer": { 12 | "message": "Integer parameter" 13 | }, 14 | "weh_prefs_description_myparam_integer": { 15 | "message": "Minimum -10, maximum 100" 16 | }, 17 | "weh_prefs_label_myparam_float": { 18 | "message": "Float parameter" 19 | }, 20 | "weh_prefs_description_myparam_float": { 21 | "message": "Minimum 1.5, maximum 10.8" 22 | }, 23 | "weh_prefs_label_myparam_boolean": { 24 | "message": "Boolean parameter" 25 | }, 26 | "weh_prefs_description_myparam_boolean": { 27 | "message": "This is a boolean" 28 | }, 29 | "weh_prefs_label_myparam_choice": { 30 | "message": "Choice parameter" 31 | }, 32 | "weh_prefs_description_myparam_choice": { 33 | "message": "Pick one option" 34 | }, 35 | 36 | "sample_panel_text": { 37 | "message": "Hello there !" 38 | }, 39 | "settings": { 40 | "message": "Settings" 41 | }, 42 | "translation": { 43 | "message": "Translation" 44 | }, 45 | 46 | "save": { 47 | "message": "Save" 48 | }, 49 | "cancel": { 50 | "message": "Cancel" 51 | }, 52 | "default": { 53 | "message": "Default" 54 | }, 55 | "version": { 56 | "message": "Version" 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/weh.js: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | exports.browser = require('webextension-polyfill'); 14 | 15 | var browserType; 16 | if(typeof browser == "undefined" && typeof chrome !== "undefined" && chrome.runtime) { 17 | if(/\bOPR\//.test(navigator.userAgent)) 18 | browserType = "opera"; 19 | else 20 | browserType = "chrome"; 21 | } else if(/\bEdge\//.test(navigator.userAgent)) 22 | browserType = "edge"; 23 | else 24 | browserType = "firefox"; 25 | exports.browserType = browserType; 26 | 27 | // Monkey-patching to support MV2 & MV3. 28 | // browser.action is a MV3 features equivalent to MV2' browserAction. 29 | // There doesn't seem to be a path-forward to support that in webextension-polyfill: 30 | // https://github.com/mozilla/webextension-polyfill/issues/329 31 | if (typeof exports.browser.action == "undefined") { 32 | exports.browser.action = exports.browser.browserAction; 33 | } 34 | 35 | exports.isBrowser = (...args) => { 36 | for(var i=0; i { 43 | console.groupCollapsed(err.message); 44 | if(err.stack) 45 | console.error(err.stack); 46 | console.groupEnd(); 47 | } 48 | -------------------------------------------------------------------------------- /src/weh-i18n.js: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | const { browser } = require('weh'); 14 | 15 | var customStrings = {} 16 | 17 | const SUBST_RE = new RegExp("\\$[a-zA-Z]*([0-9]+)\\$","g"); 18 | 19 | let has_loaded = false; 20 | let custom_strings_ready = browser.storage.local.get("wehI18nCustom").then((result) => { 21 | has_loaded = true; 22 | var weCustomStrings = result.wehI18nCustom; 23 | if (weCustomStrings) { 24 | Object.assign(customStrings, weCustomStrings); 25 | } 26 | }); 27 | 28 | function GetMessage(messageName,substitutions) { 29 | if (!has_loaded) { 30 | console.warn("Using `weh._` before custom strings were loaded:", messageName); 31 | } 32 | if(/-/.test(messageName)) { 33 | var fixedName = messageName.replace(/-/g,"_"); 34 | console.warn("Wrong i18n message name. Should it be",fixedName,"instead of",messageName,"?"); 35 | messageName = fixedName; 36 | } 37 | var custom = customStrings[messageName]; 38 | if(custom && custom.message.length>0) { 39 | if(!Array.isArray(substitutions)) 40 | substitutions = [ substitutions ]; 41 | var str = (custom.message || "").replace(SUBST_RE,(ph)=>{ 42 | var m = SUBST_RE.exec(ph); 43 | if(m) 44 | return substitutions[parseInt(m[1])-1] || "??"; 45 | else 46 | return "??"; 47 | }); 48 | return str; 49 | } 50 | return browser.i18n.getMessage.apply(browser.i18n,arguments); 51 | } 52 | 53 | module.exports = { 54 | getMessage: GetMessage, 55 | custom_strings_ready, 56 | } 57 | 58 | -------------------------------------------------------------------------------- /templates/inspector/locales/en_US/messages.json: -------------------------------------------------------------------------------- 1 | { 2 | "weh_inspector": { 3 | "message": "Weh Inspector" 4 | }, 5 | "rescan_addons": { 6 | "message": "Rescan addons" 7 | }, 8 | "messages_none": { 9 | "message": "No message" 10 | }, 11 | "clear_messages": { 12 | "message": "Clear messages" 13 | }, 14 | "storage": { 15 | "message": "Storage" 16 | }, 17 | "show_storage": { 18 | "message": "Storage" 19 | }, 20 | "get_prefs": { 21 | "message": "Preferences" 22 | }, 23 | "prefs": { 24 | "message": "Preferences" 25 | }, 26 | "prefs_save": { 27 | "message": "Save" 28 | }, 29 | "weh_prefs_label_messages_display_mode": { 30 | "message": "Messages display mode" 31 | }, 32 | "weh_prefs_description_messages_display_mode": { 33 | "message": "How calls/replies should be displayed" 34 | }, 35 | "weh_prefs_messages_display_mode_option_async": { 36 | "message": "Asynchronous" 37 | }, 38 | "weh_prefs_messages_display_mode_option_sync_call": { 39 | "message": "Synchronous (on call)" 40 | }, 41 | "weh_prefs_messages_display_mode_option_sync_reply": { 42 | "message": "Synchronous (on reply)" 43 | }, 44 | "weh_prefs_label_display_timestamp": { 45 | "message": "Display timestamp" 46 | }, 47 | "weh_prefs_description_display_timestamp": { 48 | "message": "Should the event timestamp be displayed" 49 | }, 50 | "weh_prefs_label_display_call_duration": { 51 | "message": "Display call duration" 52 | }, 53 | "weh_prefs_description_display_call_duration": { 54 | "message": "Should the call duration be displayed" 55 | }, 56 | "weh_prefs_label_max_messages": { 57 | "message": "Max messages" 58 | }, 59 | "weh_prefs_description_max_messages": { 60 | "message": "Maximum number of messages to be displayed (0=no limit)" 61 | }, 62 | "translation": { 63 | "message": "Translation" 64 | }, 65 | "save": { 66 | "message": "Save" 67 | }, 68 | "cancel": { 69 | "message": "Cancel" 70 | }, 71 | "default": { 72 | "message": "Default" 73 | }, 74 | "rpc_messages": { 75 | "message": "RPC messages" 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/weh-inspect.js: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | const weh = require('weh'); 14 | const wehRpc = require('weh-rpc'); 15 | const wehPrefs = require('weh-prefs'); 16 | 17 | var browser = weh.browser; 18 | 19 | var inspectorId = null; 20 | var inspect = null; 21 | var inspected = false; 22 | 23 | if(browser.runtime.onMessageExternal) { 24 | browser.runtime.onMessageExternal.addListener(function(message, sender, sendResponse) { 25 | switch(message.type) { 26 | case "weh#inspect-ping": 27 | inspectorId = sender.id; 28 | sendResponse({ 29 | type: "weh#inspect-pong", 30 | version: 1, 31 | manifest: browser.runtime.getManifest() 32 | }); 33 | break; 34 | case "weh#inspect": 35 | inspectorId = sender.id; 36 | inspected = message.inspected; 37 | if(inspected) 38 | wehRpc.setHook((message) => { 39 | if(inspected && inspectorId) 40 | browser.runtime.sendMessage(inspectorId,{ 41 | type: "weh#inspect-message", 42 | message 43 | }) 44 | .catch((err)=>{ 45 | console.info("Error sending message",err); 46 | inspected = false; 47 | }); 48 | }); 49 | else 50 | wehRpc.setHook(null); 51 | sendResponse({ 52 | type: "weh#inspect", 53 | version: 1, 54 | inspected 55 | }); 56 | break; 57 | case "weh#get-prefs": 58 | inspectorId = sender.id; 59 | sendResponse({ 60 | type: "weh#prefs", 61 | prefs: wehPrefs.getAll(), 62 | specs: wehPrefs.getSpecs() 63 | }); 64 | break; 65 | case "weh#set-pref": 66 | wehPrefs[message.pref] = message.value; 67 | sendResponse(true); 68 | break; 69 | } 70 | }); 71 | inspect = { 72 | send: () => { 73 | console.info("TODO implement inspect.send"); 74 | } 75 | } 76 | } 77 | 78 | module.exports = inspect; 79 | -------------------------------------------------------------------------------- /src/weh-worker.js: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | const rpc = require('weh-rpc'); 14 | 15 | class WehWorker { 16 | 17 | constructor(file, options = {}) { 18 | this.name = options.name || file; 19 | this.autoKill = (typeof options.autoKill !== "undefined") ? options.autoKill : false; 20 | this.autoKillTimer = null; 21 | this.file = file; 22 | this.callsInProgress = 0; 23 | this.postFn = this.post.bind(this); 24 | this.worker = null; 25 | if(options.startNow) 26 | this.ensureWorkerStarted(); 27 | } 28 | 29 | ensureWorkerStarted() { 30 | if(!this.worker) { 31 | var self = this; 32 | this.startKillTimer(); 33 | this.worker = new Worker(this.file); 34 | this.worker.onmessage = (event) => { 35 | rpc.receive(event.data,self.postFn,self.name); 36 | }; 37 | } 38 | } 39 | 40 | post(receiver,message) { 41 | this.ensureWorkerStarted(); 42 | this.worker.postMessage(message); 43 | } 44 | 45 | endKillTimer() { 46 | if(this.autoKillTimer) { 47 | clearTimeout(this.autoKillTimer); 48 | this.autoKillTimer = null; 49 | } 50 | } 51 | 52 | startKillTimer() { 53 | this.endKillTimer(); 54 | if(this.autoKill!==false) { 55 | var self = this; 56 | this.autoKillTimer = setTimeout(function() { 57 | self.worker.terminate(); 58 | self.worker = null; 59 | }, this.autoKill); 60 | } 61 | } 62 | 63 | callEnded() { 64 | this.callsInProgress--; 65 | if(this.callsInProgress===0) 66 | this.startKillTimer(); 67 | } 68 | 69 | call(...params) { 70 | var self = this; 71 | this.callsInProgress++; 72 | this.endKillTimer(); 73 | return rpc.call(this.postFn,this.name,...params) 74 | .then((result)=>{ 75 | self.callEnded(); 76 | return result; 77 | }) 78 | .catch((err)=>{ 79 | self.callEnded(); 80 | throw err; 81 | }); 82 | } 83 | 84 | } 85 | 86 | module.exports = (...params) => { 87 | return new WehWorker(...params); 88 | } 89 | /* 90 | export default (...params) => { 91 | return new WehWorker(...params); 92 | } 93 | */ 94 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "weh", 3 | "version": "2.14.0", 4 | "description": "Toolkit for developing WebExtensions add-ons on Firefox, Chrome, Edge, Opera and Vivaldi", 5 | "keywords": [ 6 | "webextensions", 7 | "add-on", 8 | "browser extension", 9 | "extension", 10 | "chrome", 11 | "firefox", 12 | "opera", 13 | "vivaldi", 14 | "edge", 15 | "react", 16 | "redux" 17 | ], 18 | "homepage": "https://github.com/mi-g/weh", 19 | "bugs": { 20 | "url": "https://github.com/mi-g/weh/issues" 21 | }, 22 | "license": "MPL-2.0", 23 | "author": { 24 | "name": "Michel Gutierrez", 25 | "email": "michel.gutierrez@gmail.com", 26 | "url": "https://github.com/mi-g" 27 | }, 28 | "repository": { 29 | "type": "git", 30 | "url": "https://github.com/mi-g/weh.git" 31 | }, 32 | "bin": { 33 | "weh": "./index.js" 34 | }, 35 | "scripts": { 36 | "test": "echo \"Error: no test specified\" && exit 1" 37 | }, 38 | "dependencies": { 39 | "@babel/core": "^7.14.3", 40 | "babel": "^6.23.0", 41 | "babel-loader": "^8.2.2", 42 | "babel-preset-es2015": "6.24.1", 43 | "babel-preset-react": "6.24.1", 44 | "bootstrap": "4.3.1", 45 | "css-loader": "^2.1.1", 46 | "file-loader": "^6.2.0", 47 | "gulp": "^4.0.2", 48 | "gulp-babel": "^6.1.3", 49 | "gulp-clean": "^0.4.0", 50 | "gulp-coffee": "^2.3.5", 51 | "gulp-debug": "^3.2.0", 52 | "gulp-ejs": "^3.1.2", 53 | "gulp-filter": "^7.0.0", 54 | "gulp-if": "^2.0.2", 55 | "gulp-install": "^1.1.0", 56 | "gulp-less": "^4.0.1", 57 | "gulp-rename": "^1.2.2", 58 | "gulp-sass": "^3.1.0", 59 | "gulp-sort": "^2.0.0", 60 | "gulp-sourcemaps": "^2.6.5", 61 | "gulp-stylus": "^2.7.0", 62 | "gulp-typescript": "^5.0.1", 63 | "gulp4-run-sequence": "^0.3.3", 64 | "install": "^0.10.4", 65 | "jquery": "^3.5.0", 66 | "json-stable-stringify": "^1.0.1", 67 | "lazypipe": "^1.0.1", 68 | "merge-stream": "^1.0.1", 69 | "npm": "^6.14.13", 70 | "popper.js": "^1.12.9", 71 | "react": "^16.2.0", 72 | "react-dom": "^16.14.0", 73 | "react-json-view": "^1.21.3", 74 | "react-redux": "^5.0.7", 75 | "redux": "^3.7.2", 76 | "redux-form": "^7.3.0", 77 | "redux-logger": "^3.0.6", 78 | "run-sequence": "^2.2.1", 79 | "style-loader": "^3.0.0", 80 | "terser-webpack-plugin": "^5.1.2", 81 | "through2": "^2.0.3", 82 | "typescript": "^2.7.2", 83 | "url-loader": "^1.1.2", 84 | "vinyl-buffer": "^1.0.1", 85 | "vinyl-named": "^1.1.0", 86 | "vinyl-source-stream": "^1.1.2", 87 | "vinyl-string": "^1.0.2", 88 | "webextension-polyfill": "^0.1.2", 89 | "webpack": "^5.74.0", 90 | "webpack-stream": "^6.1.2", 91 | "yargs": "^17.0.1" 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /templates/inspector/src/content/settings.jsx: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | import React from 'react' 14 | import { render } from 'react-dom' 15 | import { Provider } from 'react-redux' 16 | import { applyMiddleware, createStore, combineReducers } from 'redux' 17 | import { 18 | reducer as prefsSettingsReducer, 19 | App as PrefsSettingsApp, 20 | WehParam, 21 | WehPrefsControls, 22 | listenPrefs 23 | } from 'react/weh-prefs-settings' 24 | import logger from 'redux-logger' 25 | import WehHeader from 'react/weh-header'; 26 | import weh from 'weh-content'; 27 | 28 | import bootstrapStyles from 'bootstrap/dist/css/bootstrap.css' 29 | 30 | let reducers = combineReducers({ 31 | prefs: prefsSettingsReducer, 32 | }); 33 | let store = createStore(reducers, applyMiddleware(logger)); 34 | 35 | listenPrefs(store); 36 | 37 | function openTranslation() { 38 | weh.rpc.call("openTranslation") 39 | } 40 | 41 | function RenderControls() { 42 | return ( 43 |
44 | 49 |
50 | 55 | 60 | 65 |
66 |
67 | ) 68 | } 69 | 70 | render( 71 | 72 | 73 |
74 |
75 |
76 | 77 | 78 | 79 | 80 |
81 |
82 |
83 |
84 | 85 |
86 |
87 |
, 88 | document.getElementById('root') 89 | ) 90 | 91 | weh.setPageTitle(weh._("settings")); 92 | -------------------------------------------------------------------------------- /templates/skeleton/src/content/settings.jsx: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | import React from 'react' 14 | import { render } from 'react-dom' 15 | import { Provider } from 'react-redux' 16 | import { applyMiddleware, createStore, combineReducers } from 'redux' 17 | import { 18 | reducer as prefsSettingsReducer, 19 | App as PrefsSettingsApp, 20 | WehParam, 21 | WehPrefsControls, 22 | listenPrefs 23 | } from 'react/weh-prefs-settings' 24 | import logger from 'redux-logger' 25 | import WehHeader from 'react/weh-header'; 26 | 27 | import weh from 'weh-content'; 28 | 29 | import bootstrapStyles from 'bootstrap/dist/css/bootstrap.css' 30 | 31 | let reducers = combineReducers({ 32 | prefs: prefsSettingsReducer, 33 | }); 34 | let store = createStore(reducers, applyMiddleware(logger)); 35 | 36 | listenPrefs(store); 37 | 38 | function openTranslation() { 39 | weh.rpc.call("openTranslation") 40 | } 41 | 42 | function RenderControls() { 43 | return ( 44 |
45 | 50 |
51 | 56 | 61 | 66 |
67 |
68 | ) 69 | } 70 | 71 | render( 72 | 73 | 74 | 75 |
76 |
77 |
78 | 79 | 80 | 81 | 82 | 83 |
84 |
85 |
86 |
87 | 88 |
89 |
90 |
, 91 | document.getElementById('root') 92 | ) 93 | 94 | weh.setPageTitle(weh._("settings")); 95 | -------------------------------------------------------------------------------- /templates/inspector/src/content/styles.scss: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | #root { 14 | min-width: 500px; 15 | } 16 | 17 | :focus {outline:none;} 18 | ::-moz-focus-inner {border:0;} 19 | 20 | .sample-popup { 21 | .sample-panel { 22 | padding: 2em; 23 | font-size: 20pt; 24 | text-align: center; 25 | } 26 | .sample-toolbar { 27 | overflow: hidden; 28 | padding: 8px; 29 | background-color: #eee; 30 | a { 31 | float: right; 32 | cursor: pointer; 33 | margin: 0 8px; 34 | } 35 | } 36 | } 37 | 38 | .insp-msg:nth-child(even) { 39 | background-color: #f8f8f8; 40 | } 41 | 42 | .insp-msg { 43 | 44 | font-family: "Courier New", Courier, "Lucida Sans Typewriter", "Lucida Typewriter", monospace; 45 | 46 | .im-caller { 47 | color: #484; 48 | } 49 | .im-callee { 50 | color: #484; 51 | } 52 | .im-call-sign { 53 | margin: 0 4px; 54 | } 55 | .im-result-sign { 56 | margin: 0 4px 0 12px; 57 | } 58 | .im-error-sign { 59 | position: relative; 60 | top: 3px; 61 | margin: 0 8px; 62 | font-size: 1.5rem; 63 | } 64 | .im-error { 65 | color: #e44; 66 | } 67 | .im-method { 68 | color: #448; 69 | } 70 | .im-timestamp { 71 | margin: 0 12px 0 0; 72 | color: #888; 73 | font-size: .8rem; 74 | } 75 | .im-duration { 76 | margin: 0 0 0 8px; 77 | color: #888; 78 | font-size: .8rem; 79 | } 80 | .collapsed-icon { 81 | position: relative; 82 | top: 4px; 83 | left: 6px; 84 | } 85 | } 86 | 87 | .sel-addon { 88 | display: inline-flex; 89 | 90 | .sel-addon-id { 91 | font-family: "Courier New", Courier, "Lucida Sans Typewriter", "Lucida Typewriter", monospace; 92 | font-size: .7rem; 93 | margin: 0 8px; 94 | } 95 | } 96 | 97 | .commands { 98 | padding: 12px 0; 99 | 100 | li { 101 | list-style: none; 102 | 103 | a:not([href]):not([tabindex]) { 104 | color: #007bff; 105 | text-decoration: none; 106 | background-color: transparent; 107 | -ms-touch-action: manipulation; 108 | touch-action: manipulation; 109 | cursor: pointer; 110 | } 111 | 112 | a:hover:not([href]):not([tabindex]) { 113 | color: #0056b3; 114 | text-decoration: underline; 115 | } 116 | } 117 | } 118 | 119 | .prefs-table.table { 120 | 121 | font-family: "Courier New", Courier, "Lucida Sans Typewriter", "Lucida Typewriter", monospace; 122 | 123 | tr:nth-child(even) { 124 | background-color: #f8f8f8; 125 | } 126 | 127 | td { 128 | vertical-align: middle; 129 | } 130 | .pref-value { 131 | padding: 0 0 0 8px; 132 | } 133 | } 134 | 135 | .storage-table { 136 | 137 | font-family: "Courier New", Courier, "Lucida Sans Typewriter", "Lucida Typewriter", monospace; 138 | 139 | tr:nth-child(odd) { 140 | background-color: #f8f8f8; 141 | } 142 | 143 | tr.storage-type { 144 | background-color: #eee; 145 | font-weight: 800; 146 | font-size: 1.1rem; 147 | } 148 | } 149 | 150 | .no-message { 151 | color: #ccc; 152 | padding: 2em; 153 | } 154 | 155 | .insp-layout { 156 | 157 | .insp-main { 158 | display: flex; 159 | flex-direction: row; 160 | height: 100%; 161 | } 162 | 163 | .insp-left { 164 | flex: 0 0 auto; 165 | max-width: 200px; 166 | } 167 | 168 | .insp-content { 169 | flex: 1 1 auto; 170 | display: flex; 171 | flex-direction: column; 172 | } 173 | 174 | .insp-scrollable { 175 | overflow-y: auto; 176 | height: 100%; 177 | } 178 | 179 | .insp-container { 180 | flex: 1 1 auto; 181 | display: flex; 182 | flex-direction: column; 183 | height: 100%; 184 | } 185 | 186 | .insp-tabs { 187 | flex: 0 0 auto; 188 | } 189 | 190 | .insp-main-content { 191 | flex: 1 1 auto; 192 | height: 100%; 193 | overflow-y: auto; 194 | } 195 | 196 | } 197 | 198 | .react-json-view.scalar-view { 199 | font-family: "Courier New", Courier, "Lucida Sans Typewriter", "Lucida Typewriter", monospace; 200 | display: inline-block; 201 | color: rgb(0, 43, 54); 202 | font-size: .9rem; 203 | } 204 | 205 | .pref-edit { 206 | input { 207 | width: 100%; 208 | border: 0; 209 | background-color: #444; 210 | color: #fff; 211 | padding-left: .5em; 212 | } 213 | } 214 | 215 | .pref-edit.error { 216 | background-color: #f44; 217 | } 218 | 219 | -------------------------------------------------------------------------------- /src/weh-content.js: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | var weh = require('weh'); 14 | var browser = weh.browser; 15 | 16 | /* extracting running parameters from URL */ 17 | var urlParams = typeof _wehPanelName !== "undefined" && { panel: _wehPanelName } || function () { 18 | var m = /^([^\?]*)(?:\?(.*))?$/.exec(window.location.href); 19 | var params = {}; 20 | if (m[2]) m[2].split("&").forEach(function (paramExpr) { 21 | var terms = paramExpr.split("="); 22 | params[terms[0]] = decodeURIComponent(terms[1]); 23 | }); 24 | return params; 25 | }(); 26 | 27 | if (!urlParams.panel) throw new Error("Panel name not defined in URL"); 28 | 29 | weh.uiName = urlParams.panel; 30 | 31 | /* setting up RPC */ 32 | weh.rpc = require('weh-rpc'); 33 | //weh.rpc.setDebug(2); 34 | weh.rpc.listen({ 35 | close: () => { 36 | window.close() 37 | } 38 | }) 39 | 40 | /* connecting communication port with background */ 41 | var port = browser.runtime.connect({ name: "weh:" + browser.runtime.id + ":" + weh.uiName }); 42 | weh.rpc.setPost(port.postMessage.bind(port)); 43 | port.onMessage.addListener((message) => { 44 | weh.rpc.receive(message, port.postMessage.bind(port)); 45 | }); 46 | 47 | /* notify background app is started */ 48 | weh.rpc.call("appStarted", { 49 | uiName: weh.uiName, 50 | }).catch(function (err) { 51 | console.info("appStarted failed", err); 52 | }); 53 | 54 | /* initializing */ 55 | let onDOMLoaded = new Promise((resolve, _) => { 56 | window.addEventListener("DOMContentLoaded", resolve); 57 | }); 58 | 59 | weh.unsafe_prefs = require('weh-prefs'); 60 | weh.prefs = (async () => { 61 | let wehPrefs = weh.unsafe_prefs; 62 | let entries = await browser.storage.local.get("weh-prefs"); 63 | let initialPrefs = entries["weh-prefs"] || {}; 64 | wehPrefs.assign(initialPrefs); 65 | wehPrefs.on("", { pack: true }, (newPrefs, oldPrefs) => { 66 | weh.rpc.call("prefsSet",newPrefs); 67 | }); 68 | weh.rpc.listen({ setPrefs: (prefs) => { 69 | wehPrefs.assign(prefs); 70 | } }); 71 | let specs = await weh.rpc.call("prefsGetSpecs"); 72 | wehPrefs.declare(specs); 73 | let all_prefs = await weh.rpc.call("prefsGetAll"); 74 | wehPrefs.assign(all_prefs); 75 | wehPrefs.forceNotify(false); 76 | return wehPrefs; 77 | })(); 78 | 79 | /* setting up translation */ 80 | let i18n = require("weh-i18n"); 81 | weh._ = i18n.getMessage; 82 | 83 | /* notifies app ready: DOM and prefs, if used, are loaded */ 84 | // weh.is_safe is a promise which will return when weh 85 | // is safe to use. 86 | weh.is_safe = (async () => { 87 | await onDOMLoaded; 88 | await weh.prefs; 89 | await i18n.custom_strings_ready; 90 | await weh.rpc.call("appReady", { 91 | uiName: weh.uiName 92 | }); 93 | appStarted = true; 94 | try { 95 | if(triggerRequested) { 96 | let result = triggerArgs; 97 | triggerArgs = undefined; 98 | triggerRequested = false; 99 | weh.doTrigger(result); 100 | } 101 | } catch (err) { 102 | console.error("app not ready:",err); 103 | } 104 | })(); 105 | 106 | var triggerRequested = false; 107 | var triggerArgs = undefined; 108 | var appStarted = false; 109 | 110 | weh.doTrigger = function (result) { 111 | return weh.rpc.call("trigger",weh.uiName,result) 112 | .catch(()=>{}); 113 | } 114 | 115 | weh.trigger = function (result) { 116 | if(appStarted) 117 | return weh.doTrigger(result); 118 | else { 119 | triggerArgs = result; 120 | triggerRequested = true; 121 | } 122 | } 123 | 124 | /* utility functions */ 125 | weh.copyToClipboard = function (data, mimeType) { 126 | mimeType = mimeType || "text/plain"; 127 | document.oncopy = function (event) { 128 | event.clipboardData.setData(mimeType, data); 129 | event.preventDefault(); 130 | }; 131 | document.execCommand("Copy", false, null); 132 | }; 133 | weh.setPageTitle = function (title) { 134 | var titleElement = document.querySelector("head title"); 135 | if (!titleElement) { 136 | titleElement = document.createElement("title"); 137 | document.head.appendChild(titleElement); 138 | } else while (titleElement.firstChild) 139 | titleElement.removeChild(titleElement.firstChild); 140 | titleElement.appendChild(document.createTextNode(title)); 141 | }; 142 | 143 | module.exports = weh; 144 | -------------------------------------------------------------------------------- /templates/inspector/src/background/main.js: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | var weh = require('weh-background'); 14 | 15 | var browser = weh.browser; 16 | 17 | var allowFromAddonId = null; 18 | 19 | weh.rpc.listen({ 20 | openSettings: () => { 21 | weh.ui.open("settings",{ 22 | type: "tab", 23 | url: "content/settings.html" 24 | }); 25 | weh.ui.close("main"); 26 | }, 27 | openTranslation: () => { 28 | weh.ui.open("translation",{ 29 | type: "tab", 30 | url: "content/translation.html" 31 | }); 32 | weh.ui.close("main"); 33 | }, 34 | getAddons: () => { 35 | return new Promise((resolve,reject)=>{ 36 | if(!browser.management) 37 | return reject(new Error("Browser management not available")); 38 | browser.management.getAll() 39 | .then((extensions) => { 40 | Promise.all(extensions.map(CheckAddon)) 41 | .then((addons)=>{ 42 | resolve(addons.filter((addon)=>{ 43 | return addon!==null; 44 | })) 45 | }) 46 | .catch(reject); 47 | }) 48 | .catch(reject); 49 | }); 50 | }, 51 | updateMonitoredAddon: (newAddonId,oldAddonId) => { 52 | allowFromAddonId = newAddonId; 53 | if(oldAddonId && oldAddonId!=newAddonId) 54 | browser.runtime.sendMessage(oldAddonId,{ 55 | type: "weh#inspect", 56 | inspected: false 57 | }); 58 | if(newAddonId) 59 | browser.runtime.sendMessage(newAddonId,{ 60 | type: "weh#inspect", 61 | inspected: true 62 | }); 63 | }, 64 | getPrefs: (addonId) => { 65 | return new Promise((resolve,reject) => { 66 | browser.runtime.sendMessage(addonId,{ 67 | type: "weh#get-prefs" 68 | }) 69 | .then((response) => { 70 | if(!response) 71 | reject(new Error("No addon answer")); 72 | else 73 | resolve(response); 74 | }) 75 | .catch(reject); 76 | }) 77 | }, 78 | getStorage: (addonId) => { 79 | return new Promise((resolve,reject) => { 80 | browser.runtime.sendMessage(addonId,{ 81 | type: "weh#get-storage" 82 | }) 83 | .then((response) => { 84 | if(!response) 85 | reject(new Error("No addon answer")); 86 | else 87 | resolve(response); 88 | }) 89 | .catch(reject); 90 | }) 91 | }, 92 | setAddonPref: (pref,value,addonId) => { 93 | return new Promise((resolve,reject) => { 94 | browser.runtime.sendMessage(addonId,{ 95 | type: "weh#set-pref", 96 | pref, 97 | value 98 | }) 99 | .then((response) => { 100 | if(!response) 101 | reject(new Error("No addon answer")); 102 | else 103 | resolve(response); 104 | }) 105 | .catch(reject); 106 | }) 107 | } 108 | }); 109 | 110 | function CheckNewAddon(addon) { 111 | if(addon.id==allowFromAddonId) { 112 | var counter=0; 113 | function Connect() { 114 | if(counter++>100) 115 | return; 116 | browser.runtime.sendMessage(addon.id,{ 117 | type: "weh#inspect", 118 | inspected: true 119 | }) 120 | .then((response)=>{ 121 | if(!response) 122 | setTimeout(Connect,100); 123 | }) 124 | .catch((err)=>{ 125 | setTimeout(Connect,100); 126 | }); 127 | } 128 | Connect(); 129 | } 130 | } 131 | 132 | function SetupContextMenu() { 133 | browser.contextMenus.create({ 134 | "title": weh._("weh_inspector"), 135 | "type": "normal", 136 | "contexts":["page"], 137 | "id": "weh-inspector" 138 | }); 139 | } 140 | 141 | SetupContextMenu(); 142 | 143 | function CheckAddon(extension) { 144 | var id = extension.id; 145 | return new Promise((resolve,reject)=>{ 146 | browser.runtime.sendMessage(id,{ 147 | type: "weh#inspect-ping" 148 | }) 149 | .then((response) => { 150 | if(response && response.type=="weh#inspect-pong") { 151 | resolve(Object.assign({},response.manifest,{ id })); 152 | } else { 153 | resolve(null); 154 | } 155 | }) 156 | .catch(()=>{ 157 | resolve(null); 158 | }); 159 | }); 160 | } 161 | 162 | browser.contextMenus.onClicked.addListener(function(info) { 163 | if(info.menuItemId == "weh-inspector" ) { 164 | weh.ui.open("inspector",{ 165 | type: "tab", 166 | url: "content/inspector.html" 167 | }); 168 | } 169 | }); 170 | 171 | browser.runtime.onMessageExternal.addListener(function(message, sender, sendResponse) { 172 | switch(message.type) { 173 | case "weh#inspect-message": 174 | if(sender.id===allowFromAddonId) 175 | weh.rpc.call("inspector","newMessage",message.message); 176 | break; 177 | case "weh#storage": 178 | if(sender.id===allowFromAddonId) 179 | weh.rpc.call("inspector","setAddonStorage",message); 180 | break; 181 | } 182 | sendResponse(true); 183 | }); 184 | 185 | weh.prefs.declare(require('default-prefs')); 186 | 187 | if(browser.management.onInstalled) 188 | browser.management.onInstalled.addListener(CheckNewAddon); 189 | if(browser.management.onEnabled) 190 | browser.management.onEnabled.addListener(CheckNewAddon); 191 | -------------------------------------------------------------------------------- /src/weh-rpc.js: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | class RPC { 14 | 15 | constructor() { 16 | this.replyId = 0; 17 | this.replies = {}; 18 | this.listeners = {}; 19 | this.hook = this.nullHook; 20 | this.debugLevel = 0; 21 | this.useTarget = false; 22 | this.logger = console; 23 | this.posts = {}; 24 | } 25 | 26 | setPost(arg1, arg2) { 27 | if(typeof arg1=="string") 28 | this.posts[arg1] = arg2; 29 | else 30 | this.post = arg1; 31 | } 32 | 33 | setUseTarget(useTarget) { 34 | this.useTarget = useTarget; 35 | } 36 | 37 | setDebugLevel(_debugLevel) { 38 | this.debugLevel = _debugLevel; 39 | } 40 | 41 | setHook(hook) { 42 | var self = this; 43 | var timestamp0 = Date.now(); 44 | function Now() { 45 | if(typeof window!="undefined" && typeof window.performance!="undefined") 46 | return window.performance.now(); 47 | else 48 | return Date.now() - timestamp0; 49 | } 50 | if(hook) 51 | this.hook = (message) => { 52 | message.timestamp = Now(); 53 | try { 54 | hook(message); 55 | } catch(e) { 56 | self.logger.warn("Hoor error",e); 57 | } 58 | } 59 | else 60 | this.hook = this.nullHook; 61 | } 62 | 63 | nullHook() {} 64 | 65 | call() { 66 | var self = this; 67 | var _post, receiver, method, args; 68 | var _arguments = Array.prototype.slice.call(arguments); 69 | if(typeof _arguments[0]=="function") 70 | _post = _arguments.shift(); 71 | if (self.useTarget) 72 | [receiver, method, ...args] = _arguments; 73 | else 74 | [method, ...args] = _arguments; 75 | var promise = new Promise(function (resolve, reject) { 76 | var rid = ++self.replyId; 77 | if (self.debugLevel >= 2) 78 | self.logger.info("rpc #" + rid, "call =>", method, args); 79 | self.hook({ 80 | type: "call", 81 | callee: receiver, 82 | rid, 83 | method, 84 | args 85 | }); 86 | self.replies[rid] = { 87 | resolve: resolve, 88 | reject: reject, 89 | peer: receiver 90 | } 91 | var post = _post || (self.useTarget && self.posts[receiver]) || self.post; 92 | if(self.useTarget) { 93 | post(receiver,{ 94 | type: "weh#rpc", 95 | _request: rid, 96 | _method: method, 97 | _args: [...args] 98 | }); 99 | } else 100 | post({ 101 | type: "weh#rpc", 102 | _request: rid, 103 | _method: method, 104 | _args: [...args] 105 | }); 106 | }); 107 | return promise; 108 | } 109 | 110 | receive(message,send,peer) { 111 | var self = this; 112 | if (message._request) 113 | Promise.resolve() 114 | .then(() => { 115 | var method = self.listeners[message._method]; 116 | if (typeof method == "function") { 117 | if (self.debugLevel >= 2) 118 | self.logger.info("rpc #" + message._request, "serve <= ", message._method, message._args); 119 | self.hook({ 120 | type: "call", 121 | caller: peer, 122 | rid: message._request, 123 | method: message._method, 124 | args: message._args 125 | }); 126 | return Promise.resolve(method.apply(null, message._args)) 127 | .then((result)=>{ 128 | self.hook({ 129 | type: "reply", 130 | caller: peer, 131 | rid: message._request, 132 | result: result 133 | }); 134 | return result; 135 | }) 136 | .catch((error)=>{ 137 | self.hook({ 138 | type: "reply", 139 | caller: peer, 140 | rid: message._request, 141 | error: error.message 142 | }); 143 | throw error; 144 | }) 145 | } else 146 | throw new Error("Method " + message._method + " is not a function"); 147 | }) 148 | .then((result) => { 149 | if (self.debugLevel >= 2) 150 | self.logger.info("rpc #" + message._request, "serve => ", result); 151 | send({ 152 | type: "weh#rpc", 153 | _reply: message._request, 154 | _result: result 155 | }); 156 | }) 157 | .catch((error) => { 158 | if (self.debugLevel >= 1) 159 | self.logger.info("rpc #" + message._request, "serve => !", error.message); 160 | send({ 161 | type: "weh#rpc", 162 | _reply: message._request, 163 | _error: error.message 164 | }); 165 | }); 166 | else if (message._reply) { 167 | var reply = self.replies[message._reply]; 168 | delete self.replies[message._reply]; 169 | if (!reply) 170 | self.logger.error("Missing reply handler"); 171 | else if (message._error) { 172 | if (self.debugLevel >= 1) 173 | self.logger.info("rpc #" + message._reply, "call <= !", message._error); 174 | self.hook({ 175 | type: "reply", 176 | callee: reply.peer, 177 | rid: message._reply, 178 | error: message._error 179 | }); 180 | reply.reject(new Error(message._error)); 181 | } else { 182 | if (self.debugLevel >= 2) 183 | self.logger.info("rpc #" + message._reply, "call <= ", message._result); 184 | self.hook({ 185 | type: "reply", 186 | callee: reply.peer, 187 | rid: message._reply, 188 | result: message._result 189 | }); 190 | reply.resolve(message._result); 191 | } 192 | } 193 | } 194 | 195 | listen(listener) { 196 | Object.assign(this.listeners,listener); 197 | } 198 | 199 | } 200 | 201 | module.exports = new RPC(); 202 | 203 | 204 | 205 | -------------------------------------------------------------------------------- /src/weh-background.js: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | var weh = require('weh'); 14 | var browser = weh.browser; 15 | 16 | var apps = {}; 17 | 18 | weh.rpc = require('weh-rpc'); 19 | //weh.rpc.setDebug(2); 20 | weh.rpc.setUseTarget(true); 21 | 22 | weh.rpc.setPost((app,message)=>{ 23 | var appOptions = apps[app]; 24 | if(appOptions && appOptions.port) 25 | appOptions.port.postMessage(message); 26 | }); 27 | 28 | weh.rpc.listen({ 29 | appStarted: (options) => { 30 | }, 31 | appReady: (app) => { 32 | }, 33 | closePanel: (app) => { 34 | weh.ui.close(app); 35 | } 36 | }); 37 | 38 | browser.runtime.onConnect.addListener((port) => { 39 | var m = /^weh:(.*?):(.*)/.exec(port.name); 40 | if(!m) 41 | return; 42 | port.onMessage.addListener((message) => { 43 | if(typeof message._method !== "undefined" && (message._method==="appStarted" || message._method==="appReady")) { 44 | var app = message._args[0] && message._args[0].uiName || null; 45 | var appOptions = apps[app] || { 46 | ready: false 47 | }; 48 | apps[app] = appOptions; 49 | Object.assign(appOptions,message._args[0],{ port: port }); 50 | if(message._method=="appReady") { 51 | appOptions.ready = true; 52 | if(appOptions.initData) 53 | setTimeout(()=>{ 54 | weh.rpc.call(app,"wehInitData",appOptions.initData); 55 | },0); 56 | var wait = waiting[app]; 57 | if(wait && wait.timer) { 58 | clearTimeout(wait.timer); 59 | delete wait.timer; 60 | } 61 | } 62 | port._weh_app = app; 63 | 64 | } 65 | weh.rpc.receive(message,port.postMessage.bind(port),port._weh_app); 66 | }); 67 | port.onDisconnect.addListener(() => { 68 | var app = port._weh_app; 69 | if(app) { 70 | delete apps[app]; 71 | var wait = waiting[app]; 72 | if(wait) { 73 | if(wait.timer) 74 | clearTimeout(wait.timer); 75 | delete waiting[app]; 76 | wait.reject(new Error("Disconnected waiting for "+app)); 77 | } 78 | } 79 | }); 80 | }); 81 | 82 | weh.__declareAppTab = function(app,data) { 83 | if(!apps[app]) 84 | apps[app] = {}; 85 | Object.assign(apps[app],data); 86 | } 87 | 88 | weh.__closeByTab = function(tabId) { 89 | Object.keys(apps).forEach((app)=>{ 90 | var appOptions = apps[app]; 91 | if(appOptions.tab===tabId) { 92 | delete apps[app]; 93 | var wait = waiting[app]; 94 | if(wait) { 95 | if(wait.timer) 96 | clearTimeout(wait.timer); 97 | delete waiting[app]; 98 | wait.reject(new Error("Disconnected waiting for "+app)); 99 | } 100 | } 101 | }); 102 | } 103 | 104 | weh._ = require('weh-i18n').getMessage; 105 | weh.ui = require('weh-ui'); 106 | weh.openedContents = () => Object.keys(apps); 107 | 108 | function Hash(str){ 109 | var hash = 0, char; 110 | if (str.length === 0) return hash; 111 | for(var i=0; i { 142 | let wehPrefs = weh.unsafe_prefs; 143 | let prefs = entries["weh-prefs"] || {}; 144 | wehPrefs.assign(prefs); 145 | wehPrefs.on("",{ 146 | pack: true 147 | }, function(newPrefs,oldPrefs) { 148 | Object.assign(prefs,newPrefs); 149 | var prefsStr = Stringify(prefs); 150 | var hash = Hash(prefsStr); 151 | if(hash!=lastHash) { 152 | lastHash = hash; 153 | browser.storage.local.set({ 154 | "weh-prefs": prefs 155 | }); 156 | } 157 | Object.keys(apps).forEach((app)=>{ 158 | var appOptions = apps[app]; 159 | weh.rpc.call(app,"setPrefs",newPrefs); 160 | }); 161 | }); 162 | return wehPrefs; 163 | }).catch(e => { 164 | console.error("web-background error:", e); 165 | }); 166 | 167 | const waiting = {}; 168 | 169 | weh.wait = (id,options={}) => { 170 | var wait = waiting[id]; 171 | if(wait) { 172 | if(wait.timer) 173 | clearTimeout(wait.timer); 174 | delete waiting[id]; 175 | wait.reject(new Error("Waiter for "+id+" overriden")); 176 | } 177 | return new Promise((resolve, reject) => { 178 | waiting[id] = { 179 | resolve, 180 | reject, 181 | timer: setTimeout(()=>{ 182 | delete waiting[id]; 183 | reject(new Error("Waiter for "+id+" timed out")); 184 | }, options.timeout || 60000) 185 | } 186 | }); 187 | } 188 | 189 | weh.rpc.listen({ 190 | prefsGetAll: async () => { 191 | let wehPrefs = await weh.prefs; 192 | return wehPrefs.getAll(); 193 | }, 194 | prefsGetSpecs: async () => { 195 | let wehPrefs = await weh.prefs; 196 | return wehPrefs.getSpecs(); 197 | }, 198 | prefsSet: async (prefs) => { 199 | let wehPrefs = await weh.prefs; 200 | return wehPrefs.assign(prefs); 201 | }, 202 | trigger: (id,result) => { 203 | var wait = waiting[id]; 204 | if(!wait) 205 | throw new Error("No waiter for",id); 206 | if(wait.timer) { 207 | clearTimeout(wait.timer); 208 | delete wait.timer; 209 | } 210 | delete waiting[id]; 211 | wait.resolve(result); 212 | } 213 | }); 214 | 215 | 216 | module.exports = weh; 217 | -------------------------------------------------------------------------------- /src/react/weh-natmsg-shell.jsx: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | import React from 'react' 14 | import ReactJson from 'react-json-view'; 15 | import natmsgshStyles from '../css/weh-natmsg-shell.css'; 16 | import weh from 'weh-content'; 17 | import rpc from 'weh-rpc'; 18 | 19 | export class NativeMessagingShell extends React.Component { 20 | 21 | constructor(props) { 22 | super(props); 23 | this.state = { 24 | className: "", 25 | method: null, 26 | args: null, 27 | items: [] 28 | }; 29 | this.itemIndex = 0; 30 | this.history = []; 31 | this.historyIndex = 0; 32 | this.handleChange = this.handleChange.bind(this); 33 | this.handleKeyDown = this.handleKeyDown.bind(this); 34 | this.clear = this.clear.bind(this); 35 | } 36 | 37 | resetInput() { 38 | this.input.value = ""; 39 | this.setState({ 40 | className: "", 41 | method: null, 42 | args: null 43 | }); 44 | } 45 | 46 | clear() { 47 | this.setState({ 48 | items: [] 49 | }); 50 | } 51 | 52 | handleChange(event) { 53 | var value = this.input.value.trim(); 54 | var className = "", method = null, args = null; 55 | if(value.length) { 56 | className = "syntax-error"; 57 | var parts = /^\s*([^\s\(\)]+)\s*\((.*)\)\s*$/.exec(value); 58 | if(parts) { 59 | var argsStr = "[" + parts[2] +"]"; 60 | try { 61 | args = JSON.parse(argsStr); 62 | method = parts[1]; 63 | className = "syntax-ok" 64 | } catch(e) {} 65 | } 66 | } 67 | this.setState({ 68 | className: className, 69 | method: method, 70 | args: args 71 | }); 72 | } 73 | 74 | addItem(item) { 75 | item = Object.assign({},item,{ 76 | key: ++this.itemIndex 77 | }); 78 | this.setState({ 79 | items: this.state.items.concat([item]) 80 | }) 81 | } 82 | 83 | handleKeyDown(event) { 84 | var self = this; 85 | if(event.keyCode==13 && this.state.method) { 86 | this.history.push({ 87 | method: this.state.method, 88 | args: this.state.args 89 | }); 90 | this.historyIndex = this.history.push(); 91 | this.addItem({ 92 | type: "call", 93 | method: this.state.method, 94 | args: this.state.args 95 | }); 96 | rpc.call(this.props.proxyFnName,this.state.method,...this.state.args) 97 | .then((result)=>{ 98 | console.info("result",result); 99 | self.addItem({ 100 | type: "result", 101 | result 102 | }); 103 | }) 104 | .catch((error)=>{ 105 | console.info("error",error); 106 | self.addItem({ 107 | type: "error", 108 | error 109 | }); 110 | }); 111 | this.resetInput(); 112 | } 113 | if(event.keyCode==38 && this.historyIndex>0) { 114 | let entry = this.history[--this.historyIndex]; 115 | this.setState({ 116 | method: entry.method, 117 | args: entry.args, 118 | className: "syntax-ok", 119 | }); 120 | this.input.value = this.entryString(entry); 121 | } 122 | if(event.keyCode==40 && this.historyIndexJSON.stringify(arg)).join(", ")+")"; 138 | } 139 | 140 | scrollToBottom() { 141 | this.itemsEnd.scrollIntoView({ behavior: "smooth" }); 142 | } 143 | 144 | componentDidMount() { 145 | this.scrollToBottom(); 146 | } 147 | 148 | componentDidUpdate() { 149 | this.scrollToBottom(); 150 | } 151 | 152 | renderJson(obj) { 153 | switch(typeof obj) { 154 | case "undefined": 155 | return ( 156 |
157 | no explicit return value 158 |
159 | ); 160 | case "number": 161 | case "string": 162 | case "boolean": 163 | return ( 164 |
165 | {JSON.stringify(obj)} 166 |
167 | ); 168 | } 169 | return ( 170 | 179 | ) 180 | } 181 | 182 | render() { 183 | var self = this; 184 | var items = this.state.items.map((item)=>{ 185 | return ( 186 |
187 | { item.type == 'call' && ( 188 |
189 | {self.entryString(item)} 190 |
191 | )} 192 | { item.type == 'result' && ( 193 |
194 | 195 | { self.renderJson(item.result) } 196 |
197 | )} 198 | { item.type == 'error' && ( 199 |
200 | 201 | { item.error.message } 202 |
203 | )} 204 |
205 | ) 206 | }); 207 | return ( 208 |
209 |
210 | {items} 211 |
{ this.itemsEnd = el; }}> 213 |
214 |
215 |
216 | this.input = input} 218 | className={this.state.className} 219 | onChange={this.handleChange} 220 | placeholder="RPC call as: method(arg1,arg2)" 221 | onKeyDown={this.handleKeyDown} 222 | type="text" 223 | /> 224 | 228 | 230 |
231 |
232 | ) 233 | } 234 | } 235 | -------------------------------------------------------------------------------- /src/weh-ui.js: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | var weh = require('weh'); 14 | var wehRpc = require('weh-rpc'); 15 | 16 | var browser = weh.browser; 17 | var panels = {}; 18 | var tabs = {}; 19 | 20 | function Open(name,options) { 21 | switch(options.type) { 22 | case "panel": 23 | return OpenPanel(name,options); 24 | break; 25 | case "tab": 26 | default: 27 | return OpenTab(name,options); 28 | } 29 | } 30 | 31 | function OpenTab(name,options) { 32 | return new Promise((resolve, reject) => { 33 | var url = browser.runtime.getURL(options.url+"?panel="+name); 34 | GotoTab(url) 35 | .then(function(foundTab) { 36 | if(!foundTab) 37 | return browser.tabs.create({ 38 | url: url, 39 | }) 40 | .then(function(tab) { 41 | weh.__declareAppTab(name,{tab:tab.id,initData:options.initData}); 42 | panels[name] = { 43 | type: "tab", 44 | tabId: tab.id 45 | } 46 | tabs[tab.id] = name; 47 | }); 48 | }) 49 | .then(resolve) 50 | .catch(reject); 51 | }) 52 | } 53 | 54 | function CreatePanel(name,options) { 55 | return new Promise((resolve, reject) => { 56 | var url = browser.runtime.getURL(options.url+"?panel="+name); 57 | 58 | browser.windows.getCurrent() 59 | .then((currentWindow) => { 60 | var width = options.width || 500; 61 | var height = options.height || 400; 62 | var cwcParam = { 63 | url, 64 | width, 65 | height, 66 | type: "popup", 67 | left: Math.round((currentWindow.width-width)/2+currentWindow.left), 68 | top: Math.round((currentWindow.height-height)/2+currentWindow.top), 69 | }; 70 | if(weh.isBrowser("chrome","opera")) 71 | cwcParam.focused = true; 72 | 73 | return browser.windows.create(cwcParam) 74 | .then((window) => { 75 | panels[name] = { 76 | type: "window", 77 | windowId: window.id 78 | } 79 | return Promise.all([window,browser.windows.update(window.id,{ 80 | focused: true 81 | })]); 82 | }) 83 | .then(([window]) => { 84 | // trick to repaint window on Firefox 85 | // useless if auto resize 86 | Promise.resolve() 87 | .then(()=>{ 88 | if(options.initData && options.initData.autoResize) 89 | return; 90 | else 91 | return browser.windows.update(window.id,{ 92 | height: window.height+1 93 | }) 94 | .then(()=>{ 95 | return browser.windows.update(window.id,{ 96 | height: window.height-1 97 | }) 98 | }); 99 | }) 100 | .then(()=>{ 101 | var promise1 = new Promise((resolve, reject) => { 102 | var timer = setTimeout(()=>{ 103 | browser.tabs.onCreated.removeListener(ListenOpenedTabs); 104 | reject(new Error("Tab did not open")); 105 | },5000); 106 | function ListenOpenedTabs(tab) { 107 | if(tab.windowId==window.id) { 108 | clearTimeout(timer); 109 | browser.tabs.onCreated.removeListener(ListenOpenedTabs); 110 | resolve(tab); 111 | } 112 | } 113 | browser.tabs.onCreated.addListener(ListenOpenedTabs); 114 | }); 115 | var promise2 = browser.tabs.query({ 116 | windowId: window.id 117 | }).then((_tabs)=>{ 118 | return new Promise((resolve, reject) => { 119 | if(_tabs.length>0) 120 | resolve(_tabs[0]); 121 | }); 122 | }); 123 | return Promise.race([promise1,promise2]); 124 | }) 125 | .then((tab)=>{ 126 | if(tab.status=="loading") { 127 | return new Promise((resolve, reject) => { 128 | var timer = setTimeout(()=>{ 129 | browser.tabs.onUpdated.removeListener(onUpdated); 130 | reject(new Error("Tab did not complete")); 131 | },60000); 132 | function onUpdated(tabId,changeInfo,_tab) { 133 | if(tabId == tab.id && _tab.status=="complete") { 134 | clearTimeout(timer); 135 | browser.tabs.onUpdated.removeListener(onUpdated); 136 | resolve(_tab); 137 | } 138 | } 139 | browser.tabs.onUpdated.addListener(onUpdated); 140 | }) 141 | } else 142 | return tab; 143 | }) 144 | .then((tab)=>{ 145 | weh.__declareAppTab(name,{tab:tab.id,initData:options.initData}); 146 | tabs[tab.id] = name; 147 | }).then(resolve) 148 | .catch(reject); 149 | 150 | 151 | function OnFocusChanged(focusedWindowId) { 152 | if(focusedWindowId==window.id) 153 | return; 154 | 155 | if(!options.autoClose) 156 | return; 157 | 158 | browser.windows.getCurrent() 159 | .then((currentWindow) => { 160 | if(currentWindow.id!=window.id) 161 | browser.windows.remove(window.id) 162 | .then(()=>{},()=>{}); 163 | }); 164 | } 165 | function OnRemoved(removedWindowId) { 166 | if(removedWindowId==window.id) { 167 | browser.windows.onFocusChanged.removeListener(OnFocusChanged); 168 | browser.windows.onFocusChanged.removeListener(OnRemoved); 169 | } 170 | } 171 | browser.windows.onFocusChanged.addListener(OnFocusChanged); 172 | browser.windows.onRemoved.addListener(OnRemoved); 173 | }) 174 | .catch(reject); 175 | }) 176 | .catch(reject); 177 | }) 178 | } 179 | 180 | function OpenPanel(name,options) { 181 | return new Promise((resolve, reject) => { 182 | var url = browser.runtime.getURL(options.url+"?panel="+name); 183 | GotoTab(url) 184 | .then((found)=>{ 185 | if(!found) 186 | return CreatePanel(name,options); 187 | }) 188 | .then(resolve) 189 | .catch(reject); 190 | }) 191 | } 192 | 193 | 194 | browser.tabs.onRemoved.addListener((tabId)=>{ 195 | weh.__closeByTab(tabId); 196 | var panelName = tabs[tabId]; 197 | if(panelName) { 198 | delete tabs[tabId]; 199 | delete panels[panelName]; 200 | } 201 | }); 202 | 203 | function GotoTab(url, callback) { 204 | var foundTab = false; 205 | return new Promise( function(resolve, reject) { 206 | return browser.tabs.query({}) 207 | .then(function (tabs) { 208 | tabs.forEach(function (tab) { 209 | if (tab.url === url) { 210 | browser.tabs.update(tab.id, { 211 | active: true 212 | }); 213 | browser.windows.update(tab.windowId, { 214 | focused: true 215 | }); 216 | foundTab = true; 217 | } 218 | }); 219 | resolve(foundTab); 220 | }) 221 | }); 222 | } 223 | 224 | 225 | function Close(name) { 226 | var tab = panels[name]; 227 | if(tab && tab.type=="tab") 228 | browser.tabs.remove(tab.tabId); 229 | else if(tab && tab.type=="window") 230 | browser.windows.remove(tab.windowId); 231 | else 232 | wehRpc.call(name,"close"); 233 | } 234 | 235 | function IsOpen(name) { 236 | return !!panels[name]; 237 | } 238 | 239 | module.exports = { 240 | open: Open, 241 | close: Close, 242 | isOpen: IsOpen 243 | } 244 | -------------------------------------------------------------------------------- /src/weh-natmsg.js: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | const weh = require('weh'); 14 | var browser = weh.browser; 15 | const rpc = require('weh-rpc'); 16 | 17 | class EventHandler { 18 | constructor() { 19 | this.listeners = []; 20 | } 21 | addListener(listener) { 22 | this.listeners.push(listener); 23 | } 24 | removeListener(listener) { 25 | this.listeners = this.listeners.filter((_listener) => listener !== _listener); 26 | } 27 | removeAllListeners() { 28 | this.listeners = []; 29 | } 30 | notify(...args) { 31 | this.listeners.forEach((listener) => { 32 | try { 33 | listener(...args); 34 | } catch(e) { 35 | console.warn(e); 36 | } 37 | }); 38 | } 39 | } 40 | 41 | const ADDON2APP = 1; 42 | const APP2ADDON = 2; 43 | 44 | class NativeMessagingApp { 45 | 46 | constructor(appId,options={}) { 47 | this.appId = appId; 48 | this.name = options.name || appId; 49 | this.appPort = null; 50 | this.pendingCalls = []; 51 | this.runningCalls = []; 52 | this.state = "idle"; 53 | this.postFn = this.post.bind(this); 54 | this.postMessageFn = this.postMessage.bind(this); 55 | this.onAppNotFound = new EventHandler(); // general 56 | this.onAppNotFoundCheck = new EventHandler(); // call specific 57 | this.onCallCount = new EventHandler(); 58 | this.appStatus = "unknown"; 59 | this.app2AddonCallCount = 0; 60 | this.addon2AppCallCount = 0; 61 | } 62 | 63 | post(receiver,message) { 64 | this.appPort.postMessage(message); 65 | } 66 | 67 | // workaround to handle the fact that returning functions do not have 68 | // receiver parameter 69 | // TODO have a unique post() function 70 | postMessage(message) { 71 | this.appPort.postMessage(message); 72 | } 73 | 74 | updateCallCount(way,delta) { 75 | switch(way) { 76 | case APP2ADDON: 77 | this.app2AddonCallCount += delta; 78 | break; 79 | case ADDON2APP: 80 | this.addon2AppCallCount += delta; 81 | break; 82 | } 83 | this.onCallCount.notify(this.addon2AppCallCount,this.app2AddonCallCount); 84 | } 85 | 86 | close() { 87 | if(this.appPort) 88 | try { 89 | this.appPort.disconnect(); 90 | this.cleanup(); 91 | } catch(e) {} 92 | } 93 | 94 | call(...params) { 95 | var self = this; 96 | return this.callCatchAppNotFound(null,...params); 97 | } 98 | 99 | callCatchAppNotFound(appNotFoundHandler,...params) { 100 | var self = this; 101 | 102 | function ProcessPending(err) { 103 | var call; 104 | while(call=self.pendingCalls.shift()) { 105 | if(err) 106 | call.reject(err); 107 | else { 108 | self.runningCalls.push(call); 109 | let _call = call; 110 | rpc.call(self.postFn,self.name,...call.params) 111 | .then((result)=>{ 112 | self.runningCalls.splice(self.runningCalls.indexOf(_call),1); 113 | return result; 114 | }) 115 | .then(_call.resolve) 116 | .catch((err) => { 117 | self.runningCalls.splice(self.runningCalls.indexOf(_call),1); 118 | _call.reject(err); 119 | }); 120 | } 121 | } 122 | } 123 | 124 | if(appNotFoundHandler && (self.appStatus=="unknown" || self.appStatus=="checking")) 125 | self.onAppNotFoundCheck.addListener(appNotFoundHandler); 126 | 127 | self.updateCallCount(ADDON2APP,1); 128 | 129 | switch(this.state) { 130 | case "running": 131 | return new Promise((resolve,reject)=>{ 132 | var call = { 133 | resolve, 134 | reject, 135 | params: [...params] 136 | }; 137 | self.runningCalls.push(call); 138 | rpc.call(self.postFn,self.name,...params) 139 | .then((result)=>{ 140 | self.runningCalls.splice(self.runningCalls.indexOf(call),1); 141 | return result; 142 | }) 143 | .then(call.resolve) 144 | .catch((err)=>{ 145 | self.runningCalls.splice(self.runningCalls.indexOf(call),1); 146 | call.reject(err); 147 | }) 148 | }) 149 | .then((result)=>{ 150 | self.updateCallCount(ADDON2APP,-1); 151 | return result; 152 | }) 153 | .catch((err)=>{ 154 | self.updateCallCount(ADDON2APP,-1); 155 | throw err; 156 | }); 157 | case "idle": 158 | self.state = "pending"; 159 | return new Promise((resolve,reject)=>{ 160 | self.pendingCalls.push({ 161 | resolve, 162 | reject, 163 | params: [...params] 164 | }); 165 | var appPort = browser.runtime.connectNative(self.appId); 166 | self.appStatus = "checking"; 167 | self.appPort = appPort; 168 | appPort.onMessage.addListener((response) => { 169 | if(self.appStatus=="checking") { 170 | self.appStatus="ok"; 171 | self.onAppNotFoundCheck.removeAllListeners(); 172 | } 173 | rpc.receive(response,self.postMessageFn,self.name); 174 | }); 175 | appPort.onDisconnect.addListener(() => { 176 | ProcessPending(new Error("Disconnected")); 177 | self.cleanup(); 178 | if(self.appStatus=="checking" && !appNotFoundHandler) 179 | self.onAppNotFound.notify(self.appPort && self.appPort.error || browser.runtime.lastError); 180 | 181 | }); 182 | self.state = "running"; 183 | ProcessPending(); 184 | }) 185 | .then((result)=>{ 186 | self.updateCallCount(ADDON2APP,-1); 187 | return result; 188 | }) 189 | .catch((err)=>{ 190 | self.updateCallCount(ADDON2APP,-1); 191 | throw err; 192 | }); 193 | case "pending": 194 | return new Promise((resolve,reject)=>{ 195 | self.pendingCalls.push({ 196 | resolve, 197 | reject, 198 | params: [...params] 199 | }); 200 | }) 201 | .then((result)=>{ 202 | self.updateCallCount(ADDON2APP,-1); 203 | return result; 204 | }) 205 | .catch((err)=>{ 206 | self.updateCallCount(ADDON2APP,-1); 207 | throw err; 208 | }); 209 | } 210 | } 211 | 212 | listen(handlers) { 213 | var self = this; 214 | var rpcHandlers = {} 215 | Object.keys(handlers).forEach((handler)=>{ 216 | rpcHandlers[handler] = (...args) => { 217 | self.updateCallCount(APP2ADDON,1); 218 | return Promise.resolve(handlers[handler](...args)) 219 | .then((result)=>{ 220 | self.updateCallCount(APP2ADDON,-1); 221 | return result; 222 | }) 223 | .catch((err)=>{ 224 | self.updateCallCount(APP2ADDON,-1); 225 | throw err; 226 | }) 227 | } 228 | }); 229 | return rpc.listen(rpcHandlers); 230 | } 231 | 232 | cleanup() { 233 | var self = this; 234 | if(self.appStatus=="checking") { 235 | self.onAppNotFoundCheck.notify(self.appPort && self.appPort.error || browser.runtime.lastError); 236 | self.onAppNotFoundCheck.removeAllListeners(); 237 | } 238 | var call; 239 | while(call=self.runningCalls.shift()) { 240 | call.reject(new Error("Native port disconnected")); 241 | } 242 | self.state = "idle"; 243 | self.appStatus = "unknown"; 244 | self.appPort = null; 245 | } 246 | } 247 | 248 | module.exports = function New(...params) { 249 | return new NativeMessagingApp(...params); 250 | } 251 | -------------------------------------------------------------------------------- /src/weh-prefs.js: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | var _ = require('weh-i18n').getMessage; 14 | 15 | function Prefs() { 16 | 17 | this.$specs = {}; 18 | this.$values = null; 19 | if(!this.$values) 20 | this.$values = {}; 21 | this.$listeners = {}; 22 | } 23 | 24 | Prefs.prototype = { 25 | 26 | notify: function(p,val,oldVal,spec) { 27 | var self = this; 28 | var terms = p.split("."); 29 | var keys = []; 30 | for(var i=terms.length;i>=0;i--) 31 | keys.push(terms.slice(0,i).join(".")); 32 | keys.forEach(function(key) { 33 | var listeners = self.$listeners[key]; 34 | if(listeners) 35 | listeners.forEach(function(listener) { 36 | if(listener.specs!=spec) 37 | return; 38 | if(!listener.pack) 39 | try { 40 | listener.callback(p,val,oldVal); 41 | } catch(e) {} 42 | else { 43 | listener.pack[p] = val; 44 | if(typeof listener.old[p]=="undefined") 45 | listener.old[p] = oldVal; 46 | if(listener.timer) 47 | clearTimeout(listener.timer); 48 | listener.timer = setTimeout(function() { 49 | delete listener.timer; 50 | var pack = listener.pack; 51 | var old = listener.old; 52 | listener.pack = {}; 53 | listener.old = {}; 54 | try { 55 | listener.callback(pack,old); 56 | } catch(e) {} 57 | },0); 58 | 59 | } 60 | }); 61 | }); 62 | 63 | }, 64 | 65 | forceNotify: function(spec) { 66 | 67 | if(typeof spec==="undefined") 68 | spec = false; 69 | 70 | var self = this; 71 | 72 | Object.keys(self.$specs).forEach((key)=>{ 73 | self.notify(key, self.$values[key], self.$values[key], spec); 74 | }); 75 | 76 | }, 77 | 78 | declare: function(specs) { 79 | 80 | var self = this; 81 | 82 | if(!Array.isArray(specs)) 83 | specs = Object.keys(specs).map(function(prefName) { 84 | var spec = specs[prefName]; 85 | spec.name = prefName; 86 | return spec; 87 | }); 88 | 89 | specs.forEach(function(spec) { 90 | 91 | if(forbiddenKeys[spec.name]) 92 | throw new Error("Forbidden prefs key "+spec.name); 93 | 94 | if(spec.hidden) { 95 | spec.label = spec.name; 96 | spec.description = ""; 97 | } else { 98 | var localeName = spec.name.replace(/[^0-9a-zA-Z_]/g,'_'); 99 | spec.label = spec.label || _("weh_prefs_label_"+localeName) || spec.name; 100 | spec.description = spec.description || _("weh_prefs_description_"+localeName) || ""; 101 | } 102 | 103 | if(spec.type == "choice") 104 | spec.choices = (spec.choices || []).map(function(choice) { 105 | if(typeof choice=="object") 106 | return choice; 107 | if(spec.hidden) 108 | return { 109 | value: choice, 110 | name: choice 111 | } 112 | else { 113 | var localeChoice = choice.replace(/[^0-9a-zA-Z_]/g,'_'); 114 | var localeChoiceTag = "weh_prefs_"+localeName+"_option_"+localeChoice; 115 | return { 116 | value: choice, 117 | name: _("weh_prefs_"+localeName+"_option_"+localeChoice) || choice 118 | } 119 | } 120 | }); 121 | 122 | var prevValue = null; 123 | 124 | if(!self.$specs[spec.name]) 125 | (function(p) { 126 | if(typeof self[spec.name]!=="undefined") 127 | prevValue = self[spec.name]; 128 | Object.defineProperty(self, p, { 129 | set: function(val) { 130 | var oldVal = self.$values[p]; 131 | if(oldVal===val) 132 | return; 133 | self.$values[p] = val; 134 | self.notify(p,val,oldVal,false); 135 | 136 | }, 137 | get: function() { 138 | return self.$values[p]!==undefined ? self.$values[p] : 139 | (self.$specs[p] && self.$specs[p].defaultValue || undefined); 140 | } 141 | }); 142 | })(spec.name); 143 | 144 | var oldSpecs = self.$specs[spec.name]; 145 | self.$specs[spec.name] = spec; 146 | if(prevValue!==null) 147 | self.$values[spec.name] = prevValue; 148 | else if(typeof self.$values[spec.name]=="undefined") 149 | self.$values[spec.name] = spec.defaultValue; 150 | 151 | self.notify(spec.name,spec,oldSpecs,true); 152 | }); 153 | 154 | }, 155 | 156 | on: function() { 157 | var pref = "", options = {}, argIndex = 0; 158 | if(typeof arguments[argIndex]=="string") 159 | pref = arguments[argIndex++]; 160 | if(typeof arguments[argIndex]=="object") 161 | options = arguments[argIndex++]; 162 | var callback = arguments[argIndex]; 163 | var pack = !!options.pack; 164 | 165 | if(!this.$listeners[pref]) 166 | this.$listeners[pref] = []; 167 | var handler = { 168 | callback: callback, 169 | specs: !!options.specs 170 | } 171 | if(pack) { 172 | handler.pack = {}; 173 | handler.old = {}; 174 | } 175 | this.$listeners[pref].push(handler); 176 | }, 177 | 178 | off: function() { 179 | var pref = "", argIndex = 0; 180 | if(typeof arguments[argIndex]=="string") 181 | pref = arguments[argIndex++]; 182 | var callback = arguments[argIndex]; 183 | var listeners = this.$listeners[pref]; 184 | if(!listeners) 185 | return; 186 | for(var i=listeners.length-1;i>=0;i--) 187 | if(!callback || listeners[i]==callback) 188 | listeners.splice(i,1); 189 | }, 190 | 191 | getAll: function() { 192 | return Object.assign({},this.$values); 193 | }, 194 | 195 | getSpecs: function() { 196 | return Object.assign({},this.$specs); 197 | }, 198 | 199 | assign: function(prefs) { 200 | for(var k in prefs) 201 | if(prefs.hasOwnProperty(k)) 202 | this[k] = prefs[k]; 203 | }, 204 | 205 | isValid: function(prefName,value) { 206 | var spec = this.$specs[prefName]; 207 | if(!spec) 208 | return undefined; 209 | switch(spec.type) { 210 | case "string": 211 | if(spec.regexp && !new RegExp(spec.regexp).test(value)) 212 | return false; 213 | break; 214 | case "integer": 215 | if(!/^-?[0-9]+$/.test(value)) 216 | return false; 217 | if(isNaN(parseInt(value))) 218 | return false; 219 | /* falls through */ 220 | case "float": 221 | if(spec.type=="float") { 222 | if(!/^-?[0-9]+(\.[0-9]+)?|(\.[0-9]+)$/.test(value)) 223 | return false; 224 | if(isNaN(parseFloat(value))) 225 | return false; 226 | } 227 | if(typeof spec.minimum!="undefined" && valuespec.maximum) 230 | return false; 231 | break; 232 | case "choice": 233 | var ok = false; 234 | (spec.choices || []).forEach((choice) => { 235 | if(value==choice.value) 236 | ok = true; 237 | }); 238 | if(!ok) 239 | return false; 240 | break; 241 | } 242 | return true; 243 | }, 244 | 245 | reducer: function(state={}, action) { 246 | switch(action.type) { 247 | case "weh.SET_PREFS": 248 | state = Object.assign({},state,action.payload); 249 | break; 250 | } 251 | return state; 252 | }, 253 | 254 | reduxDispatch(store) { 255 | this.on("", { 256 | pack:true 257 | },(changedPrefs)=>{ 258 | store.dispatch({ 259 | type: "weh.SET_PREFS", 260 | payload: changedPrefs 261 | }); 262 | }); 263 | } 264 | 265 | } 266 | 267 | var prefs = new Prefs(); 268 | 269 | var forbiddenKeys = {}; 270 | for(var k in prefs) 271 | if(prefs.hasOwnProperty(k)) 272 | forbiddenKeys[k] = true; 273 | 274 | module.exports = prefs; 275 | -------------------------------------------------------------------------------- /src/react/weh-prefs-settings.jsx: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | import React from 'react'; 14 | import {bindActionCreators} from 'redux'; 15 | import {connect} from 'react-redux'; 16 | 17 | import 'bootstrap/dist/css/bootstrap.css' 18 | import 'css/weh-form-states.css'; 19 | 20 | import weh from 'weh-content'; 21 | 22 | export function reducer(state, action) { 23 | if (!state) { 24 | state = { 25 | values: weh.unsafe_prefs.getAll(), 26 | current: weh.unsafe_prefs.getAll(), 27 | specs: weh.unsafe_prefs.getSpecs(), 28 | flags: {}, 29 | }; 30 | state.flags = GetFlags(); 31 | } 32 | 33 | function GetFlags() { 34 | var flags = { 35 | isModified: false, 36 | isDefault: true, 37 | isValid: true 38 | } 39 | Object.keys(state.specs || {}).forEach((prefName)=>{ 40 | var spec = (state.specs || {})[prefName]; 41 | var value = state.current[prefName]; 42 | if(!spec) return; 43 | if(spec.defaultValue!==value) 44 | flags.isDefault = false; 45 | if(value!==state.values[prefName]) 46 | flags.isModified = true; 47 | if(!weh.unsafe_prefs.isValid(prefName,value)) 48 | flags.isValid = false; 49 | }); 50 | return flags; 51 | } 52 | 53 | switch(action.type) { 54 | case "PREFS_UPDATED": 55 | state = Object.assign({},state,{ 56 | values: Object.assign({},state.values,action.payload), 57 | current: Object.assign({},action.payload,state.current), 58 | }); 59 | state.flags = GetFlags(); 60 | break; 61 | 62 | case "PREFS_SPECS_UPDATED": 63 | state = Object.assign({},state,{ 64 | specs: Object.assign({},state.specs,action.payload), 65 | }) 66 | state.flags = GetFlags(); 67 | break; 68 | 69 | case "PREF_UPDATE": 70 | if(state.current[action.payload.prefName] != action.payload.value) { 71 | state = Object.assign({},state); 72 | state.current = Object.assign({},state.current); 73 | state.current[action.payload.prefName] = action.payload.value; 74 | state.flags = GetFlags(); 75 | } 76 | break; 77 | 78 | case "PREFS_RESET": 79 | state = Object.assign({},state); 80 | Object.keys(state.specs || {}).forEach((prefName)=>{ 81 | var spec = (state.specs || {})[prefName]; 82 | if(!spec) return; 83 | state.current[prefName] = spec.defaultValue; 84 | }); 85 | state.flags = GetFlags(); 86 | break; 87 | 88 | case "PREFS_CANCEL": 89 | state = Object.assign({},state); 90 | Object.keys(state.specs || {}).forEach((prefName)=>{ 91 | state.current[prefName] = state.values[prefName]; 92 | }); 93 | state.flags = GetFlags(); 94 | break; 95 | 96 | case "PREFS_SAVE": 97 | weh.unsafe_prefs.assign(state.current); 98 | break; 99 | } 100 | return state; 101 | } 102 | 103 | export class App extends React.Component { 104 | render() { 105 | return ( 106 |
e.preventDefault()}> 107 |
{this.props.children}
108 |
109 | ) 110 | } 111 | } 112 | 113 | var wehParamIndex = 1; 114 | export var WehParam = connect( 115 | // map redux state to react component props 116 | (state, ownProps) => { 117 | return { 118 | initialValue: state.prefs.values[ownProps.prefName] || "", 119 | value: state.prefs.current[ownProps.prefName] || "", 120 | spec: state.prefs.specs[ownProps.prefName] || {} 121 | } 122 | }, 123 | // make some redux actions available as react component props 124 | (dispatch) => { 125 | return bindActionCreators ({ 126 | updateCurrentPref: (prefName,value) => { 127 | return { 128 | type: "PREF_UPDATE", 129 | payload: { prefName, value } 130 | } 131 | } 132 | },dispatch); 133 | })( 134 | 135 | class extends React.Component { 136 | 137 | constructor(props) { 138 | super(props); 139 | this.state = { 140 | value: this.props.value || "", 141 | spec: this.props.spec 142 | }; 143 | this.paramIndex = wehParamIndex++; 144 | this.handleChange=this.handleChange.bind(this); 145 | } 146 | 147 | componentWillReceiveProps(props) { 148 | this.setState({ 149 | value: props.value || "", 150 | spec: props.spec 151 | }) 152 | } 153 | 154 | handleChange(event) { 155 | var value = this.state.spec.type=="boolean" ? event.target.checked : event.target.value; 156 | this.setState({ 157 | value: value 158 | }); 159 | if(this.state.spec.type=="integer") 160 | value = parseInt(value); 161 | if(this.state.spec.type=="float") 162 | value = parseFloat(value); 163 | this.props.updateCurrentPref(this.props.prefName,value); 164 | } 165 | 166 | setCustomValue(value) { 167 | var event = { target: {} }; 168 | if(this.state.spec.type=="boolean") 169 | event.target.checked = value; 170 | else 171 | event.target.value = value; 172 | this.handleChange(event); 173 | } 174 | 175 | isValid(value) { 176 | var spec = this.state.spec; 177 | if(arguments.length===0) 178 | value = this.state.value; 179 | if(!spec) 180 | return false; 181 | return weh.unsafe_prefs.isValid(this.props.prefName,value); 182 | } 183 | 184 | formGroupClass() { 185 | if(!this.isValid()) 186 | return "has-danger"; 187 | else if(this.state.value != this.props.initialValue) 188 | return "has-success"; 189 | else if(this.state.value != this.state.spec.defaultValue) 190 | return "has-warning"; 191 | else 192 | return ""; 193 | } 194 | 195 | getInputWidth() { 196 | switch(this.state.spec.type) { 197 | case "string": 198 | return this.state.spec.width || "20em"; 199 | case "integer": 200 | case "float": 201 | return this.state.spec.width || "8em"; 202 | case "boolean": 203 | return "34px"; 204 | case "choice": 205 | return this.state.spec.width || "12em"; 206 | } 207 | } 208 | 209 | renderInput() { 210 | switch(this.state.spec.type) { 211 | case "string": 212 | case "integer": 213 | case "float": 214 | return 221 | case "boolean": 222 | return
223 | 230 |
231 | case "choice": 232 | var options = (this.state.spec.choices || []).map( 233 | (option) => 234 | ); 235 | if(options.length===0) 236 | return false; 237 | return 245 | 246 | } 247 | } 248 | 249 | render() { 250 | return ( 251 |
252 | 254 |
255 | { this.props.renderInput && this.props.renderInput.call(this) || this.renderInput()} 256 | { this.state.spec.description && ( 257 |
{ this.state.spec.description }
258 | )} 259 |
260 |
261 | ) 262 | } 263 | } 264 | 265 | ); // end export WehParam 266 | 267 | 268 | export var WehPrefsControls = connect( 269 | (state) => { 270 | return { 271 | flags: state.prefs.flags || {} 272 | } 273 | }, 274 | (dispatch) => { 275 | return bindActionCreators ({ 276 | save: () => { 277 | return { 278 | type: "PREFS_SAVE" 279 | } 280 | }, 281 | reset: () => { 282 | return { 283 | type: "PREFS_RESET" 284 | } 285 | }, 286 | cancel: () => { 287 | return { 288 | type: "PREFS_CANCEL" 289 | } 290 | } 291 | },dispatch); 292 | } 293 | )( 294 | class extends React.Component { 295 | 296 | render() { 297 | return this.props.render.call(this); 298 | } 299 | } 300 | ); 301 | 302 | export function listenPrefs(store) { 303 | const wehPrefs = weh.unsafe_prefs; 304 | wehPrefs.on("",{ 305 | pack: true 306 | },(prefs)=>{ 307 | store.dispatch({ 308 | type: "PREFS_UPDATED", 309 | payload: prefs 310 | }) 311 | }); 312 | 313 | wehPrefs.on("",{ 314 | pack: true, 315 | specs: true 316 | },(specs)=>{ 317 | store.dispatch({ 318 | type: "PREFS_SPECS_UPDATED", 319 | payload: specs 320 | }) 321 | }); 322 | 323 | } 324 | -------------------------------------------------------------------------------- /src/react/weh-translation.jsx: -------------------------------------------------------------------------------- 1 | /* 2 | * weh - WebExtensions Helper 3 | * 4 | * @summary workflow and base code for developing WebExtensions browser add-ons 5 | * @author Michel Gutierrez 6 | * @link https://github.com/mi-g/weh 7 | * 8 | * This Source Code Form is subject to the terms of the Mozilla Public 9 | * License, v. 2.0. If a copy of the MPL was not distributed with this 10 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 11 | */ 12 | 13 | import {browser} from 'weh'; 14 | import React from 'react'; 15 | import {bindActionCreators} from 'redux'; 16 | import {connect} from 'react-redux'; 17 | import i18nKeys from 'weh-i18n-keys'; 18 | import WehHeader from 'react/weh-header'; 19 | 20 | import 'bootstrap/dist/css/bootstrap.css' 21 | import 'css/weh-form-states.css'; 22 | 23 | let needRestore = true; 24 | 25 | const initialState = { 26 | keys: Object.keys(i18nKeys), 27 | custom: {}, 28 | modified: {}, 29 | }; 30 | 31 | export function reducer(state=initialState,action) { 32 | switch(action.type) { 33 | case "UPDATE_STRING": 34 | state = Object.assign({}, state, { 35 | modified: Object.assign({},state.modified) 36 | }); 37 | if(state.custom[action.payload.key]===action.payload.value || 38 | typeof state.custom[action.payload.key]==="undefined" && action.payload.value.trim()==="") 39 | delete state.modified[action.payload.key]; 40 | else 41 | state.modified[action.payload.key] = action.payload.value; 42 | break; 43 | 44 | case "SAVE": 45 | state = Object.assign({}, state, { 46 | custom: Object.assign({},state.custom,state.modified), 47 | modified: {} 48 | }); 49 | var customMessages = {}; 50 | Object.keys(state.custom).forEach((key)=>{ 51 | customMessages[key] = { 52 | message: state.custom[key] 53 | } 54 | }); 55 | browser.storage.local.set({ 56 | "wehI18nCustom": customMessages 57 | }); 58 | break; 59 | 60 | case "CANCEL": 61 | state = Object.assign({}, state, { 62 | modified: {} 63 | }); 64 | break; 65 | case "IMPORT": 66 | state = Object.assign({}, state, { 67 | modified: action.payload 68 | }); 69 | break; 70 | case "RESET": 71 | state = Object.assign({}, state, { 72 | modified: {}, 73 | custom: {} 74 | }); 75 | break; 76 | case "RESTORE": 77 | var customMessages = {}; 78 | Object.keys(action.payload).forEach((key)=>{ 79 | customMessages[key] = action.payload[key].message 80 | }); 81 | state = Object.assign({}, state, { 82 | custom: customMessages, 83 | modified: {} 84 | }); 85 | break; 86 | } 87 | return state; 88 | } 89 | 90 | function IsObjectEmpty(obj) { 91 | var empty = true; 92 | for(var f in obj) 93 | if(obj.hasOwnProperty(f)) { 94 | empty = false; 95 | break; 96 | } 97 | return empty; 98 | } 99 | 100 | export var WehTranslationForm = connect( 101 | // map redux state to react component props 102 | (state) => { 103 | return { 104 | keys: state.translate.keys || [], 105 | custom: state.translate.custom, 106 | isModified: !IsObjectEmpty(state.translate.modified), 107 | modified: state.translate.modified 108 | } 109 | }, 110 | // make some redux actions available as react component props 111 | (dispatch) => { 112 | return bindActionCreators ({ 113 | save: () => { 114 | return { 115 | type: "SAVE" 116 | } 117 | }, 118 | cancel: () => { 119 | return { 120 | type: "CANCEL" 121 | } 122 | }, 123 | import: (data) => { 124 | return { 125 | type: "IMPORT", 126 | payload: data 127 | } 128 | }, 129 | reset: (data) => { 130 | return { 131 | type: "RESET" 132 | } 133 | }, 134 | restore: (data) => { 135 | return { 136 | type: "RESTORE", 137 | payload: data 138 | } 139 | } 140 | },dispatch); 141 | } 142 | )( 143 | class extends React.Component { 144 | 145 | constructor(props) { 146 | super(props); 147 | this.state = { 148 | search: "", 149 | filter: props.missingTags && props.missingTags.length>0 && "missing" || "all" 150 | } 151 | var maxArgs = 4; // should be 9 but this is a bug in Edge 152 | this.argPlaceHolders = new Array(maxArgs).fill("").map((v,i) => {return ""}); 153 | 154 | this.handleSearchChange = this.handleSearchChange.bind(this); 155 | this.searchFilter = this.searchFilter.bind(this); 156 | this.fileInputChange = this.fileInputChange.bind(this); 157 | } 158 | 159 | componentWillMount(props) { 160 | var self = this; 161 | if(needRestore) { 162 | needRestore = false; 163 | browser.storage.local.get("wehI18nCustom") 164 | .then((result)=>{ 165 | const weCustomMessages = result.wehI18nCustom; 166 | weCustomMessages && self.props.restore(weCustomMessages); 167 | }); 168 | } 169 | } 170 | 171 | handleSearchChange(event) { 172 | var search = event.target.value; 173 | this.setState({ search }); 174 | } 175 | 176 | searchFilter() { 177 | var self = this; 178 | return (key) => { 179 | key = key.toLowerCase(); 180 | var search = self.state.search.toLowerCase().trim(); 181 | if(search.length===0) 182 | return true; 183 | if(typeof self.props.modified[key]!=="undefined") 184 | return true; 185 | if(key.indexOf(search)>=0) 186 | return true; 187 | if(self.props.custom[key] && self.props.custom[key].toLowerCase().indexOf(search)>=0) 188 | return true; 189 | if(self.props.modified[key] && self.props.modified[key].toLowerCase().indexOf(search)>=0) 190 | return true; 191 | var original = browser.i18n.getMessage(key,self.argPlaceHolders).toLowerCase(); 192 | if(original.indexOf(search)>=0) 193 | return true; 194 | return false; 195 | } 196 | } 197 | 198 | typeFilter() { 199 | var self = this; 200 | return (key)=>{ 201 | return self.state.filter!="missing" || !self.props.missingTags || 202 | self.props.missingTags.length==0 || self.props.missingTags.indexOf(key)>=0; 203 | } 204 | } 205 | 206 | changedFilter() { 207 | var self = this; 208 | return (event) => { 209 | self.setState({ 210 | filter: event.target.value 211 | }) 212 | } 213 | } 214 | 215 | reset() { 216 | var self = this; 217 | return ()=>{ 218 | this.props.reset(); 219 | } 220 | } 221 | 222 | import() { 223 | var self = this; 224 | return () => { 225 | self.fileInput.click(); 226 | } 227 | } 228 | 229 | fileInputChange(event) { 230 | var self = this; 231 | var file = self.fileInput.files[0]; 232 | if(file) { 233 | var reader = new FileReader(); 234 | reader.onload = (event) => { 235 | try { 236 | var data = JSON.parse(event.target.result); 237 | self.props.import(data); 238 | } catch(e) { 239 | alert("File "+file.name+": Invalid format "+e.message); 240 | } 241 | } 242 | reader.readAsText(file); 243 | } 244 | } 245 | 246 | setFileInput(input) { 247 | var self = this; 248 | return (input) => { 249 | if(input) 250 | input.removeEventListener("change",self.fileInputChange); 251 | self.fileInput = input; 252 | if(!input) 253 | return; 254 | input.addEventListener("change",self.fileInputChange); 255 | } 256 | } 257 | 258 | export() { 259 | var self = this; 260 | return () => { 261 | var data = Object.assign({},self.props.custom,self.props.modified); 262 | var blob = new Blob([JSON.stringify(data,null,4)]); 263 | browser.downloads.download({ 264 | url: window.URL.createObjectURL(blob), 265 | filename: "messages.json", 266 | saveAs: true, 267 | conflictAction: "uniquify" 268 | }); 269 | } 270 | } 271 | 272 | render() { 273 | var items = this.props.keys.filter(this.searchFilter()).filter(this.typeFilter()).sort().map((key)=>{ 274 | return ( 275 | 276 | ) 277 | }); 278 | return ( 279 |
282 | 283 |
284 | 290 | {"\u00a0"} 291 | { this.props.missingTags && this.props.missingTags.length>0 && ( 292 | 296 | )} 297 |
298 |
299 |
300 |
301 |
302 | { items } 303 |
304 |
305 |
306 |
307 |
308 | 309 |
310 | { this.props.footerExtra && ( 311 |
312 | {this.props.footerExtra} 313 |
314 | )} 315 |
316 |
317 | 320 | 323 | 327 | 330 | 333 |
334 |
335 |
336 |
337 | ) 338 | } 339 | } 340 | ); 341 | 342 | export var WehTranslationItem = connect( 343 | (state,ownProps) => { 344 | var orgValue = state.translate.custom[ownProps.keyName]; 345 | var value = orgValue; 346 | if(typeof state.translate.modified[ownProps.keyName]!=="undefined") 347 | value = state.translate.modified[ownProps.keyName]; 348 | return { 349 | value: value || "", 350 | orgValue: orgValue || "" 351 | } 352 | }, 353 | (dispatch) => { 354 | return bindActionCreators ({ 355 | updateString: (key,value) => { 356 | return { 357 | type: "UPDATE_STRING", 358 | payload: { 359 | key: key, 360 | value: value 361 | } 362 | } 363 | } 364 | },dispatch); 365 | } 366 | )( 367 | class extends React.Component { 368 | 369 | constructor(props) { 370 | super(props); 371 | this.state = { 372 | value: this.props.value || "", 373 | orgValue: this.props.orgValue || "" 374 | } 375 | var maxArgs = 4; // should be 9 but this is a bug in Edge 376 | var argPlaceHolders = new Array(maxArgs).fill("").map((v,i) => {return "$ARG"+(i+1)+"$"}); 377 | this.defaultString = browser.i18n.getMessage(this.props.keyName,argPlaceHolders); 378 | this.handleChange = this.handleChange.bind(this); 379 | this.formClass = this.formClass.bind(this); 380 | } 381 | 382 | componentWillReceiveProps(props) { 383 | this.setState({ 384 | value: props.value || "", 385 | orgValue: props.orgValue || "" 386 | }) 387 | } 388 | 389 | formClass(prefix="") { 390 | if(this.state.value!==this.state.orgValue) 391 | return prefix + "success"; 392 | if(this.state.value!=="") 393 | return prefix + "warning"; 394 | return ""; 395 | } 396 | 397 | handleChange(event) { 398 | var value = event.target.value; 399 | this.setState({ 400 | value: value 401 | }); 402 | this.props.updateString(this.props.keyName,value); 403 | } 404 | 405 | render() { 406 | return ( 407 |
408 | 410 |
411 | 417 |
{ this.defaultString }
418 |
419 |
420 | ) 421 | } 422 | } 423 | ); 424 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # weh 2 | 3 | **weh** stands for *WebExtensions Helper*. 4 | 5 | This toolkit speeds up browser add-ons development by providing a number of facilities for WebExtensions-based (Firefox, Chrome, Opera and Edge) extensions. 6 | 7 | This is not a framework in the sense that the developer does not have to embrace all the provided utilities and there are not many architectural constraints to follow in order to take benefit of the tool. 8 | 9 | The build system generates automatically a directory you can directly install into your browser, compiling 10 | automatically CoffeeScript, TypeScript and JSX to Javascript, Sass, Less and Stylus to CSS. 11 | 12 | **weh** also provides some libraries that go into your addon to ease a number of common tasks like managing preferences and two-way communications between the extension background and its user interface content pages, 13 | providing a way for the end-user to customize any string in the add-on user interface. Developing the user interface using ReactJS is also simplified but you may choose not to use this library. 14 | 15 | In addition, an inspector application (under the form of a **weh**-based extension) is provided to monitor other **weh** extensions in real-time. 16 | 17 | **weh**-generated extensions are compatible with Firefox, Chrome, Opera and Edge. You should of course maintain this compatibility in the code you add to your project. 18 | 19 | ## install from npm 20 | 21 | ``` 22 | npm install -g weh gulp 23 | ``` 24 | 25 | ### testing installation 26 | 27 | ``` 28 | weh init --prjdir myextension 29 | ``` 30 | 31 | You can now install your skeleton extension from the `myextension/build` directory as described 32 | [here](#install-local). 33 | 34 | ## install from github 35 | 36 | ``` 37 | npm install -g gulp 38 | git clone https://github.com/mi-g/weh.git 39 | cd weh 40 | npm install 41 | npm link 42 | ``` 43 | 44 | You can now move away from the *weh* directory. 45 | 46 | ## using weh 47 | 48 | To create a new extension project: 49 | 50 | ``` 51 | weh init --prjdir myextension 52 | ``` 53 | 54 | You now have a `myextension` folder. The `myextension/src` sub-directory is the place where your add-on specific 55 | code goes. After running `weh init`, the directory contains a simple skeleton code that demonstrates preferences edition. This code is to be modified 56 | to do what your extension is supposed to do. 57 | The `myextension/build` contain an add-on ready to be installed into your browser. 58 | 59 | To build and maintain the add-on: 60 | 61 | ``` 62 | cd myextension 63 | weh 64 | ``` 65 | 66 | You will notice that the last `weh` command does not return. It is in watch mode, meaning whenever you make a change into the `myextension/src` 67 | directory, those changes are rebuild into `myextension/build`. If you do not want this behavior and prefer running the build command manually, 68 | add `--no-watch` to the command line. 69 | 70 | Run `weh help` to see more command line options. 71 | 72 | ## installing a local add-on into the browser 73 | 74 | - on ***Firefox***: visit `about:debugging`, click *Load Temporary Addon*, select the `myextension/build/manifest.json` file 75 | - on ***Chrome***: visit `chrome://extension`, check *Developer mode*, click *Load unpacked extension*, select the `myextension/build` directory 76 | - on ***Opera***: visit `about:extension`, click *Developer mode*, *Load unpacked extension*, select `myextension/build` directory 77 | - on ***Edge***: (tested with insider *Edge version 39.14959*) click the 3 dots icon at the top right, select *Extensions*, click *Load extension*, select `myextension/build` directory 78 | 79 | ## extension directory structure 80 | 81 | **weh** expects all project-specific code to be put into the `src` sub-directory: 82 | 83 | - `src/manifest.json`: your add-on's manifest 84 | - `src/**/*`: those files are processed, so resources like js and css (and other supported languages) are learned and processed to the build directory. 85 | - `src-modules/**/*`: files here are used to resolve dependencies 86 | - `locales`: files are copied to `build/_locales` 87 | 88 | Also note that you can change the `src` directory by specifying a directory path with the `--srcdir` option. 89 | 90 | ## accessing weh services 91 | 92 | Declaring `weh` from a background script: `const weh = require('weh-background');` 93 | From a content script: `const weh = require('weh-content');` 94 | 95 | You can then access a number of services from the `weh` variable: 96 | 97 | - `weh.rpc`: making function calls (both ways) through various components completely transparent: between background and content, background and workers, background and native apps, background and injected-content 98 | - `weh.prefs`: preferences system 99 | - `weh.i18n`: translation system 100 | - `weh.ui`: content management from background utilities 101 | 102 | ## multi-language support 103 | 104 | *Weh* obviously supports Javascript (`.js` file extension) for scripts and Cascading Style Sheets (`.css` extension), but you can also use other languages: 105 | 106 | - scripts: *JSX* (`.jsx`), *Typescript* (`.ts`), *Coffee* (`.coffee`) 107 | - styling: *Sass* (`.scss`), *Less* (`.less`), *Stylus* (`.styl`) 108 | 109 | ## pre-processing files 110 | 111 | All files with a `.ejs` are processed first by an *EJS* processor. For instance, a file named `myscript.js.ejs` will 112 | be transformed to `myscript.js` before being processed. You can specify one or several JSON files to provide data 113 | for the EJS resolution using the `--ejsdata` option. 114 | 115 | The EJS pre-processing occurs in a first place, so a file named `myscript.ts.ejs` will first be EJS-processed, then 116 | compiled using Typescript, and will end up in the build directory as `myscript.js`. 117 | 118 | Any text file in the `src` directory can be processed with EJS, not only js and css-like. 119 | 120 | Pre-processing is useful if you want to generate different builds from the same source code. 121 | 122 | ## using weh libraries 123 | 124 | ### weh preferences 125 | 126 | Preferences are to be formally defined in order to be used in your add-on. An example of preferences description could be: 127 | ```js 128 | weh.prefs.declare([{ 129 | name: "myparam_string", 130 | type: "string", 131 | defaultValue: "Default value", 132 | maxLength: 15, 133 | regexp: "^[a-zA-Z ]+$" 134 | },{ 135 | name: "myparam_integer", 136 | type: "integer", 137 | defaultValue: 42, 138 | minimum: -10, 139 | maximum: 100 140 | },{ 141 | name: "myparam_float", 142 | type: "float", 143 | defaultValue: 3.14159, 144 | minimum: 1.5, 145 | maximum: 10.8 146 | },{ 147 | name: "myparam_boolean", 148 | type: "boolean", 149 | defaultValue: true 150 | },{ 151 | name: "myparam_choice", 152 | type: "choice", 153 | defaultValue: "second", 154 | choices: [{ 155 | name: "First choice", 156 | value: "first" 157 | },{ 158 | name: "Second choice", 159 | value: "second" 160 | },{ 161 | name: "Third choice", 162 | value: "third" 163 | }] 164 | }]); 165 | ``` 166 | For each parameter, you must provide at least `name`, `type` and `defaultValue`. `type` must be one of `string`, `integer`, `float`, `boolean` or 167 | `choice`. A specific preference parameter can then be accessed, as read or write, through `weh.prefs["parameter name"]`. 168 | 169 | You can install preferences listeners using `weh.prefs.on(whatToWatch,callback)` and un-install listeners using `weh.prefs.off` with the same parameters. `whatToWatch` uses a dotted notation. For instance, listening to `""`, `"a"`, `"a.b"` or `"a.b.c"` will trigger the callback whenever 170 | parameter `a.b.c` is modified. Note that the preferences listeners are available from both background and local content. 171 | 172 | You should also define a couple of human viewable strings associated to each parameter in `locales//messages.json`: 173 | - `weh_prefs_label_` defines a label for the parameter 174 | - `weh_prefs_description_` defines an optional longer description for this parameter 175 | 176 | Example (`locales/en_US/messages.json`): 177 | ```js 178 | "weh_prefs_label_myparam_string": { 179 | "message": "String parameter" 180 | }, 181 | "weh_prefs_description_myparam_string": { 182 | "message": "Only letters and spaces, 20 characters max" 183 | }, 184 | ``` 185 | 186 | You can define a number of constraints to your preferences. This is useful with the settings user interface provided by *weh*. 187 | - `maxLength`: (type `string`, `integer` and `float`) the number of characters in the input 188 | - `regexp`: (type `string`) a regular expression the string must match 189 | - `minimum`: (type `integer` and `float`) the minimum acceptable value 190 | - `maximum`: (type `integer` and `float`) the maximum acceptable value 191 | - `choices`: (type `choice`) the set of possible choices to appear in a select input. This is array of either: 192 | - object containing fields `value` (the actual preference value) and `name` (what is to be displayed to the user) 193 | - string representing the actual preference value. The label to be displayed for this choice is searched in `locales//messages.json` as `weh_prefs_label__option_` 194 | 195 | Note that the preferences definition can be declared or updated at any time. This is useful if, for instance, you don't the list of choices in advance. 196 | 197 | *weh* takes care of adding/removing the listener when the component is mounted/unmounted and delivering the message to the `onWehMessage` method. 198 | 199 | ## debugging tools 200 | 201 | The *weh* toolkit includes an extension called *weh-inspector* which allows to: 202 | - monitor messages between the background and UI 203 | - read/write addon preferences 204 | - read add-on storage 205 | 206 | The *weh-inspector* is available as a template in the *weh* toolkit. As such, you can install it with `weh init --template inspector --prjdir inspector` and then load the generated extension into the browser like any regular weh addon. 207 | 208 | ## i18n 209 | 210 | *weh* provides some utilities for dealing with locales. 211 | 212 | Instead of `browser.i18n.getMessage()`, you should use `weh._()`, with the same parameters: 213 | - it's shorter 214 | - it automatically turns character `'-'` into `'_'` in string tags while leaving a warning in the console 215 | - more important: it allows overwriting some or all locale strings. Whenever a call is made to `weh._()`, the library first searches for a storage-based translation for this tag. If not found, it uses the default string defined in `_locales//messages.json`. By default, *weh* provides a user interface page for the user to edit locale strings. It is up to the add-on developer to write the code to centralize the user-generated translations on a server, so that it can be shared amongst all users. 216 | 217 | ## rpc 218 | 219 | *weh* provides an easy way to call functions across components that do not run within the same threads. 220 | 221 | All the functions return promises. If a declared function returns something other than a Promise object, *weh* takes of promisifying the returned value. 222 | 223 | Functions are declared on the called side using `weh.rpc.listen()` and are called with `weh.rpc.call()`. 224 | 225 | For instance, the background can define a function like this: 226 | ```js 227 | weh.rpc.listen({ 228 | my_function: (a,b) => { 229 | return a + b; 230 | } 231 | }) 232 | ``` 233 | 234 | and a content script can call the function this way: 235 | ```js 236 | weh.call("my_function",39,3) 237 | .then((result)=>{ 238 | console.info("=",result); 239 | }); 240 | ``` 241 | 242 | `weh.rpc.listen()` can declare several functions at once, and can be called several times: only function with the same name are overwritten. 243 | 244 | When using the `weh.ui` module to create a content, for instance creating a tab, a name is given to this content, for instance `settings`. When the background wants to call a function declared within this content, it must use the content name as the first parameter: `weh.rpc.call("settings","my_function",39,3); 245 | 246 | If the called function does not exists, throw an exception or return explicitly a failed promise the returned promise is rejected. 247 | 248 | ## native messaging 249 | 250 | *weh* is also very useful when dealing with native messaging. 251 | 252 | ```js 253 | var nativeApp = require('weh-natmsg')("com.example.myapp"); 254 | 255 | nativeApp.call("my_function",...params) 256 | .then((result)=>{ 257 | // do something 258 | }) 259 | .catch((err)=>{ 260 | // handle error 261 | }) 262 | ``` 263 | 264 | You can catch all errors due to the native app not being installed (or at least not being callable): 265 | ```js 266 | nativeApp.onAppNotFound.addListener((err)=>{ 267 | // for instance, open a tab to a site where to download the app 268 | }) 269 | ``` 270 | 271 | You can just check whether the app is present, without triggering the `onAppNotFound()` if it is not: 272 | ```js 273 | nativeApp.callCatchAppNotFound((err)=>{ 274 | // this is called if the app could not be launched 275 | },"my_function",...params); 276 | ``` 277 | 278 | On the native app side, assuming it is developed on node.js, you can use the exact same rpc mechanism, using `rpc.listen()` and `rpc.call()` to communicate both ways with the add-on. 279 | 280 | For now, the only implementation of such a native is available on the [`vdhcoapp` project](https://github.com/mi-g/vdhcoapp) under GPL-2.0 license. It is planned to release a version using a less restrictive license. 281 | 282 | ## UI utilities 283 | 284 | `weh.ui` provides the ability to open a tab or a panel, so that the created content can directly be callable from the background using `weh.rpc`. 285 | 286 | ```js 287 | weh.ui.open("some_name",{ 288 | url: "content/content.html", 289 | type: "tab" 290 | }); 291 | weh.rpc.call("some_name","my_content_function",...params); 292 | ``` 293 | -------------------------------------------------------------------------------- /gulpfile.js: -------------------------------------------------------------------------------- 1 | 2 | const gulp = require("gulp"); 3 | const clean = require('gulp-clean'); 4 | const runSequence = require('gulp4-run-sequence'); 5 | const rename = require("gulp-rename"); 6 | const through = require('through2'); 7 | const gulpif = require('gulp-if'); 8 | const lazypipe = require('lazypipe'); 9 | const vinylString = require("vinyl-string"); 10 | const source = require('vinyl-source-stream'); 11 | const filter = require('gulp-filter'); 12 | const debug = require('gulp-debug'); 13 | const sass = require('gulp-sass'); 14 | const less = require("gulp-less"); 15 | const stylus = require("gulp-stylus"); 16 | const babel = require('gulp-babel'); 17 | const es2015 = require('babel-preset-es2015'); 18 | const react = require('babel-preset-react'); 19 | const typescript = require("gulp-typescript"); 20 | const coffee = require("gulp-coffee"); 21 | const sourcemaps = require('gulp-sourcemaps'); 22 | const gutil = require('gulp-util'); 23 | const install = require('gulp-install'); 24 | const merge = require('merge-stream'); 25 | const ejs = require('gulp-ejs'); 26 | const sort = require('gulp-sort'); 27 | 28 | const package = require('./package.json'); 29 | const webpack = require('webpack'); 30 | const webpackStream = require('webpack-stream'); 31 | const uglify = require("terser-webpack-plugin"); 32 | 33 | const named = require('vinyl-named'); 34 | var argv = require('yargs').argv; 35 | const fs = require("fs"); 36 | const path = require("path"); 37 | const exec = require('child_process').exec; 38 | const stringify = require('json-stable-stringify'); 39 | 40 | const now = "" + new Date(); 41 | 42 | if(process.env.wehCwd) 43 | process.chdir(process.env.wehCwd); 44 | 45 | function OverrideOptions() { 46 | var globalOptions = {}; 47 | var globalOptionsFile = process.env.HOME ? 48 | path.join(process.env.HOME,".weh.json") : 49 | path.join(process.env.HOMEPATH,"AppData","Local","weh","config.json"); 50 | try { 51 | fs.lstatSync(globalOptionsFile); 52 | try { 53 | globalOptions = JSON.parse(fs.readFileSync(globalOptionsFile,"utf8")); 54 | } catch(e) { 55 | console.warn("Error parsing",globalOptionsFile,"option file:",e); 56 | } 57 | } catch(e) {} 58 | var wehOptions = {}; 59 | // on init project, the options file is in the template not the project dir 60 | var optionsFile = argv._.indexOf("init")<0 ? 61 | path.join(etcDir,"weh-options.json") : 62 | path.join(__dirname,"templates",template,"etc/weh-options.json"); 63 | try { 64 | fs.lstatSync(optionsFile); 65 | try { 66 | wehOptions = JSON.parse(fs.readFileSync(optionsFile,"utf8")); 67 | } catch(e) { 68 | console.warn("Error parsing",optionsFile,"option file:",e); 69 | } 70 | } catch(e) {} 71 | var newArgv = {} 72 | Object.assign( 73 | newArgv, 74 | Object.assign({},globalOptions.all,wehOptions.all), 75 | dev ? Object.assign({},globalOptions.dev,wehOptions.dev) : Object.assign({},globalOptions.prod,wehOptions.prod), 76 | argv); 77 | argv = newArgv; 78 | } 79 | 80 | var dev = !argv.prod; 81 | var prjDir = path.resolve(argv.prjdir || '.'); 82 | var etcDir = path.join(prjDir,argv.etcdir || "etc"); 83 | var template = argv.template || "skeleton"; 84 | OverrideOptions(); 85 | var buildPost = argv.buildpost && "-"+argv.buildpost || ""; 86 | var buildDir = path.join(prjDir,argv.builddir || "build"+buildPost); 87 | var buildTmpDir = path.join(prjDir,argv.buildtmpdir || "build-tmp"+buildPost); 88 | var buildTmpAddonDir = path.join(buildTmpDir,"addon"); 89 | var buildTmpModDir = path.join(buildTmpDir,"modules"); 90 | var buildTmpWehDir = path.join(buildTmpDir,"weh"); 91 | var srcDir = path.join(prjDir,argv.srcdir || "src"); 92 | var srcModDir = path.join(prjDir,argv.srcmoddir || "src-modules"); 93 | var locDir = path.join(prjDir,argv.locdir || "locales"); 94 | var ejsData = {}; 95 | const mapExtensions = /.*\.(js|jsx|ts|coffee)$/; 96 | 97 | if(typeof argv.ejsdata !== "undefined") { 98 | if(!Array.isArray(argv.ejsdata)) 99 | argv.ejsdata = [argv.ejsdata]; 100 | argv.ejsdata.forEach((statement)=>{ 101 | var m = /^(.*?)=(.*)$/.exec(statement); 102 | if(m) 103 | ejsData[m[1]] = m[2]; 104 | else 105 | console.warn("Invalid statement --args",statement); 106 | }); 107 | } 108 | 109 | var buildTmpError = null; 110 | 111 | gulp.task('clean', function() { 112 | return gulp.src([buildDir+"/*",buildTmpDir+"/*"],{read: false}) 113 | .pipe(clean()); 114 | }); 115 | 116 | var WebPack = (function() { 117 | var paths = {}; 118 | return lazypipe() 119 | .pipe(named) 120 | .pipe(function() { 121 | return rename(function(filePath) { 122 | paths[filePath.basename] = filePath.dirname; 123 | }); 124 | }) 125 | .pipe(function() { 126 | return webpackStream({ 127 | optimization: { 128 | chunkIds: "deterministic", 129 | minimize: true, 130 | /* !!! this makes chrome builds defective !!! 131 | runtimeChunk: "single", 132 | */ 133 | mangleExports: "deterministic", 134 | moduleIds: "size", 135 | }, 136 | context: srcDir, 137 | output: { 138 | filename: '[name].js' 139 | }, 140 | resolve: { 141 | modules: [ 142 | buildTmpModDir, 143 | buildTmpWehDir, 144 | buildTmpDir+"/node_modules", 145 | __dirname+"/node_modules" 146 | ], 147 | }, 148 | module: { 149 | rules: [ 150 | { 151 | test: /\.css$/, 152 | use: [ __dirname+"/node_modules/style-loader", __dirname+"/node_modules/css-loader"], 153 | },{ 154 | test: /\.(png|woff|woff2|eot|ttf|svg)$/, 155 | use: [__dirname+"/node_modules/url-loader?limit=100000"] 156 | }] 157 | }, 158 | plugins: dev ? [ 159 | new webpack.DefinePlugin({ 160 | 'process.env': { 161 | NODE_ENV: `""` 162 | } 163 | }) 164 | ] : [ 165 | new webpack.DefinePlugin({ 166 | 'process.env': { 167 | NODE_ENV: `"production"` 168 | } 169 | }), 170 | new uglify() 171 | ] 172 | },webpack,(err,stats) => { 173 | if(stats.compilation.errors.length) { 174 | gutil.log(stats.toString({ 175 | colors: gutil.colors.supportsColor 176 | })); 177 | if(argv.onerror) 178 | exec(argv.onerror,function(error) { 179 | if(error) 180 | console.warn("Could not execute onerror handle:",error.message); 181 | }); 182 | } else { 183 | if(argv.onsuccess) 184 | exec(argv.onsuccess,function(error) { 185 | if(error) 186 | console.warn("Could not execute onsuccess handle:",error.message); 187 | }); 188 | } 189 | return true; 190 | }); 191 | }) 192 | .pipe(function() { 193 | // workaround to prevent undesired XXX.js.LICENSE.txt being generated by webpack-stream 6 194 | return filter(['**','!**/*LICENSE.txt']); 195 | }) 196 | .pipe(function() { 197 | return rename(function(filePath) { 198 | filePath.dirname = paths[filePath.basename] || filePath.dirname; 199 | }); 200 | }) 201 | ; 202 | })(); 203 | 204 | gulp.task("build-locales",function() { 205 | return gulp.src(locDir+"/**/*") 206 | .pipe(gulp.dest(buildTmpAddonDir+"/_locales")); 207 | }); 208 | 209 | gulp.task("build-final",function(callback) { 210 | if(buildTmpError) { 211 | console.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); 212 | console.error("!!! INTERMEDIATE BUILD HAS AN ERROR !!!"); 213 | console.error("!!! Skipping final build !!!"); 214 | console.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); 215 | callback(); 216 | return; 217 | } 218 | gulp.src(buildTmpAddonDir+"/**/*") 219 | .pipe(sort()) 220 | .pipe(gulpif('*.js',gulpif(dev,sourcemaps.init({loadMaps:true})))) 221 | .pipe(gulpif('*.js',WebPack())) 222 | .on("error",function(error) { 223 | this.emit("end"); 224 | }) 225 | .pipe(gulpif(dev,sourcemaps.write('.'))) 226 | .pipe(gulp.dest(buildDir)) 227 | .on("end",()=>{ 228 | fs.writeFileSync(buildDir+"/build.date",argv["force-build-date"] || now); 229 | callback(); 230 | }) 231 | }); 232 | 233 | function ProcessFiles(stream) { 234 | var error = null; 235 | function Error(err) { 236 | HandleError(err); 237 | buildTmpError = err; 238 | this.emit("end"); 239 | } 240 | return stream 241 | .pipe(gulpif(mapExtensions,gulpif(dev,sourcemaps.init()))) 242 | .pipe(gulpif('*.ejs',ejs(ejsData))) 243 | .pipe(rename(function(filePath) { 244 | if(filePath.extname==".ejs") 245 | filePath.extname = ""; 246 | })) 247 | .pipe(gulpif('*.jsx',babel({ 248 | presets: [react], 249 | compact: false 250 | }))) 251 | .on("error",Error) 252 | .pipe(gulpif('*.ts',typescript())) 253 | .on("error",Error) 254 | .pipe(gulpif('*.coffee',coffee({bare:true}))) 255 | .on("error",Error) 256 | .pipe(gulpif('*.js',babel({ 257 | presets: [es2015], 258 | compact: false 259 | }))) 260 | .on("error",Error) 261 | .pipe(gulpif('*.scss',sass())) 262 | .on("error",Error) 263 | .pipe(gulpif('*.less',less())) 264 | .on("error",Error) 265 | .pipe(gulpif('*.styl',stylus())) 266 | .on("error",Error) 267 | .pipe(gulpif(dev,sourcemaps.write('.'))) 268 | .on("error",Error) 269 | } 270 | 271 | gulp.task("build-tmp-src",function() { 272 | buildTmpError = null; 273 | return ProcessFiles(gulp.src([srcDir+"/**/*"])) 274 | .pipe(gulp.dest(buildTmpAddonDir)) 275 | ; 276 | }); 277 | 278 | gulp.task("build-tmp-src-mod",function() { 279 | buildTmpError = null; 280 | return ProcessFiles(gulp.src([srcModDir+"/**/*"])) 281 | .pipe(gulp.dest(buildTmpModDir)) 282 | ; 283 | }); 284 | 285 | gulp.task("build-tmp-install",function() { 286 | return gulp.src(prjDir+'/package.json') 287 | .pipe(gulp.dest(buildTmpDir)) 288 | .pipe(install()); 289 | }); 290 | 291 | gulp.task("build-tmp-copylock",function() { 292 | return gulp.src(prjDir+'/package-lock.json') 293 | .pipe(gulp.dest(buildTmpDir)); 294 | }); 295 | 296 | gulp.task("build-tmp-weh",function() { 297 | return ProcessFiles(gulp.src(__dirname+"/src/**/*")) 298 | .pipe(gulp.dest(buildTmpWehDir)); 299 | }); 300 | 301 | gulp.task("make-i86n-keys",function(callback) { 302 | var keys = {}; 303 | fs.readdir(locDir,(err,files) => { 304 | if(err) 305 | throw err; 306 | var promises = files.map((lang) => { 307 | return new Promise((resolve,reject)=>{ 308 | fs.readFile(path.join(locDir,lang,"messages.json"),(err,content)=>{ 309 | if(err) 310 | return reject(err); 311 | try { 312 | var messages = JSON.parse(content); 313 | Object.keys(messages).forEach((key)=>{ 314 | keys[key] = 1; 315 | }); 316 | resolve(); 317 | } catch(e) { 318 | reject(e); 319 | } 320 | }); 321 | }); 322 | }); 323 | Promise.all(promises) 324 | .then(()=>{ 325 | vinylString('module.exports = ' + stringify(keys,{ space: ' ' }),{ 326 | path: 'weh-i18n-keys.js' 327 | }) 328 | .pipe(gulp.dest(buildTmpModDir)) 329 | .on('end',callback); 330 | }) 331 | .catch((err)=>{ 332 | throw err; 333 | }); 334 | }); 335 | }); 336 | 337 | gulp.task("make-build-manifest",function(callback) { 338 | const buildManifest = { 339 | prod: !dev, 340 | buildDate: argv["force-build-date"] || now, 341 | buildOptions: ejsData 342 | }; 343 | const buildManifestCode = "module.exports = "+stringify(buildManifest,{ space: ' ' }); 344 | fs.writeFile(buildTmpWehDir+"/weh-build.js",buildManifestCode,(err)=>{ 345 | if(err) 346 | throw err; 347 | callback(); 348 | }); 349 | }); 350 | 351 | gulp.task("build",function(callback) { 352 | return runSequence( 353 | ["build-tmp-src","build-tmp-src-mod","build-tmp-weh","build-locales","make-i86n-keys"], 354 | ["make-build-manifest"], 355 | ["build-tmp-copylock"], 356 | ["build-tmp-install"], 357 | ["build-final"], 358 | callback); 359 | }); 360 | 361 | gulp.task("watch-locales",function(callback) { 362 | return runSequence( 363 | ["build-locales","make-i86n-keys"], 364 | ["build-final"], 365 | callback); 366 | }); 367 | 368 | gulp.task("watch-src",function(callback) { 369 | return runSequence( 370 | ["build-tmp-src","build-tmp-src-mod","build-tmp-weh"], 371 | ["build-tmp-install"], 372 | ["build-final"], 373 | callback 374 | ); 375 | }); 376 | 377 | gulp.task("watch", function(callback) { 378 | gulp.watch([srcDir+"/**/*",srcModDir+"/**/*","src/**/*",__dirname+"/src/**/*"],gulp.series("watch-src")); 379 | gulp.watch(locDir+"/**/*",gulp.series("watch-locales")); 380 | callback(); 381 | }); 382 | 383 | // list available templates 384 | gulp.task("templates",function(callback) { 385 | var templates = fs.readdirSync(path.join(__dirname,"templates")); 386 | templates.forEach(function(template) { 387 | var manifest = null; 388 | try { 389 | manifest = JSON.parse(fs.readFileSync(path.join(__dirname,"templates",template,"src/manifest.json"),"utf8")); 390 | } catch(e) {} 391 | console.info(template+":",manifest && manifest.description ? manifest.description : "no description found"); 392 | }); 393 | callback(); 394 | }); 395 | 396 | gulp.task("default", function(callback) { 397 | if(argv.help) 398 | return runSequence("help"); 399 | if(argv.templates) 400 | return runSequence("templates"); 401 | 402 | console.info("Directories:"); 403 | console.info(" src:",srcDir); 404 | console.info(" src-modules:",srcModDir); 405 | console.info(" build:",buildDir); 406 | console.info(" locales:",locDir); 407 | console.info(" etc:",etcDir); 408 | 409 | try { 410 | JSON.parse(fs.readFileSync(path.join(srcDir,"manifest.json"),"utf8")); 411 | } catch(e) { 412 | try { 413 | fs.readFileSync(path.join(srcDir,"manifest.json.ejs"),"utf8"); 414 | } catch(e) { 415 | console.error("Directory",srcDir,"does not contain a valid manifest.json nor manifest.json.ejs file. You may want to init a new weh project first with 'weh init --prjdir my-project'"); 416 | process.exit(-1); 417 | } 418 | } 419 | 420 | var tasks = ["clean","build"]; 421 | if(argv["watch"]!==false && dev) 422 | tasks.push("watch"); 423 | tasks.push(callback); 424 | runSequence.apply(null,tasks); 425 | }); 426 | 427 | // create new project 428 | gulp.task("init", function(callback) { 429 | runSequence("copy-template","build",callback); 430 | }); 431 | 432 | // get some help 433 | gulp.task("help", function(callback) { 434 | var help = [ 435 | "weh version "+package.version, 436 | "usage: gulp [] []", 437 | "", 438 | "commands:", 439 | " build: generate project build", 440 | " clean: remove project build recursively", 441 | " watch: watch project and build dynamically on changes", 442 | " init: generate project from template", 443 | " templates: display available templates", 444 | "", 445 | "default commands: clean + build + watch", 446 | "", 447 | "options:", 448 | " --prjdir : project directory (required for most commands)", 449 | " --srcdir : add-on source sub-directory (relative to project directory), defaults to 'src'", 450 | " --srcmoddir : add-on source modules sub-directory (relative to project directory), defaults to 'src-modules'", 451 | " --prod: addon generated for production", 452 | " --template