This commit is contained in:
gongwenxin
2025-08-28 16:20:24 +08:00
parent 61e533cddf
commit 73e887ebf4
1539 changed files with 360926 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
src
docs
+178
View File
@@ -0,0 +1,178 @@
Copyright OpenJS Foundation and other contributors, https://openjsf.org/
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
+10
View File
@@ -0,0 +1,10 @@
@node-red/util
====================
Node-RED utilities module.
This provides common utilities shared by the Node-RED components.
### Source
The main Node-RED modules are maintained as a monorepo on [GitHub](https://github.com/node-red/node-red).
+81
View File
@@ -0,0 +1,81 @@
/*!
* 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.
**/
const log = require("./lib/log");
const i18n = require("./lib/i18n");
const util = require("./lib/util");
const events = require("./lib/events");
const exec = require("./lib/exec");
const hooks = require("./lib/hooks");
/**
* This module provides common utilities for the Node-RED runtime and editor
*
* @namespace @node-red/util
*/
module.exports = {
/**
* Initialise the module with the runtime settings
* @param {Object} settings
* @memberof @node-red/util
*/
init: function(settings) {
log.init(settings);
i18n.init(settings);
},
/**
* Logging utilities
* @mixes @node-red/util_log
* @memberof @node-red/util
*/
log: log,
/**
* Internationalization utilities
* @mixes @node-red/util_i18n
* @memberof @node-red/util
*/
i18n: i18n,
/**
* General utilities
* @mixes @node-red/util_util
* @memberof @node-red/util
*/
util: util,
/**
* Runtime events
* @mixes @node-red/util_event
* @memberof @node-red/util
*/
events: events,
/**
* Run system commands with event-log integration
* @mixes @node-red/util_exec
* @memberof @node-red/util
*/
exec: exec,
/**
* Runtime hooks
* @mixes @node-red/util_hooks
* @memberof @node-red/util
*/
hooks: hooks
}
+79
View File
@@ -0,0 +1,79 @@
/*!
* 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.
**/
/**
* Runtime events
* @mixin @node-red/util_events
*/
const events = new (require("events")).EventEmitter();
const deprecatedEvents = {
"nodes-stopped": "flows:stopped",
"nodes-started": "flows:started"
}
function wrapEventFunction(obj,func) {
events["_"+func] = events[func];
return function(eventName, listener) {
if (deprecatedEvents.hasOwnProperty(eventName)) {
const log = require("@node-red/util").log;
const stack = (new Error().stack).split("\n");
let location = "(unknown)"
// See https://github.com/node-red/node-red/issues/3292
if (stack.length > 2) {
location = stack[2].split("(")[1].slice(0,-1);
}
log.warn(`[RED.events] Deprecated use of "${eventName}" event from "${location}". Use "${deprecatedEvents[eventName]}" instead.`)
}
return events["_"+func].call(events,eventName,listener)
}
}
events.on = wrapEventFunction(events,"on");
events.once = wrapEventFunction(events,"once");
events.addListener = events.on;
module.exports = events;
/**
* Runtime events emitter
* @mixin @node-red/util_events
*/
/**
* Register an event listener for a runtime event
* @name on
* @function
* @memberof @node-red/util_events
* @param {String} eventName - the name of the event to listen to
* @param {Function} listener - the callback function for the event
*/
/**
* Emit an event to all of its registered listeners
* @name emit
* @function
* @memberof @node-red/util_events
* @param {String} eventName - the name of the event to emit
* @param {any} ...args - the arguments to pass in the event
* @return {Boolean} - whether the event had listeners or not
*/
+99
View File
@@ -0,0 +1,99 @@
/*!
* 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.
**/
/**
* Run system commands with event-log integration
* @mixin @node-red/util_exec
*/
const child_process = require('child_process');
const events = require("./events");
const util = require('./util');
function logLines(id,type,data) {
events.emit("event-log", {id:id,payload:{ts: Date.now(),data:data,type:type}});
}
module.exports = {
/**
* Run a system command with stdout/err being emitted as 'event-log' events
* on the @node-red/util/events handler.
*
* The main arguments to this function are the same as passed to `child_process.spawn`
*
* @param {String} command - the command to run
* @param {Array} args - arguments for the command
* @param {Object} options - options to pass child_process.spawn
* @param {Boolean} emit - whether to emit events to the event-log for each line of stdout/err
* @return {Promise} A promise that resolves (rc=0) or rejects (rc!=0) when the command completes. The value
* of the promise is an object of the form:
*
* {
* code: <exit code>,
* stdout: <standard output from the command>,
* stderr: <standard error from the command>
* }
* @memberof @node-red/util_exec
*/
run: function(command,args,options,emit) {
var invocationId = util.generateId();
emit && events.emit("event-log", {ts: Date.now(),id:invocationId,payload:{ts: Date.now(),data:command+" "+args.join(" ")}});
return new Promise((resolve, reject) => {
let stdout = "";
let stderr = "";
let child
if (args && options.shell) {
// If we are using a shell, we need to join the args into a single string
// as passing a separate array of args is deprecated in Node 24
command = [command].concat(args).join(" ");
child = child_process.spawn(command, options)
} else {
child = child_process.spawn(command, args, options);
}
child.stdout.on('data', (data) => {
const str = ""+data;
stdout += str;
emit && logLines(invocationId,"out",str);
});
child.stderr.on('data', (data) => {
const str = ""+data;
stderr += str;
emit && logLines(invocationId,"err",str);
});
child.on('error', function(err) {
stderr = err.toString();
emit && logLines(invocationId,"err",stderr);
})
child.on('close', (code) => {
let result = {
code: code,
stdout: stdout,
stderr: stderr
}
emit && events.emit("event-log", {id:invocationId,payload:{ts: Date.now(), data:"rc="+code, end: true}});
if (code === 0) {
resolve(result)
} else {
reject(result);
}
});
})
}
}
+260
View File
@@ -0,0 +1,260 @@
const Log = require("./log.js");
const VALID_HOOKS = [
// Message Routing Path
"onSend",
"preRoute",
"preDeliver",
"postDeliver",
"onReceive",
"postReceive",
"onComplete",
// Module install hooks
"preInstall",
"postInstall",
"preUninstall",
"postUninstall"
]
// Flags for what hooks have handlers registered
let states = { }
// Doubly-LinkedList of hooks by id.
// - hooks[id] points to head of list
// - each list item looks like:
// {
// cb: the callback function
// location: filename/line of code that added the hook
// previousHook: reference to previous hook in list
// nextHook: reference to next hook in list
// removed: a flag that is set if the item was removed
// }
let hooks = { }
// Hooks by label
let labelledHooks = { }
/**
* Runtime hooks engine
*
* The following hooks can be used:
*
* Message sending
* - `onSend` - passed an array of `SendEvent` objects. The messages inside these objects are exactly what the node has passed to `node.send` - meaning there could be duplicate references to the same message object.
* - `preRoute` - passed a `SendEvent`
* - `preDeliver` - passed a `SendEvent`. The local router has identified the node it is going to send to. At this point, the message has been cloned if needed.
* - `postDeliver` - passed a `SendEvent`. The message has been dispatched to be delivered asynchronously (unless the sync delivery flag is set, in which case it would be continue as synchronous delivery)
* - `onReceive` - passed a `ReceiveEvent` when a node is about to receive a message
* - `postReceive` - passed a `ReceiveEvent` when the message has been given to the node's `input` handler(s)
* - `onComplete` - passed a `CompleteEvent` when the node has completed with a message or logged an error
*
* @mixin @node-red/util_hooks
*/
/**
* Register a handler to a named hook
* @memberof @node-red/util_hooks
* @param {String} hookId - the name of the hook to attach to
* @param {Function} callback - the callback function for the hook
*/
function add(hookId, callback) {
let [id, label] = hookId.split(".");
if (VALID_HOOKS.indexOf(id) === -1) {
throw new Error(`Invalid hook '${id}'`);
}
if (label && labelledHooks[label] && labelledHooks[label][id]) {
throw new Error("Hook "+hookId+" already registered")
}
// Get location of calling code
let callModule;
const stack = new Error().stack;
const stackEntries = stack.split("\n").slice(1);//drop 1st line (error message)
const stackEntry2 = stackEntries[1];//get 2nd stack entry
if (stackEntry2) {
try {
if (stackEntry2.indexOf(" (") >= 0) {
callModule = stackEntry2.split("(")[1].slice(0, -1);
} else {
callModule = stackEntry2.split(" ").slice(-1)[0];
}
} catch (error) {
Log.debug(`Unable to determined module when adding hook '${hookId}'. Stack:\n${stackEntries.join("\n")}`);
callModule = "unknown:0:0";
}
} else {
Log.debug(`Unable to determined module when adding hook '${hookId}'. Stack:\n${stackEntries.join("\n")}`);
callModule = "unknown:0:0";
}
Log.debug(`Adding hook '${hookId}' from ${callModule}`);
const hookItem = {cb:callback, location: callModule, previousHook: null, nextHook: null }
let tailItem = hooks[id];
if (tailItem === undefined) {
hooks[id] = hookItem;
} else {
while(tailItem.nextHook !== null) {
tailItem = tailItem.nextHook
}
tailItem.nextHook = hookItem;
hookItem.previousHook = tailItem;
}
if (label) {
labelledHooks[label] = labelledHooks[label]||{};
labelledHooks[label][id] = hookItem;
}
// TODO: get rid of this;
states[id] = true;
}
/**
* Remove a handled from a named hook
* @memberof @node-red/util_hooks
* @param {String} hookId - the name of the hook event to remove - must be `name.label`
*/
function remove(hookId) {
let [id,label] = hookId.split(".");
if ( !label) {
throw new Error("Cannot remove hook without label: "+hookId)
}
Log.debug(`Removing hook '${hookId}'`);
if (labelledHooks[label]) {
if (id === "*") {
// Remove all hooks for this label
let hookList = Object.keys(labelledHooks[label]);
for (let i=0;i<hookList.length;i++) {
removeHook(hookList[i],labelledHooks[label][hookList[i]])
}
delete labelledHooks[label];
} else if (labelledHooks[label][id]) {
removeHook(id,labelledHooks[label][id])
delete labelledHooks[label][id];
if (Object.keys(labelledHooks[label]).length === 0){
delete labelledHooks[label];
}
}
}
}
function removeHook(id,hookItem) {
let previousHook = hookItem.previousHook;
let nextHook = hookItem.nextHook;
if (previousHook) {
previousHook.nextHook = nextHook;
} else {
hooks[id] = nextHook;
}
if (nextHook) {
nextHook.previousHook = previousHook;
}
hookItem.removed = true;
if (!previousHook && !nextHook) {
delete hooks[id];
delete states[id];
}
}
function trigger(hookId, payload, done) {
let hookItem = hooks[hookId];
if (!hookItem) {
if (done) {
done();
return;
} else {
return Promise.resolve();
}
}
if (!done) {
return new Promise((resolve,reject) => {
invokeStack(hookItem,payload,function(err) {
if (err !== undefined && err !== false) {
if (!(err instanceof Error)) {
err = new Error(err);
}
err.hook = hookId
reject(err);
} else {
resolve(err);
}
})
});
} else {
invokeStack(hookItem,payload,done)
}
}
function invokeStack(hookItem,payload,done) {
function callNextHook(err) {
if (!hookItem || err) {
done(err);
return;
}
if (hookItem.removed) {
hookItem = hookItem.nextHook;
callNextHook();
return;
}
const callback = hookItem.cb;
if (callback.length === 1) {
try {
let result = callback(payload);
if (result === false) {
// Halting the flow
done(false);
return
}
if (result && typeof result.then === 'function') {
result.then(handleResolve, callNextHook)
return;
}
hookItem = hookItem.nextHook;
callNextHook();
} catch(err) {
done(err);
return;
}
} else {
try {
callback(payload,handleResolve)
} catch(err) {
done(err);
return;
}
}
}
function handleResolve(result) {
if (result === undefined) {
hookItem = hookItem.nextHook;
callNextHook();
} else {
done(result);
}
}
callNextHook();
}
function clear() {
hooks = {}
labelledHooks = {}
states = {}
}
function has(hookId) {
let [id, label] = hookId.split(".");
if (label) {
return !!(labelledHooks[label] && labelledHooks[label][id])
}
return !!states[id]
}
module.exports = {
has,
clear,
add,
remove,
trigger
}
+255
View File
@@ -0,0 +1,255 @@
/**
* 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.
* @ignore
**/
/**
* Internationalization utilities
* @mixin @node-red/util_i18n
*/
var i18n = require("i18next");
var path = require("path");
var fs = require("fs");
var defaultLang = "en-US";
var resourceMap = {};
var resourceCache = {};
var initPromise;
/**
* Register multiple message catalogs with i18n.
* @memberof @node-red/util_i18n
*/
function registerMessageCatalogs(catalogs) {
var promises = catalogs.map(function(catalog) {
return registerMessageCatalog(catalog.namespace,catalog.dir,catalog.file).catch(err => {});
});
return Promise.all(promises);
}
/**
* Register a message catalog with i18n.
* @memberof @node-red/util_i18n
*/
async function registerMessageCatalog(namespace,dir,file) {
return initPromise.then(function() {
return new Promise((resolve,reject) => {
resourceMap[namespace] = { basedir:dir, file:file, lngs: []};
fs.readdir(dir,function(err, files) {
if (err) {
resolve();
} else {
files.forEach(function(f) {
if (fs.existsSync(path.join(dir,f,file))) {
resourceMap[namespace].lngs.push(f);
}
});
i18n.loadNamespaces(namespace,function() {
resolve();
});
}
})
});
});
}
function mergeCatalog(fallback,catalog) {
for (var k in fallback) {
if (fallback.hasOwnProperty(k)) {
if (!catalog[k]) {
catalog[k] = fallback[k];
} else if (typeof fallback[k] === 'object') {
mergeCatalog(fallback[k],catalog[k]);
}
}
}
}
function migrateMessageCatalogV3toV4(catalog) {
const keys = Object.keys(catalog)
keys.forEach(key => {
if (typeof catalog[key] === 'object') {
catalog[key] = migrateMessageCatalogV3toV4(catalog[key])
} else if (key.endsWith('_plural')) {
const otherKey = key.replace('_plural', '_other')
if (!catalog[otherKey]) {
catalog[otherKey] = catalog[key]
}
delete catalog[key]
}
})
return catalog
}
async function readFile(lng, ns) {
if (/[^a-z\-]/i.test(lng)) {
throw new Error("Invalid language: "+lng)
}
if (resourceCache[ns] && resourceCache[ns][lng]) {
return resourceCache[ns][lng];
} else if (resourceMap[ns]) {
const file = path.join(resourceMap[ns].basedir, lng, resourceMap[ns].file);
const content = await fs.promises.readFile(file, "utf8");
resourceCache[ns] = resourceCache[ns] || {};
resourceCache[ns][lng] = JSON.parse(content.replace(/^\uFEFF/, ''));
// Message catalogues are in i18next v3 format. That is no longer supported
// by i18next so we need to migrate any catalog to the v4 format.
// This primarily means mapping `FOO_plural` to `FOO_other`
resourceCache[ns][lng] = migrateMessageCatalogV3toV4(resourceCache[ns][lng])
var baseLng = lng.split('-')[0];
if (baseLng !== lng && resourceCache[ns][baseLng]) {
mergeCatalog(resourceCache[ns][baseLng], resourceCache[ns][lng]);
}
if (lng !== defaultLang) {
mergeCatalog(resourceCache[ns][defaultLang], resourceCache[ns][lng]);
}
return resourceCache[ns][lng];
} else {
throw new Error("Unrecognised namespace");
}
}
var MessageFileLoader = {
type: "backend",
init: function (services, backendOptions, i18nextOptions) { },
read: function (lng, ns, callback) {
readFile(lng, ns)
.then(data => callback(null, data))
.catch(err => {
if (/-/.test(lng)) {
// if reading language file fails -> try reading base language (e. g. 'fr' instead of 'fr-FR' or 'de' for 'de-DE')
var baseLng = lng.split('-')[0];
readFile(baseLng, ns).then(baseData => callback(null, baseData)).catch(err => callback(err));
} else {
callback(err);
}
});
}
}
function getCurrentLocale() {
var env = process.env;
for (var name of ['LC_ALL', 'LC_MESSAGES', 'LANG']) {
if (name in env) {
var val = env[name];
return val.substring(0, 2);
}
}
return undefined;
}
function init(settings) {
if (!initPromise) {
initPromise = new Promise((resolve,reject) => {
i18n.use(MessageFileLoader);
var opt = {
// debug: true,
defaultNS: "runtime",
ns: [],
fallbackLng: defaultLang,
keySeparator: ".",
nsSeparator: ":",
interpolation: {
unescapeSuffix: 'HTML',
escapeValue: false,
prefix: '__',
suffix: '__'
}
};
var lang = settings.lang || getCurrentLocale();
if (lang) {
opt.lng = lang;
}
i18n.init(opt ,function() {
resolve();
});
});
}
}
/**
* Gets a message catalog.
* @name catalog
* @function
* @memberof @node-red/util_i18n
*/
function getCatalog(namespace,lang) {
var result = null;
lang = lang || defaultLang;
if (/[^a-z\-]/i.test(lang)) {
throw new Error("Invalid language: "+lng)
}
if (resourceCache.hasOwnProperty(namespace)) {
result = resourceCache[namespace][lang];
if (!result) {
var langParts = lang.split("-");
if (langParts.length == 2) {
result = resourceCache[namespace][langParts[0]];
}
}
}
return result;
}
/**
* Gets a list of languages a given catalog is available in.
* @name availableLanguages
* @function
* @memberof @node-red/util_i18n
*/
function availableLanguages(namespace) {
if (resourceMap.hasOwnProperty(namespace)) {
return resourceMap[namespace].lngs
}
}
var obj = module.exports = {
init: init,
registerMessageCatalog: registerMessageCatalog,
registerMessageCatalogs: registerMessageCatalogs,
catalog: getCatalog,
availableLanguages: availableLanguages,
/**
* The underlying i18n library for when direct access is really needed
*/
i: i18n,
/**
* The default language of the runtime
*/
defaultLang: defaultLang
}
/**
* Perform a message catalog lookup.
* @name _
* @function
* @memberof @node-red/util_i18n
*/
obj['_'] = function() {
//var opts = {};
//if (def) {
// opts.defaultValue = def;
//}
//console.log(arguments);
var res = i18n.t.apply(i18n,arguments);
return res;
}
+265
View File
@@ -0,0 +1,265 @@
/*!
* 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.
**/
/**
* Logging utilities
* @mixin @node-red/util_log
*/
var util = require("util");
var EventEmitter = require("events").EventEmitter;
var i18n = require("./i18n");
const chalk = require("chalk");
var levels = {
off: 1,
fatal: 10,
error: 20,
warn: 30,
info: 40,
debug: 50,
trace: 60,
audit: 98,
metric: 99
};
var levelNames = {
10: "fatal",
20: "error",
30: "warn",
40: "info",
50: "debug",
60: "trace",
98: "audit",
99: "metric"
};
var levelColours = {
10: 'red',
20: 'red',
30: 'yellow',
40: '',
50: 'cyan',
60: 'gray',
98: '',
99: ''
};
var logHandlers = [];
var verbose;
var metricsEnabled = false;
var LogHandler = function(settings) {
this.logLevel = settings ? levels[settings.level]||levels.info : levels.info;
this.metricsOn = settings ? settings.metrics||false : false;
this.auditOn = settings ? settings.audit||false : false;
metricsEnabled = metricsEnabled || this.metricsOn;
this.handler = (settings && settings.handler) ? settings.handler(settings) : consoleLogger;
this.on("log",function(msg) {
if (this.shouldReportMessage(msg.level)) {
this.handler(msg);
}
});
}
util.inherits(LogHandler, EventEmitter);
LogHandler.prototype.shouldReportMessage = function(msglevel) {
return (msglevel == log.METRIC && this.metricsOn) ||
(msglevel == log.AUDIT && this.auditOn) ||
msglevel <= this.logLevel;
}
// Older versions of Node-RED used the deprecated util.log function.
// With Node.js 22, use of that function causes warnings. So here we
// are replicating the same format output to ensure we don't break any
// log parsing that happens in the real world.
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const utilLog = function (msg, level) {
const d = new Date();
const time = [
d.getHours().toString().padStart(2, '0'),
d.getMinutes().toString().padStart(2, '0'),
d.getSeconds().toString().padStart(2, '0')
].join(':');
const logLine = `${d.getDate()} ${months[d.getMonth()]} ${time} - ${msg}`
if (levelColours[level]) {
console.log(chalk[levelColours[level]](logLine))
} else {
console.log(logLine)
}
}
var consoleLogger = function(msg) {
if (msg.level == log.METRIC || msg.level == log.AUDIT) {
utilLog("["+levelNames[msg.level]+"] "+JSON.stringify(msg), msg.level);
} else {
if (verbose && msg.msg && msg.msg.stack) {
utilLog("["+levelNames[msg.level]+"] "+(msg.type?"["+msg.type+":"+(msg.name||msg.id)+"] ":"")+msg.msg.stack, msg.level);
} else {
var message = msg.msg;
try {
if (typeof message === 'object' && message !== null && message.toString() === '[object Object]' && message.message) {
message = message.message;
}
} catch(e){
message = 'Exception trying to log: '+util.inspect(message);
}
utilLog("["+levelNames[msg.level]+"] "+(msg.type?"["+msg.type+":"+(msg.name||msg.id)+"] ":"")+message, msg.level);
}
}
}
var log = module.exports = {
FATAL: 10,
ERROR: 20,
WARN: 30,
INFO: 40,
DEBUG: 50,
TRACE: 60,
AUDIT: 98,
METRIC: 99,
init: function(settings) {
metricsEnabled = false;
logHandlers = [];
var loggerSettings = {};
verbose = settings.verbose;
if (settings.logging) {
var keys = Object.keys(settings.logging);
if (keys.length === 0) {
log.addHandler(new LogHandler());
} else {
for (var i=0, l=keys.length; i<l; i++) {
var config = settings.logging[keys[i]];
loggerSettings = config || {};
if ((keys[i] === "console") || config.handler) {
log.addHandler(new LogHandler(loggerSettings));
}
}
}
} else {
log.addHandler(new LogHandler());
}
},
/**
* Add a log handler function
* @memberof @node-red/util_log
*/
addHandler: function(func) {
logHandlers.push(func);
},
/**
* Remove a log handler function
* @memberof @node-red/util_log
*/
removeHandler: function(func) {
var index = logHandlers.indexOf(func);
if (index > -1) {
logHandlers.splice(index,1);
}
},
/**
* Log a message object
* @memberof @node-red/util_log
*/
log: function(msg) {
msg.timestamp = Date.now();
logHandlers.forEach(function(handler) {
handler.emit("log",msg);
});
},
/**
* Log a message at INFO level
* @memberof @node-red/util_log
*/
info: function(msg) {
log.log({level:log.INFO,msg:msg});
},
/**
* Log a message at WARN level
* @memberof @node-red/util_log
*/
warn: function(msg) {
log.log({level:log.WARN,msg:msg});
},
/**
* Log a message at ERROR level
* @memberof @node-red/util_log
*/
error: function(msg) {
log.log({level:log.ERROR,msg:msg});
},
/**
* Log a message at TRACE level
* @memberof @node-red/util_log
*/
trace: function(msg) {
log.log({level:log.TRACE,msg:msg});
},
/**
* Log a message at DEBUG level
* @memberof @node-red/util_log
*/
debug: function(msg) {
log.log({level:log.DEBUG,msg:msg});
},
/**
* Check if metrics are enabled
* @memberof @node-red/util_log
*/
metric: function() {
return metricsEnabled;
},
/**
* Log an audit event.
* @memberof @node-red/util_log
*/
audit: function(msg,req) {
msg.level = log.AUDIT;
if (req) {
msg.user = req.user;
msg.path = req.path;
msg.ip = req.ip || (req.headers && req.headers['x-forwarded-for']) || (req.connection && req.connection.remoteAddress) || undefined;
}
log.log(msg);
}
}
/**
* Perform a message catalog lookup.
* @name _
* @function
* @memberof @node-red/util_log
*/
log["_"] = i18n._;
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
{
"name": "@node-red/util",
"version": "4.1.0",
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "https://github.com/node-red/node-red.git"
},
"contributors": [
{
"name": "Nick O'Leary"
},
{
"name": "Dave Conway-Jones"
}
],
"dependencies": {
"chalk": "^4.1.2",
"fs-extra": "11.3.0",
"i18next": "24.2.3",
"json-stringify-safe": "5.0.1",
"jsonata": "2.0.6",
"lodash.clonedeep": "^4.5.0",
"moment": "2.30.1",
"moment-timezone": "0.5.48"
}
}