initial commit
initial commit

file:b/LICENSE (new)
--- /dev/null
+++ b/LICENSE
@@ -1,1 +1,178 @@
 
+                                 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
+

file:b/README.md (new)
--- /dev/null
+++ b/README.md
@@ -1,1 +1,10 @@
+# node-red-contrib-jquerify
 
+A <a href="http://nodered.org" target="_blank">Node-RED</a> node that uses jQuery in a JavaScript function block to run against the messages being received by the node.
+
+## Install
+
+Run the following command in the root directory of your Node-RED install
+
+    npm install node-red-contrib-jquerify
+

 Binary files /dev/null and b/jquerify/icons/jquerify.png differ
--- /dev/null
+++ b/jquerify/jquerify.html
@@ -1,1 +1,154 @@
 
+<script type="text/x-red" data-template-name="jquerify">
+    <div class="form-row">
+        <label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
+        <input type="text" id="node-input-name" placeholder="Name">
+    </div>
+    <div class="form-row" style="margin-bottom: 0px;">
+        <label for="node-input-func"><i class="fa fa-wrench"></i> Function</label>
+        <input type="hidden" id="node-input-func" autofocus="autofocus">
+        <input type="hidden" id="node-input-noerr">
+    </div>
+    <div class="form-row node-text-editor-row">
+        <div style="height: 250px; min-height:150px;" class="node-text-editor" id="node-input-func-editor" ></div>
+    </div>
+    <div class="form-row">
+        <label for="node-input-outputs"><i class="fa fa-random"></i> Outputs</label>
+        <input id="node-input-outputs" style="width: 60px;" value="1">
+    </div>
+    <div class="form-tips">See the Info tab for help writing functions.</div>
+</script>
+
+<script type="text/x-red" data-help-name="jquerify">
+    <p>Use jQuery in a JavaScript function block to run against the messages being received by the node.</p>
+    <p><pre>var obj = $(msg.payload);</pre></p>
+    <p>The messages are passed in as a JavaScript object called <code>msg</code>.</p>
+    <p>By convention it will have a <code>msg.payload</code> property containing
+       the body of the message.</p>
+    <p>The function is expected to return a message object (or multiple message objects), but can choose
+       to return nothing in order to halt a flow.</p>
+    <h3>Details</h3>
+    <p>See the jQuery <a target="_blank" href="https://jquery.com/">online documentation</a>
+    for more information.</p>
+    <p>See the NodeRED <a target="_blank" href="http://nodered.org/docs/writing-functions.html">online documentation</a>
+    for more information on writing functions.</p>
+    <h4>Sending messages</h4>
+    <p>The function can either return the messages it wants to pass on to the next nodes
+    in the flow, or can call <code>node.send(messages)</code>.</p>
+    <p>It can return/send:</p>
+    <ul>
+      <li>a single message object - passed to nodes connected to the first output</li>
+      <li>an array of message objects - passed to nodes connected to the corresponding outputs</li>
+    </ul>
+    <p>If any element of the array is itself an array of messages, multiple
+          messages are sent to the corresponding output.</p>
+    <p>If null is returned, either by itself or as an element of the array, no
+          message is passed on.</p>
+    <h4>Logging and Error Handling</h4>
+    <p>To log any information, or report an error, the following functions are available:</p>
+      <ul>
+          <li><code>node.log("Log message")</code></li>
+          <li><code>node.warn("Warning")</code></li>
+          <li><code>node.error("Error")</code></li>
+      </ul>
+    </p>
+    <p>The Catch node can also be used to handle errors. To invoke a Catch node,
+    pass <code>msg</code> as a second argument to <code>node.error</code>:</p>
+    <pre>node.error("Error",msg);</pre>
+</script>
+
+<script type="text/javascript">
+    RED.nodes.registerType('jquerify',{
+        color:"#83CBF4",
+        category: 'function',
+        defaults: {
+            name: {value:""},
+            func: {value:"var obj = $(msg.payload);\n\nreturn msg;"},
+            outputs: {value:1},
+            noerr: {value:0,required:true,validate:function(v) { return ((!v) || (v === 0)) ? true : false; }}
+        },
+        inputs:1,
+        inputLabels: "Input",
+        outputs:1,
+        outputLabels: "Output",
+        icon: "jquerify.png",
+        label: function() {
+            return this.name;
+        },
+        labelStyle: function() {
+            return this.name?"node_label_italic":"";
+        },
+        oneditprepare: function() {
+            var that = this;
+            $( "#node-input-outputs" ).spinner({
+                min:1,
+                change: function(event, ui) {
+                    var value = this.value;
+                    if (!value.match(/^\d+$/)) { value = 1;  }
+                    else if (value < this.min) { value = this.min; }
+                    if (value !== this.value) { $(this).spinner("value", value); }
+                }
+            });
+
+            this.editor = RED.editor.createEditor({
+                id: 'node-input-func-editor',
+                mode: 'ace/mode/javascript',
+                value: $("#node-input-func").val(),
+                globals: {
+                    msg:true,
+                    context:true,
+                    RED: true,
+                    util: true,
+                    flow: true,
+                    global: true,
+                    console: true,
+                    Buffer: true,
+                    setTimeout: true,
+                    clearTimeout: true,
+                    setInterval: true,
+                    clearInterval: true
+                }
+            });
+
+            RED.library.create({
+                url:"functions", // where to get the data from
+                type:"function", // the type of object the library is for
+                editor:this.editor, // the field name the main text body goes to
+                mode:"ace/mode/javascript",
+                fields:['name','outputs']
+            });
+            this.editor.focus();
+        },
+        oneditsave: function() {
+            var annot = this.editor.getSession().getAnnotations();
+            this.noerr = 0;
+            $("#node-input-noerr").val(0);
+            for (var k=0; k < annot.length; k++) {
+                //console.log(annot[k].type,":",annot[k].text, "on line", annot[k].row);
+                if (annot[k].type === "error") {
+                    $("#node-input-noerr").val(annot.length);
+                    this.noerr = annot.length;
+                }
+            }
+            $("#node-input-func").val(this.editor.getValue());
+            this.editor.destroy();
+            delete this.editor;
+        },
+        oneditcancel: function() {
+            this.editor.destroy();
+            delete this.editor;
+        },
+        oneditresize: function(size) {
+            var rows = $("#dialog-form>div:not(.node-text-editor-row)");
+            var height = $("#dialog-form").height();
+            for (var i=0; i<rows.size(); i++) {
+                height -= $(rows[i]).outerHeight(true);
+            }
+            var editorRow = $("#dialog-form>div.node-text-editor-row");
+            height -= (parseInt(editorRow.css("marginTop"))+parseInt(editorRow.css("marginBottom")));
+            $(".node-text-editor").css("height",height+"px");
+            this.editor.resize();
+        }
+    });
+</script>
+

