├── .gitignore ├── LICENSE.txt ├── README.md ├── gulpfile.js ├── index.js ├── package-lock.json ├── package.json ├── src ├── css │ ├── weh-form-states.css │ ├── weh-header.css │ ├── weh-natmsg-shell.scss │ └── weh-shf.css ├── react │ ├── weh-header.jsx │ ├── weh-natmsg-shell.jsx │ ├── weh-prefs-settings.jsx │ └── weh-translation.jsx ├── weh-background.js ├── weh-content.js ├── weh-i18n.js ├── weh-inspect.js ├── weh-natmsg.js ├── weh-prefs.js ├── weh-rpc.js ├── weh-ui.js ├── weh-worker-rpc.js ├── weh-worker.js └── weh.js └── templates ├── inspector ├── locales │ └── en_US │ │ └── messages.json ├── package.json ├── src-modules │ └── default-prefs.js └── src │ ├── background │ └── main.js │ ├── content │ ├── images │ │ ├── icon-128.png │ │ ├── icon-32.png │ │ ├── icon-40.png │ │ └── icon-48.png │ ├── inspector.html │ ├── inspector.jsx │ ├── settings.html │ ├── settings.jsx │ ├── styles.scss │ ├── translation.html │ └── translation.jsx │ └── manifest.json └── skeleton ├── locales └── en_US │ └── messages.json ├── src-modules └── default-prefs.js └── src ├── background └── main.js ├── content ├── images │ ├── icon-128.png │ ├── icon-32.png │ ├── icon-40.png │ └── icon-48.png ├── popup.html ├── popup.jsx ├── settings.html ├── settings.jsx ├── styles.scss ├── translation.html └── translation.jsx └── manifest.json /.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 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Mozilla Public License, version 2.0 2 | 3 | 1. Definitions 4 | 5 | 1.1. “Contributor” 6 | 7 | means each individual or legal entity that creates, contributes to the 8 | creation of, or owns Covered Software. 9 | 10 | 1.2. “Contributor Version” 11 | 12 | means the combination of the Contributions of others (if any) used by a 13 | Contributor and that particular Contributor’s Contribution. 14 | 15 | 1.3. “Contribution” 16 | 17 | means Covered Software of a particular Contributor. 18 | 19 | 1.4. “Covered Software” 20 | 21 | means Source Code Form to which the initial Contributor has attached the 22 | notice in Exhibit A, the Executable Form of such Source Code Form, and 23 | Modifications of such Source Code Form, in each case including portions 24 | thereof. 25 | 26 | 1.5. “Incompatible With Secondary Licenses” 27 | means 28 | 29 | a. that the initial Contributor has attached the notice described in 30 | Exhibit B to the Covered Software; or 31 | 32 | b. that the Covered Software was made available under the terms of version 33 | 1.1 or earlier of the License, but not also under the terms of a 34 | Secondary License. 35 | 36 | 1.6. “Executable Form” 37 | 38 | means any form of the work other than Source Code Form. 39 | 40 | 1.7. “Larger Work” 41 | 42 | means a work that combines Covered Software with other material, in a separate 43 | file or files, that is not Covered Software. 44 | 45 | 1.8. “License” 46 | 47 | means this document. 48 | 49 | 1.9. “Licensable” 50 | 51 | means having the right to grant, to the maximum extent possible, whether at the 52 | time of the initial grant or subsequently, any and all of the rights conveyed by 53 | this License. 54 | 55 | 1.10. “Modifications” 56 | 57 | means any of the following: 58 | 59 | a. any file in Source Code Form that results from an addition to, deletion 60 | from, or modification of the contents of Covered Software; or 61 | 62 | b. any new file in Source Code Form that contains any Covered Software. 63 | 64 | 1.11. “Patent Claims” of a Contributor 65 | 66 | means any patent claim(s), including without limitation, method, process, 67 | and apparatus claims, in any patent Licensable by such Contributor that 68 | would be infringed, but for the grant of the License, by the making, 69 | using, selling, offering for sale, having made, import, or transfer of 70 | either its Contributions or its Contributor Version. 71 | 72 | 1.12. “Secondary License” 73 | 74 | means either the GNU General Public License, Version 2.0, the GNU Lesser 75 | General Public License, Version 2.1, the GNU Affero General Public 76 | License, Version 3.0, or any later versions of those licenses. 77 | 78 | 1.13. “Source Code Form” 79 | 80 | means the form of the work preferred for making modifications. 81 | 82 | 1.14. “You” (or “Your”) 83 | 84 | means an individual or a legal entity exercising rights under this 85 | License. For legal entities, “You” includes any entity that controls, is 86 | controlled by, or is under common control with You. For purposes of this 87 | definition, “control” means (a) the power, direct or indirect, to cause 88 | the direction or management of such entity, whether by contract or 89 | otherwise, or (b) ownership of more than fifty percent (50%) of the 90 | outstanding shares or beneficial ownership of such entity. 91 | 92 | 93 | 2. License Grants and Conditions 94 | 95 | 2.1. Grants 96 | 97 | Each Contributor hereby grants You a world-wide, royalty-free, 98 | non-exclusive license: 99 | 100 | a. under intellectual property rights (other than patent or trademark) 101 | Licensable by such Contributor to use, reproduce, make available, 102 | modify, display, perform, distribute, and otherwise exploit its 103 | Contributions, either on an unmodified basis, with Modifications, or as 104 | part of a Larger Work; and 105 | 106 | b. under Patent Claims of such Contributor to make, use, sell, offer for 107 | sale, have made, import, and otherwise transfer either its Contributions 108 | or its Contributor Version. 109 | 110 | 2.2. Effective Date 111 | 112 | The licenses granted in Section 2.1 with respect to any Contribution become 113 | effective for each Contribution on the date the Contributor first distributes 114 | such Contribution. 115 | 116 | 2.3. Limitations on Grant Scope 117 | 118 | The licenses granted in this Section 2 are the only rights granted under this 119 | License. No additional rights or licenses will be implied from the distribution 120 | or licensing of Covered Software under this License. Notwithstanding Section 121 | 2.1(b) above, no patent license is granted by a Contributor: 122 | 123 | a. for any code that a Contributor has removed from Covered Software; or 124 | 125 | b. for infringements caused by: (i) Your and any other third party’s 126 | modifications of Covered Software, or (ii) the combination of its 127 | Contributions with other software (except as part of its Contributor 128 | Version); or 129 | 130 | c. under Patent Claims infringed by Covered Software in the absence of its 131 | Contributions. 132 | 133 | This License does not grant any rights in the trademarks, service marks, or 134 | logos of any Contributor (except as may be necessary to comply with the 135 | notice requirements in Section 3.4). 136 | 137 | 2.4. Subsequent Licenses 138 | 139 | No Contributor makes additional grants as a result of Your choice to 140 | distribute the Covered Software under a subsequent version of this License 141 | (see Section 10.2) or under the terms of a Secondary License (if permitted 142 | under the terms of Section 3.3). 143 | 144 | 2.5. Representation 145 | 146 | Each Contributor represents that the Contributor believes its Contributions 147 | are its original creation(s) or it has sufficient rights to grant the 148 | rights to its Contributions conveyed by this License. 149 | 150 | 2.6. Fair Use 151 | 152 | This License is not intended to limit any rights You have under applicable 153 | copyright doctrines of fair use, fair dealing, or other equivalents. 154 | 155 | 2.7. Conditions 156 | 157 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in 158 | Section 2.1. 159 | 160 | 161 | 3. Responsibilities 162 | 163 | 3.1. Distribution of Source Form 164 | 165 | All distribution of Covered Software in Source Code Form, including any 166 | Modifications that You create or to which You contribute, must be under the 167 | terms of this License. You must inform recipients that the Source Code Form 168 | of the Covered Software is governed by the terms of this License, and how 169 | they can obtain a copy of this License. You may not attempt to alter or 170 | restrict the recipients’ rights in the Source Code Form. 171 | 172 | 3.2. Distribution of Executable Form 173 | 174 | If You distribute Covered Software in Executable Form then: 175 | 176 | a. such Covered Software must also be made available in Source Code Form, 177 | as described in Section 3.1, and You must inform recipients of the 178 | Executable Form how they can obtain a copy of such Source Code Form by 179 | reasonable means in a timely manner, at a charge no more than the cost 180 | of distribution to the recipient; and 181 | 182 | b. You may distribute such Executable Form under the terms of this License, 183 | or sublicense it under different terms, provided that the license for 184 | the Executable Form does not attempt to limit or alter the recipients’ 185 | rights in the Source Code Form under this License. 186 | 187 | 3.3. Distribution of a Larger Work 188 | 189 | You may create and distribute a Larger Work under terms of Your choice, 190 | provided that You also comply with the requirements of this License for the 191 | Covered Software. If the Larger Work is a combination of Covered Software 192 | with a work governed by one or more Secondary Licenses, and the Covered 193 | Software is not Incompatible With Secondary Licenses, this License permits 194 | You to additionally distribute such Covered Software under the terms of 195 | such Secondary License(s), so that the recipient of the Larger Work may, at 196 | their option, further distribute the Covered Software under the terms of 197 | either this License or such Secondary License(s). 198 | 199 | 3.4. Notices 200 | 201 | You may not remove or alter the substance of any license notices (including 202 | copyright notices, patent notices, disclaimers of warranty, or limitations 203 | of liability) contained within the Source Code Form of the Covered 204 | Software, except that You may alter any license notices to the extent 205 | required to remedy known factual inaccuracies. 206 | 207 | 3.5. Application of Additional Terms 208 | 209 | You may choose to offer, and to charge a fee for, warranty, support, 210 | indemnity or liability obligations to one or more recipients of Covered 211 | Software. However, You may do so only on Your own behalf, and not on behalf 212 | of any Contributor. You must make it absolutely clear that any such 213 | warranty, support, indemnity, or liability obligation is offered by You 214 | alone, and You hereby agree to indemnify every Contributor for any 215 | liability incurred by such Contributor as a result of warranty, support, 216 | indemnity or liability terms You offer. You may include additional 217 | disclaimers of warranty and limitations of liability specific to any 218 | jurisdiction. 219 | 220 | 4. Inability to Comply Due to Statute or Regulation 221 | 222 | If it is impossible for You to comply with any of the terms of this License 223 | with respect to some or all of the Covered Software due to statute, judicial 224 | order, or regulation then You must: (a) comply with the terms of this License 225 | to the maximum extent possible; and (b) describe the limitations and the code 226 | they affect. Such description must be placed in a text file included with all 227 | distributions of the Covered Software under this License. Except to the 228 | extent prohibited by statute or regulation, such description must be 229 | sufficiently detailed for a recipient of ordinary skill to be able to 230 | understand it. 231 | 232 | 5. Termination 233 | 234 | 5.1. The rights granted under this License will terminate automatically if You 235 | fail to comply with any of its terms. However, if You become compliant, 236 | then the rights granted under this License from a particular Contributor 237 | are reinstated (a) provisionally, unless and until such Contributor 238 | explicitly and finally terminates Your grants, and (b) on an ongoing basis, 239 | if such Contributor fails to notify You of the non-compliance by some 240 | reasonable means prior to 60 days after You have come back into compliance. 241 | Moreover, Your grants from a particular Contributor are reinstated on an 242 | ongoing basis if such Contributor notifies You of the non-compliance by 243 | some reasonable means, this is the first time You have received notice of 244 | non-compliance with this License from such Contributor, and You become 245 | compliant prior to 30 days after Your receipt of the notice. 246 | 247 | 5.2. If You initiate litigation against any entity by asserting a patent 248 | infringement claim (excluding declaratory judgment actions, counter-claims, 249 | and cross-claims) alleging that a Contributor Version directly or 250 | indirectly infringes any patent, then the rights granted to You by any and 251 | all Contributors for the Covered Software under Section 2.1 of this License 252 | shall terminate. 253 | 254 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user 255 | license agreements (excluding distributors and resellers) which have been 256 | validly granted by You or Your distributors under this License prior to 257 | termination shall survive termination. 258 | 259 | 6. Disclaimer of Warranty 260 | 261 | Covered Software is provided under this License on an “as is” basis, without 262 | warranty of any kind, either expressed, implied, or statutory, including, 263 | without limitation, warranties that the Covered Software is free of defects, 264 | merchantable, fit for a particular purpose or non-infringing. The entire 265 | risk as to the quality and performance of the Covered Software is with You. 266 | Should any Covered Software prove defective in any respect, You (not any 267 | Contributor) assume the cost of any necessary servicing, repair, or 268 | correction. This disclaimer of warranty constitutes an essential part of this 269 | License. No use of any Covered Software is authorized under this License 270 | except under this disclaimer. 271 | 272 | 7. Limitation of Liability 273 | 274 | Under no circumstances and under no legal theory, whether tort (including 275 | negligence), contract, or otherwise, shall any Contributor, or anyone who 276 | distributes Covered Software as permitted above, be liable to You for any 277 | direct, indirect, special, incidental, or consequential damages of any 278 | character including, without limitation, damages for lost profits, loss of 279 | goodwill, work stoppage, computer failure or malfunction, or any and all 280 | other commercial damages or losses, even if such party shall have been 281 | informed of the possibility of such damages. This limitation of liability 282 | shall not apply to liability for death or personal injury resulting from such 283 | party’s negligence to the extent applicable law prohibits such limitation. 284 | Some jurisdictions do not allow the exclusion or limitation of incidental or 285 | consequential damages, so this exclusion and limitation may not apply to You. 286 | 287 | 8. Litigation 288 | 289 | Any litigation relating to this License may be brought only in the courts of 290 | a jurisdiction where the defendant maintains its principal place of business 291 | and such litigation shall be governed by laws of that jurisdiction, without 292 | reference to its conflict-of-law provisions. Nothing in this Section shall 293 | prevent a party’s ability to bring cross-claims or counter-claims. 294 | 295 | 9. Miscellaneous 296 | 297 | This License represents the complete agreement concerning the subject matter 298 | hereof. If any provision of this License is held to be unenforceable, such 299 | provision shall be reformed only to the extent necessary to make it 300 | enforceable. Any law or regulation which provides that the language of a 301 | contract shall be construed against the drafter shall not be used to construe 302 | this License against a Contributor. 303 | 304 | 305 | 10. Versions of the License 306 | 307 | 10.1. New Versions 308 | 309 | Mozilla Foundation is the license steward. Except as provided in Section 310 | 10.3, no one other than the license steward has the right to modify or 311 | publish new versions of this License. Each version will be given a 312 | distinguishing version number. 313 | 314 | 10.2. Effect of New Versions 315 | 316 | You may distribute the Covered Software under the terms of the version of 317 | the License under which You originally received the Covered Software, or 318 | under the terms of any subsequent version published by the license 319 | steward. 320 | 321 | 10.3. Modified Versions 322 | 323 | If you create software not governed by this License, and you want to 324 | create a new license for such software, you may create and use a modified 325 | version of this License if you rename the license and remove any 326 | references to the name of the license steward (except to note that such 327 | modified license differs from this License). 328 | 329 | 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses 330 | If You choose to distribute Source Code Form that is Incompatible With 331 | Secondary Licenses under the terms of this version of the License, the 332 | notice described in Exhibit B of this License must be attached. 333 | 334 | Exhibit A - Source Code Form License Notice 335 | 336 | This Source Code Form is subject to the 337 | terms of the Mozilla Public License, v. 338 | 2.0. If a copy of the MPL was not 339 | distributed with this file, You can 340 | obtain one at 341 | http://mozilla.org/MPL/2.0/. 342 | 343 | If it is not possible or desirable to put the notice in a particular file, then 344 | You may include the notice in a location (such as a LICENSE file in a relevant 345 | directory) where a recipient would be likely to look for such a notice. 346 | 347 | You may add additional accurate notices of copyright ownership. 348 | 349 | Exhibit B - “Incompatible With Secondary Licenses” Notice 350 | 351 | This Source Code Form is “Incompatible 352 | With Secondary Licenses”, as defined by 353 | the Mozilla Public License, v. 2.0. 354 | 355 | -------------------------------------------------------------------------------- /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