From 558061b80e4ffa146950ffcdb99e804796a7e084 Mon Sep 17 00:00:00 2001 From: Hiroyasu Nishiyama Date: Tue, 6 Feb 2018 21:18:32 +0900 Subject: [PATCH 1/3] initial support of widget generation --- README.md | 19 ++- bin/node-red-nodegen.js | 6 +- lib/nodegen.js | 104 ++++++++++++- samples/hello-conf.json | 7 + samples/hello.html | 4 + templates/widget/LICENSE.mustache | 208 +++++++++++++++++++++++++ templates/widget/README.md.mustache | 14 ++ templates/widget/icons/icon.png | Bin 0 -> 413 bytes templates/widget/node.html.mustache | 111 +++++++++++++ templates/widget/node.js.mustache | 78 ++++++++++ templates/widget/package.json.mustache | 14 ++ test/lib/nodegen_spec.js | 20 +++ 12 files changed, 582 insertions(+), 3 deletions(-) create mode 100644 samples/hello-conf.json create mode 100644 samples/hello.html create mode 100644 templates/widget/LICENSE.mustache create mode 100644 templates/widget/README.md.mustache create mode 100644 templates/widget/icons/icon.png create mode 100644 templates/widget/node.html.mustache create mode 100644 templates/widget/node.js.mustache create mode 100644 templates/widget/package.json.mustache diff --git a/README.md b/README.md index 67c6378..65939bb 100644 --- a/README.md +++ b/README.md @@ -9,13 +9,14 @@ You may need to run this with `sudo`, or from within an Administrator command sh ## Usage Usage: - node-red-nodegen [-o ] [--prefix ] [--name ] [--module ] [--version [--tgz] [--help] + node-red-nodegen [-o ] [--prefix ] [--name ] [--module ] [--version ] [--conf ] [--tgz] [--help] Description: Node generator for Node-RED Supported source: - Function node (js file in library, "~/.node-red/lib/function/") + - Template node (HTML file in library, "~/.node-red/lib/uitemplates/") - Swagger definition Options: @@ -24,6 +25,7 @@ You may need to run this with `sudo`, or from within an Administrator command sh --name : Node name (default: name defined in source) --module : Module name (default: "node-red-contrib-") --version : Node version (format: "number.number.number" like "4.5.1") + --conf : Path of configulation file --tgz : Save node as tgz file --help : Show help @@ -51,3 +53,18 @@ You may need to run this with `sudo`, or from within an Administrator command sh -> You can use swagger-petstore node on Node-RED flow editor. Note: Currently node generator supports GET and POST methods using JSON format without authentication. + +### Example 3. [experimental] Create original dashboard node from template widget definition (HTML code) + +- On Node-RED flow editor, save template node to library with file name (hello.js). +- copy saved template to /hello.html (change file extension from .js to .html) +- node-red-nodegen /hello.html + (you can change template variables: template_scope, store_out_msgs, and fwd_in_msgs by specifying configuration file :--conf ; see samples/hello-conf.json) +- cd node-red-contrib-hello +- sudo npm link +- cd ~/.node-red +- npm link node-red-contrib-hello +- set environment variable `NR_DASHBOARD_DIR` to path of install directory of Node-RED dashboard. +- node-red + +-> You can use hello dashboard node on Node-RED flow editor. diff --git a/bin/node-red-nodegen.js b/bin/node-red-nodegen.js index 4b4cc34..8a1e94b 100644 --- a/bin/node-red-nodegen.js +++ b/bin/node-red-nodegen.js @@ -43,6 +43,7 @@ function help() { ' [--prefix ]' + ' [--name ]' + ' [--module ]' + + ' [--conf ' + ' [--version ' + //' [--icon ' + //' [--color ' + @@ -95,6 +96,10 @@ if (!argv.h && !argv.help) { data.src = fs.readFileSync(sourcePath); var filename = nodegen.function2node(data, options); console.log('Success: ' + filename); + } else if (sourcePath.endsWith('.html')) { + data.src = fs.readFileSync(sourcePath); + var filename = nodegen.widget2node(data, options); + console.log('Success: ' + filename); } else { console.error('error: Unsupported file type'); } @@ -104,4 +109,3 @@ if (!argv.h && !argv.help) { } else { help(); } - diff --git a/lib/nodegen.js b/lib/nodegen.js index 584db4f..9867522 100644 --- a/lib/nodegen.js +++ b/lib/nodegen.js @@ -386,8 +386,110 @@ function swagger2node(data, options) { } } +function widget2node(data, options) { + // Read config + var conf = {}; + if (options.conf) { + try { + conf = require(options.conf); + } + catch (e) { + console.error(e); + } + } + // Read meta data in js file + var meta = {}; + var parts = new String(data.src).split('\n'); + parts.forEach(function (part) { + var match = /^\/\/ (\w+): (.*)/.exec(part.toString()); + if (match) { + if (match[1] === 'name') { + meta.name = match[2].replace(/([A-Z])/g, ' $1').toLowerCase().replace(/[^ a-z0-9]+/g, '').replace(/^ | $/, '').replace(/ +/g, '-'); + } else { + meta[match[1]] = match[2]; + } + } + }); + + if (!data.name || data.name === '') { + data.name = meta.name; + } + + if (data.module) { + if (data.prefix) { + console.error('error: module name and prefix are conflicted.'); + } + } else { + if (data.prefix) { + data.module = data.prefix + data.name; + } else { + data.module = 'node-red-contrib-' + data.name; + } + } + + if (!data.version || data.version === '') { + data.version = '0.0.1'; + } + + if (data.name === 'function') { + console.error('\'function\' is duplicated node name. Use another name.'); + } else { + var params = { + nodeName: data.name, + projectName: data.module, + projectVersion: data.version, + func: jsStringEscape(data.src), + outputs: meta.outputs, + template_scope: "local", + store_out_msgs: "true", + fwd_in_msgs: "true" + }; + if (conf) { + for (var name in conf.vars) { + params[name] = conf.vars[name]; + } + } + + var basedir = __dirname + '/../templates/widget'; + + createCommonFiles(basedir, data); + + // Create package.json + var packageTemplate = fs.readFileSync(basedir+'/package.json.mustache', 'utf-8'); + var packageSourceCode = mustache.render(packageTemplate, params); + fs.writeFileSync(data.dst + '/' + data.module + '/package.json', packageSourceCode); + + // Create node.js + var nodeTemplate = fs.readFileSync(basedir+'/node.js.mustache', 'utf-8'); + var nodeSourceCode = mustache.render(nodeTemplate, params); + fs.writeFileSync(data.dst + '/' + data.module + '/node.js', nodeSourceCode); + + // Create node.html + var htmlTemplate = fs.readFileSync(basedir+'/node.html.mustache', 'utf-8'); + var htmlSourceCode = mustache.render(htmlTemplate, params); + fs.writeFileSync(data.dst + '/' + data.module + '/node.html', htmlSourceCode); + + // Create README.md + var readmeTemplate = fs.readFileSync(basedir+'/README.md.mustache', 'utf-8'); + var readmeSourceCode = mustache.render(readmeTemplate, params); + fs.writeFileSync(data.dst + '/' + data.module + '/README.md', readmeSourceCode); + + // Create LICENSE file + var licenseTemplate = fs.readFileSync(basedir+'/LICENSE.mustache', 'utf-8'); + var licenseSourceCode = mustache.render(licenseTemplate, params); + fs.writeFileSync(data.dst + '/' + data.module + '/LICENSE', licenseSourceCode); + + if (options.tgz) { + runNpmPack(data); + return data.dst + '/' + data.module + '-' + data.version + '.tgz'; + } else { + return data.dst + '/' + data.module; + } + } +} + module.exports = { function2node: function2node, + widget2node: widget2node, swagger2node: swagger2node }; - diff --git a/samples/hello-conf.json b/samples/hello-conf.json new file mode 100644 index 0000000..b01c00a --- /dev/null +++ b/samples/hello-conf.json @@ -0,0 +1,7 @@ +{ + "vars" : { + "template_scope" : "local", + "store_out_msgs" : "true", + "fwd_in_msgs" : "true" + } +} diff --git a/samples/hello.html b/samples/hello.html new file mode 100644 index 0000000..dc5e4a0 --- /dev/null +++ b/samples/hello.html @@ -0,0 +1,4 @@ +// name: hello +
+ Hello Node-RED +
diff --git a/templates/widget/LICENSE.mustache b/templates/widget/LICENSE.mustache new file mode 100644 index 0000000..a548602 --- /dev/null +++ b/templates/widget/LICENSE.mustache @@ -0,0 +1,208 @@ +This node is under Apache-2.0 licence because it was created from the following +fuction node code using [node-red-nodegen](https://github.com/node-red/node-red-nodegen). +https://github.com/node-red/node-red/blob/master/nodes/core/core/80-function.html +https://github.com/node-red/node-red/blob/master/nodes/core/core/80-function.js + +--------------------------------------------------------------------------- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/templates/widget/README.md.mustache b/templates/widget/README.md.mustache new file mode 100644 index 0000000..8b85c2f --- /dev/null +++ b/templates/widget/README.md.mustache @@ -0,0 +1,14 @@ +{{&projectName}} +===================== + +Node-RED widget node for {{&nodeName}} + +{{&description}} + +Install +------- + +Run the following command in your Node-RED user directory - typically `~/.node-red` + + npm install {{&projectName}} + diff --git a/templates/widget/icons/icon.png b/templates/widget/icons/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..0e5ff114e640730d736cc48e8070d370eabf4984 GIT binary patch literal 413 zcmV;O0b>4%P)-{MTWu8@xNo;X>|?KuHiZW?TFFZ2 z + + + + + + diff --git a/templates/widget/node.js.mustache b/templates/widget/node.js.mustache new file mode 100644 index 0000000..ddeecfe --- /dev/null +++ b/templates/widget/node.js.mustache @@ -0,0 +1,78 @@ +/** + * Copyright JS Foundation and other contributors, http://js.foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ + +module.exports = function(RED) { + + var TEMPLATE_SCOPE = "{{&template_scope}}"; + var TEMPLATE = '{{&func}}'; + var STORE_OUT_MSGS = {{&store_out_msgs}}; + var FWD_IN_MSGS = {{&fwd_in_msgs}}; + + var ui = undefined; + + function TemplateNode(config) { + if(ui === undefined) { + // var base = RED.nodes.getDashboardPath(); + var base = process.env["NR_DASHBOARD_DIR"]; + ui = require(base+'/ui')(RED); + } + RED.nodes.createNode(this, config); + var node = this; + var group = RED.nodes.getNode(config.group); + if (!group && TEMPLATE_SCOPE !== 'global') { return; } + var tab = null; + if (TEMPLATE_SCOPE !== 'global') { + tab = RED.nodes.getNode(group.config.tab); + if (!tab) { return; } + if (!config.width) { + config.width = group.config.width; + } + } + var hei = Number(config.height || 0); + var done = ui.add({ + forwardInputMessages: FWD_IN_MSGS, + storeFrontEndInputAsState: STORE_OUT_MSGS, + emitOnlyNewValues: false, + node: node, + tab: tab, + group: group, + control: { + type: 'template', + order: config.order, + width: config.width || 6, + height: hei, + format: TEMPLATE, + templateScope: TEMPLATE_SCOPE + }, + beforeEmit: function(msg, value) { + var properties = Object.getOwnPropertyNames(msg).filter(function (p) { return p[0] != '_'; }); + var clonedMsg = { + templateScope: TEMPLATE_SCOPE + }; + for (var i=0; i Date: Tue, 6 Feb 2018 21:55:39 +0900 Subject: [PATCH 2/3] removed comment line --- lib/nodegen.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/lib/nodegen.js b/lib/nodegen.js index 9867522..864790d 100644 --- a/lib/nodegen.js +++ b/lib/nodegen.js @@ -397,9 +397,10 @@ function widget2node(data, options) { console.error(e); } } - // Read meta data in js file + // Read meta data in html file var meta = {}; var parts = new String(data.src).split('\n'); + var new_src = ""; parts.forEach(function (part) { var match = /^\/\/ (\w+): (.*)/.exec(part.toString()); if (match) { @@ -409,6 +410,9 @@ function widget2node(data, options) { meta[match[1]] = match[2]; } } + else { + new_src = new_src +part +"\n"; + } }); if (!data.name || data.name === '') { @@ -438,7 +442,7 @@ function widget2node(data, options) { nodeName: data.name, projectName: data.module, projectVersion: data.version, - func: jsStringEscape(data.src), + func: jsStringEscape(new_src), outputs: meta.outputs, template_scope: "local", store_out_msgs: "true", From 21ae0e7e3a64f6815f8e52f81dbc4cba6327da19 Mon Sep 17 00:00:00 2001 From: Hiroyasu Nishiyama Date: Fri, 9 Feb 2018 23:14:01 +0900 Subject: [PATCH 3/3] fix origin description in LICENSE --- templates/widget/LICENSE.mustache | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/templates/widget/LICENSE.mustache b/templates/widget/LICENSE.mustache index a548602..7aff54d 100644 --- a/templates/widget/LICENSE.mustache +++ b/templates/widget/LICENSE.mustache @@ -1,7 +1,7 @@ This node is under Apache-2.0 licence because it was created from the following -fuction node code using [node-red-nodegen](https://github.com/node-red/node-red-nodegen). -https://github.com/node-red/node-red/blob/master/nodes/core/core/80-function.html -https://github.com/node-red/node-red/blob/master/nodes/core/core/80-function.js +ui_template node code using [node-red-nodegen](https://github.com/node-red/node-red-nodegen). +https://github.com/node-red/node-red-dashboard/blob/master/nodes/ui_template.html +https://github.com/node-red/node-red-dashboard/blob/master/nodes/ui_template.js ---------------------------------------------------------------------------