--- /dev/null
+++ b/jquerify/jquerify.js
@@ -1,1 +1,201 @@
-
+module.exports = function(RED) {
+    "use strict";
+    var util = require("util");
+    var vm = require("vm");
+    const jsdom = require("jsdom");
+    const { JSDOM } = jsdom;
+    const window = (new JSDOM('')).window;
+    var $ = require("jquery")(window);
+
+    function sendResults(node,_msgid,msgs) {
+        if (msgs == null) {
+            return;
+        } else if (!util.isArray(msgs)) {
+            msgs = [msgs];
+        }
+        var msgCount = 0;
+        for (var m=0; m<msgs.length; m++) {
+            if (msgs[m]) {
+                if (!util.isArray(msgs[m])) {
+                    msgs[m] = [msgs[m]];
+                }
+                for (var n=0; n < msgs[m].length; n++) {
+                    var msg = msgs[m][n];
+                    if (msg !== null && msg !== undefined) {
+                        if (typeof msg === 'object' && !Buffer.isBuffer(msg) && !util.isArray(msg)) {
+                            msg._msgid = _msgid;
+                            msgCount++;
+                        } else {
+                            var type = typeof msg;
+                            if (type === 'object') {
+                                type = Buffer.isBuffer(msg)?'Buffer':(util.isArray(msg)?'Array':'Date');
+                            }
+                            node.error(RED._("function.error.non-message-returned",{ type: type }))
+                        }
+                    }
+                }
+            }
+        }
+        if (msgCount>0) {
+            node.send(msgs);
+        }
+    }
+
+    function FunctionNode(n) {
+        RED.nodes.createNode(this,n);
+        var node = this;
+        this.name = n.name;
+        this.func = n.func;
+        var functionText = "var results = null;"+
+                           "results = (function(msg){ "+
+                                "var __msgid__ = msg._msgid;"+
+                                "var node = {"+
+                                    "log:__node__.log,"+
+                                    "error:__node__.error,"+
+                                    "warn:__node__.warn,"+
+                                    "on:__node__.on,"+
+                                    "status:__node__.status,"+
+                                    "send:function(msgs){ __node__.send(__msgid__,msgs);}"+
+                                "};\n"+
+                                this.func+"\n"+
+                           "})(msg);";
+        this.topic = n.topic;
+        this.outstandingTimers = [];
+        this.outstandingIntervals = [];
+        var sandbox = {
+            console:console,
+            util:util,
+            Buffer:Buffer,
+            RED: {
+                util: RED.util
+            },
+            __node__: {
+                log: function() {
+                    node.log.apply(node, arguments);
+                },
+                error: function() {
+                    node.error.apply(node, arguments);
+                },
+                warn: function() {
+                    node.warn.apply(node, arguments);
+                },
+                send: function(id, msgs) {
+                    sendResults(node, id, msgs);
+                },
+                on: function() {
+                    if (arguments[0] === "input") {
+                        throw new Error(RED._("function.error.inputListener"));
+                    }
+                    node.on.apply(node, arguments);
+                },
+                status: function() {
+                    node.status.apply(node, arguments);
+                }
+            },
+            context: {
+                set: function() {
+                    node.context().set.apply(node,arguments);
+                },
+                get: function() {
+                    return node.context().get.apply(node,arguments);
+                },
+                keys: function() {
+                    return node.context().keys.apply(node,arguments);
+                },
+                get global() {
+                    return node.context().global;
+                },
+                get flow() {
+                    return node.context().flow;
+                }
+            },
+            flow: {
+                set: function() {
+                    node.context().flow.set.apply(node,arguments);
+                },
+                get: function() {
+                    return node.context().flow.get.apply(node,arguments);
+                },
+                keys: function() {
+                    return node.context().flow.keys.apply(node,arguments);
+                }
+            },
+            global: {
+                set: function() {
+                    node.context().global.set.apply(node,arguments);
+                },
+                get: function() {
+                    return node.context().global.get.apply(node,arguments);
+                },
+                keys: function() {
+                    return node.context().global.keys.apply(node,arguments);
+                }
+            },
+            jQuery: function(m) {
+                return $(m);
+            },
+            "$": function(m){
+                return $(m);
+            }
+        };
+        var context = vm.createContext(sandbox);
+        try {
+            this.script = vm.createScript(functionText);
+            this.on("input", function(msg) {
+                try {
+                    var start = process.hrtime();
+                    context.msg = msg;
+                    this.script.runInContext(context);
+                    sendResults(this,msg._msgid,context.results);
+
+                    var duration = process.hrtime(start);
+                    var converted = Math.floor((duration[0] * 1e9 + duration[1])/10000)/100;
+                    this.metric("duration", msg, converted);
+                    if (process.env.NODE_RED_FUNCTION_TIME) {
+                        this.status({fill:"yellow",shape:"dot",text:""+converted});
+                    }
+                } catch(err) {
+
+                    var line = 0;
+                    var errorMessage;
+                    var stack = err.stack.split(/\r?\n/);
+                    if (stack.length > 0) {
+                        while (line < stack.length && stack[line].indexOf("ReferenceError") !== 0) {
+                            line++;
+                        }
+
+                        if (line < stack.length) {
+                            errorMessage = stack[line];
+                            var m = /:(\d+):(\d+)$/.exec(stack[line+1]);
+                            if (m) {
+                                var lineno = Number(m[1])-1;
+                                var cha = m[2];
+                                errorMessage += " (line "+lineno+", col "+cha+")";
+                            }
+                        }
+                    }
+                    if (!errorMessage) {
+                        errorMessage = err.toString();
+                    }
+                    this.error(errorMessage, msg);
+                }
+            });
+            this.on("close", function() {
+                while (node.outstandingTimers.length > 0) {
+                    clearTimeout(node.outstandingTimers.pop())
+                }
+                while (node.outstandingIntervals.length > 0) {
+                    clearInterval(node.outstandingIntervals.pop())
+                }
+                this.status({});
+            })
+        } catch(err) {
+            // eg SyntaxError - which v8 doesn't include line number information
+            // so we can't do better than this
+            this.error(err);
+        }
+    }
+    RED.nodes.registerType("jquerify",FunctionNode);
+    RED.library.register("functions");
+}
+

file:b/package.json (new)
--- /dev/null
+++ b/package.json
@@ -1,1 +1,34 @@
+{
+    "name": "node-red-contrib-jquerify",
+    "version": "0.0.5",
+    "description": "A Node-RED node that uses jQuery in a JavaScript function block to run against the messages being received by the node",
+    "repository": {
+        "type": "git",
+        "url": "https://github.com/razvanstanga/node-red-contrib-jquerify.git"
+    },
+    "dependencies": {
+        "jquery": "^3.3.1",
+        "jsdom": "^11.6.2",
+        "xmlhttprequest": "^1.8.0"
+    },
+    "inputs": 0,
+    "keywords": [
+        "node-red",
+        "node-red-contrib",
+        "jquery"
+    ],
+    "node-red": {
+        "nodes": {
+            "jquerify": "jquerify/jquerify.js"
+        }
+    },
+    "author": {
+        "name": "Razvan Stanga"
+    },
+    "license": "Apache",
+    "bugs": {
+        "url": "https://github.com/razvanstanga/node-red-contrib-jquerify/issues"
+    },
+    "homepage": "https://github.com/razvanstanga/node-red-contrib-jquerify"
+}
 

comments