1
0
mirror of https://github.com/node-red/node-red.git synced 2023-10-10 13:36:53 +02:00

update initialize & finalize processing of function node

This commit is contained in:
Hiroyasu Nishiyama 2020-04-06 16:34:41 +09:00
parent 84d2b8ad6d
commit 161f6090c1
4 changed files with 248 additions and 157 deletions

View File

@ -50,18 +50,6 @@ RED.library = (function() {
'</form>'+
'</div>'
function toSingleLine(text) {
var result = text.replace(/\\/g, "\\\\").replace(/\n/g, "\\n");
return result;
}
function fromSingleLine(text) {
var result = text.replace(/\\[\\n]/g, function(s) {
return ((s === "\\\\") ? "\\" : "\n");
});
return result;
}
function saveToLibrary() {
var elementPrefix = activeLibrary.elementPrefix || "node-input-";
var name = $("#"+elementPrefix+"name").val().trim();
@ -80,10 +68,8 @@ RED.library = (function() {
var field = activeLibrary.fields[i];
if (field == "name") {
data.name = name;
} else if(field == "initialize") {
data.initialize = toSingleLine(activeLibrary.initEditor.getValue());
} else if(field == "finalize") {
data.finalize = toSingleLine(activeLibrary.finalizeEditor.getValue());
} else if (typeof(field) === 'object') {
data[field.name] = field.get();
} else {
data[field] = $("#"+elementPrefix+field).val();
}
@ -539,13 +525,9 @@ RED.library = (function() {
var elementPrefix = activeLibrary.elementPrefix || "node-input-";
for (var i=0; i<activeLibrary.fields.length; i++) {
var field = activeLibrary.fields[i];
if (field === "initialize") {
var text = fromSingleLine(selectedLibraryItem.initialize);
activeLibrary.initEditor.setValue(text, -1);
}
else if (field === "finalize") {
var text = fromSingleLine(selectedLibraryItem.finalize);
activeLibrary.finalizeEditor.setValue(text, -1);
if (typeof(field) === 'object') {
var val = selectedLibraryItem[field.name];
field.set(val);
}
else {
$("#"+elementPrefix+field).val(selectedLibraryItem[field]);

View File

@ -22,7 +22,7 @@
</div>
</div>
<div id="func-tab-code" style="display:none">
<div id="func-tab-body" style="display:none">
<div class="form-row" style="margin-bottom: 0px;">
<input type="hidden" id="node-input-func" autofocus="autofocus">
<input type="hidden" id="node-input-noerr">
@ -90,14 +90,14 @@
label: that._("function.label.initialize")
});
tabs.addTab({
id: "func-tab-code",
id: "func-tab-body",
label: that._("function.label.function")
});
tabs.addTab({
id: "func-tab-finalize",
label: that._("function.label.finalize")
});
tabs.activateTab("func-tab-code");
tabs.activateTab("func-tab-body");
$( "#node-input-outputs" ).spinner({
min:0,
@ -109,74 +109,66 @@
}
});
var 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
};
this.editor = RED.editor.createEditor({
id: 'node-input-func-editor',
mode: 'ace/mode/nrjavascript',
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
}
globals: globals
});
this.initEditor = RED.editor.createEditor({
id: 'node-input-init-editor',
mode: 'ace/mode/nrjavascript',
value: $("#node-input-initialize").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
}
globals: globals
});
this.finalizeEditor = RED.editor.createEditor({
id: 'node-input-finalize-editor',
mode: 'ace/mode/nrjavascript',
value: $("#node-input-finalize").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
}
globals: globals
});
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
initEditor: this.initEditor, // editor for initializer
finalizeEditor: this.finalizeEditor, // editor for finalizer
mode:"ace/mode/nrjavascript",
fields:['name','outputs', 'initialize', 'finalize'],
fields:[
'name', 'outputs',
{
name: 'initialize',
get: function() {
return that.initEditor.getValue();
},
set: function(v) {
that.initEditor.setValue(v, -1);
}
},
{
name: 'finalize',
get: function() {
return that.finalizeEditor.getValue();
},
set: function(v) {
that.finalizeEditor.setValue(v, -1);
}
}
],
ext:"js"
});
this.editor.focus();

View File

@ -57,19 +57,99 @@ module.exports = function(RED) {
}
}
function createVMOpt(node, kind) {
var opt = {
filename: 'Function node'+kind+':'+node.id+(node.name?' ['+node.name+']':''), // filename for stack traces
displayErrors: true
// Using the following options causes node 4/6 to not include the line number
// in the stack output. So don't use them.
// lineOffset: -11, // line number offset to be used for stack traces
// columnOffset: 0, // column number offset to be used for stack traces
};
return opt;
}
function updateErrorInfo(err) {
if (err.stack) {
var stack = err.stack.toString();
var m = /^([^:]+):([^:]+):(\d+).*/.exec(stack);
if (m) {
var line = parseInt(m[3]) -1;
var kind = "body:";
if (/setup/.exec(m[1])) {
kind = "setup:";
}
if (/cleanup/.exec(m[1])) {
kind = "cleanup:";
}
err.message += " ("+kind+"line "+line+")";
}
}
}
function processAsyncResult(result, callbacks) {
var promises = callbacks;
if (Array.isArray(result)) {
promises = promises.concat(result);
}
else if(result) {
promises = promises.concat([result]);
}
return Promise.all(promises);
}
function FunctionNode(n) {
RED.nodes.createNode(this,n);
var node = this;
this.name = n.name;
this.func = n.func;
this.ini = n.initialize;
this.fin = n.finalize;
node.name = n.name;
node.func = n.func;
node.ini = n.initialize;
node.fin = n.finalize;
var handleNodeDoneCall = true;
var callbackPromises = [];
function createAsyncCallback() {
var result = undefined;
var callbacks = undefined;
var promise = new Promise((resolve, reject) => {
if (result) {
if (result.error) {
reject(result.error);
}
else {
resolve(result.value);
}
}
else {
callbacks = {
resolve: resolve,
reject: reject
};
}
});
var cb = function(err, val) {
if (callbacks) {
if (err) {
callbacks.reject(err);
}
else {
callbacks.resolve(val);
}
}
else {
result = { error: err, value: val };
}
};
callbackPromises.push(promise);
return cb;
}
// Check to see if the Function appears to call `node.done()`. If so,
// we will assume it is well written and does actually call node.done().
// Otherwise, we will call node.done() after the function returns regardless.
if (/node\.done\s*\(\s*\)/.test(this.func)) {
if (/node\.done\s*\(\s*\)/.test(node.func)) {
handleNodeDoneCall = false;
}
@ -89,13 +169,15 @@ module.exports = function(RED) {
"send:function(msgs,cloneMsg){ __node__.send(__send__,__msgid__,msgs,cloneMsg);},"+
"done:__done__"+
"};\n"+
this.func+"\n"+
node.func+"\n"+
"})(msg,send,done);";
var iniText = "(function () {\n"+this.ini +"\n})();";
var finText = "(function () {\n"+this.fin +"\n})();";
this.topic = n.topic;
this.outstandingTimers = [];
this.outstandingIntervals = [];
var iniText = "(function () {\n"+node.ini +"\n})();";
var finText = "(function () {\n"+node.fin +"\n})();";
var finScript = null;
var finOpt = null;
node.topic = n.topic;
node.outstandingTimers = [];
node.outstandingIntervals = [];
var sandbox = {
console:console,
util:util,
@ -186,12 +268,12 @@ module.exports = function(RED) {
arguments[0] = function() {
sandbox.clearTimeout(timerId);
try {
func.apply(this,arguments);
func.apply(node,arguments);
} catch(err) {
node.error(err,{});
}
};
timerId = setTimeout.apply(this,arguments);
timerId = setTimeout.apply(node,arguments);
node.outstandingTimers.push(timerId);
return timerId;
},
@ -207,12 +289,12 @@ module.exports = function(RED) {
var timerId;
arguments[0] = function() {
try {
func.apply(this,arguments);
func.apply(node,arguments);
} catch(err) {
node.error(err,{});
}
};
timerId = setInterval.apply(this,arguments);
timerId = setInterval.apply(node,arguments);
node.outstandingIntervals.push(timerId);
return timerId;
},
@ -222,7 +304,9 @@ module.exports = function(RED) {
if (index > -1) {
node.outstandingIntervals.splice(index,1);
}
}
},
promisify: (util.hasOwnProperty("promisify") ? util.promisify : undefined),
asyncCallback: createAsyncCallback
};
if (util.hasOwnProperty('promisify')) {
sandbox.setTimeout[util.promisify.custom] = function(after, value) {
@ -233,88 +317,110 @@ module.exports = function(RED) {
}
var context = vm.createContext(sandbox);
try {
vm.runInContext(iniText, context);
this.script = vm.createScript(functionText, {
filename: 'Function node:'+this.id+(this.name?' ['+this.name+']':''), // filename for stack traces
displayErrors: true
// Using the following options causes node 4/6 to not include the line number
// in the stack output. So don't use them.
// lineOffset: -11, // line number offset to be used for stack traces
// columnOffset: 0, // column number offset to be used for stack traces
});
this.on("input", function(msg,send,done) {
try {
var start = process.hrtime();
context.msg = msg;
context.send = send;
context.done = done;
var iniScript = null;
var iniOpt = null;
if (iniText || (iniText === "")) {
iniOpt = createVMOpt(node, " setup");
iniScript = new vm.Script(iniText, iniOpt);
}
node.script = vm.createScript(functionText, createVMOpt(node, ""));
if (finText || (finText === "")) {
finOpt = createVMOpt(node, "cleanup");
finScript = new vm.Script(finText, finOpt);
}
var promise = Promise.resolve();
if (iniScript) {
var result = vm.runInContext(iniText, context, iniOpt);
if (result || callbackPromises) {
promise = processAsyncResult(result, callbackPromises);
}
}
promise.then(function (v) {
node.on("input", function(msg,send,done) {
try {
var start = process.hrtime();
context.msg = msg;
context.send = send;
context.done = done;
this.script.runInContext(context);
sendResults(this,send,msg._msgid,context.results,false);
if (handleNodeDoneCall) {
done();
}
node.script.runInContext(context);
sendResults(node,send,msg._msgid,context.results,false);
if (handleNodeDoneCall) {
done();
}
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) {
if ((typeof err === "object") && err.hasOwnProperty("stack")) {
//remove unwanted part
var index = err.stack.search(/\n\s*at ContextifyScript.Script.runInContext/);
err.stack = err.stack.slice(0, index).split('\n').slice(0,-1).join('\n');
var stack = err.stack.split(/\r?\n/);
var duration = process.hrtime(start);
var converted = Math.floor((duration[0] * 1e9 + duration[1])/10000)/100;
node.metric("duration", msg, converted);
if (process.env.NODE_RED_FUNCTION_TIME) {
node.status({fill:"yellow",shape:"dot",text:""+converted});
}
} catch(err) {
if ((typeof err === "object") && err.hasOwnProperty("stack")) {
//remove unwanted part
var index = err.stack.search(/\n\s*at ContextifyScript.Script.runInContext/);
err.stack = err.stack.slice(0, index).split('\n').slice(0,-1).join('\n');
var stack = err.stack.split(/\r?\n/);
//store the error in msg to be used in flows
msg.error = err;
//store the error in msg to be used in flows
msg.error = err;
var line = 0;
var errorMessage;
if (stack.length > 0) {
while (line < stack.length && stack[line].indexOf("ReferenceError") !== 0) {
line++;
}
var line = 0;
var errorMessage;
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 (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();
}
done(errorMessage);
}
if (!errorMessage) {
errorMessage = err.toString();
else if (typeof err === "string") {
done(err);
}
else {
done(JSON.stringify(err));
}
done(errorMessage);
}
else if (typeof err === "string") {
done(err);
});
node.on("close", function() {
if (finScript) {
try {
finScript.runInContext(context, finOpt);
}
catch (err) {
node.error(err);
}
}
else {
done(JSON.stringify(err));
while (node.outstandingTimers.length > 0) {
clearTimeout(node.outstandingTimers.pop());
}
}
while (node.outstandingIntervals.length > 0) {
clearInterval(node.outstandingIntervals.pop());
}
node.status({});
});
}).catch((error) => {
node.error(error);
});
this.on("close", function() {
vm.runInContext(finText, context);
while (node.outstandingTimers.length > 0) {
clearTimeout(node.outstandingTimers.pop());
}
while (node.outstandingIntervals.length > 0) {
clearInterval(node.outstandingIntervals.pop());
}
this.status({});
});
} catch(err) {
}
catch(err) {
// eg SyntaxError - which v8 doesn't include line number information
// so we can't do better than this
this.error(err);
updateErrorInfo(err);
node.error(err);
}
}
RED.nodes.registerType("function",FunctionNode);

View File

@ -25,6 +25,17 @@ var settings;
var libDir;
var libFlowsDir;
function toSingleLine(text) {
var result = text.replace(/\\/g, "\\\\").replace(/\n/g, "\\n");
return result;
}
function fromSingleLine(text) {
var result = text.replace(/\\[\\n]/g, function(s) {
return ((s === "\\\\") ? "\\" : "\n");
});
return result;
}
function getFileMeta(root,path) {
var fn = fspath.join(root,path);
@ -43,7 +54,7 @@ function getFileMeta(root,path) {
for (var i=0;i<parts.length;i+=1) {
var match = /^\/\/ (\w+): (.*)/.exec(parts[i]);
if (match) {
meta[match[1]] = match[2];
meta[match[1]] = fromSingleLine(match[2]);
} else {
read = size;
break;
@ -172,7 +183,7 @@ module.exports = {
var headers = "";
for (var i in meta) {
if (meta.hasOwnProperty(i)) {
headers += "// "+i+": "+meta[i]+"\n";
headers += "// "+i+": "+toSingleLine(meta[i])+"\n";
}
}
if (type === "flows" && settings.flowFilePretty) {