Merge pull request #4964 from node-red/4962-import-warning-tidy

Validate json dropped into editor to avoid unhelpful error messages
pull/4949/head^2
Nick O'Leary 2024-12-05 16:31:33 +00:00 committed by GitHub
commit dae4ba8044
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 29 additions and 18 deletions

View File

@ -334,6 +334,30 @@ RED.clipboard = (function() {
},100);
}
/**
* Validates if the provided string looks like valid flow json
* @param {string} flowString the string to validate
* @returns If valid, returns the node array
*/
function validateFlowString(flowString) {
const res = JSON.parse(flowString)
if (!Array.isArray(res)) {
throw new Error(RED._("clipboard.import.errors.notArray"));
}
for (let i = 0; i < res.length; i++) {
if (typeof res[i] !== "object") {
throw new Error(RED._("clipboard.import.errors.itemNotObject",{index:i}));
}
if (!Object.hasOwn(res[i], 'id')) {
throw new Error(RED._("clipboard.import.errors.missingId",{index:i}));
}
if (!Object.hasOwn(res[i], 'type')) {
throw new Error(RED._("clipboard.import.errors.missingType",{index:i}));
}
}
return res
}
var validateImportTimeout;
function validateImport() {
if (activeTab === "red-ui-clipboard-dialog-import-tab-clipboard") {
@ -351,21 +375,7 @@ RED.clipboard = (function() {
return;
}
try {
if (!/^\[[\s\S]*\]$/m.test(v)) {
throw new Error(RED._("clipboard.import.errors.notArray"));
}
var res = JSON.parse(v);
for (var i=0;i<res.length;i++) {
if (typeof res[i] !== "object") {
throw new Error(RED._("clipboard.import.errors.itemNotObject",{index:i}));
}
if (!res[i].hasOwnProperty('id')) {
throw new Error(RED._("clipboard.import.errors.missingId",{index:i}));
}
if (!res[i].hasOwnProperty('type')) {
throw new Error(RED._("clipboard.import.errors.missingType",{index:i}));
}
}
validateFlowString(v)
currentPopoverError = null;
popover.close(true);
importInput.removeClass("input-error");
@ -998,16 +1008,16 @@ RED.clipboard = (function() {
}
function importNodes(nodesStr,addFlow) {
var newNodes = nodesStr;
let newNodes = nodesStr;
if (typeof nodesStr === 'string') {
try {
nodesStr = nodesStr.trim();
if (nodesStr.length === 0) {
return;
}
newNodes = JSON.parse(nodesStr);
newNodes = validateFlowString(nodesStr)
} catch(err) {
var e = new Error(RED._("clipboard.invalidFlow",{message:err.message}));
const e = new Error(RED._("clipboard.invalidFlow",{message:err.message}));
e.code = "NODE_RED";
throw e;
}
@ -1342,6 +1352,7 @@ RED.clipboard = (function() {
}
}
} catch(err) {
console.warn('Import failed: ', err)
// Ensure any errors throw above doesn't stop the drop target from
// being hidden.
}