UNPKG

@mindconnect/mindconnect-nodejs

Version:

NodeJS Library for Siemens Insights Hub Connectivity - TypeScript SDK for Insights Hub and Industrial IoT - Command Line Interface - Insights Hub Development Proxy (Siemens Insights Hub was formerly known as MindSphere)

313 lines 15.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.humanReadableDate = exports.isPrimitive = exports.printObjectInfo = exports.buildFilter = exports.generateTestData = exports.humanFileSize = exports.retrylog = exports.homeDirLog = exports.proxyLog = exports.verboseLog = exports.errorLog = exports.agentConfigLog = exports.getSdk = exports.adjustColor = exports.getColor = exports.modeInformation = exports.directoryReadyLog = exports.displayCsvHelp = exports.subtractSecond = exports.colorizeStatus = exports.serviceCredentialLog = exports.checkForUpdates = void 0; const chalk = require("chalk"); const console_1 = require("console"); const date_fns_1 = require("date-fns"); const frontend_auth_1 = require("../../api/frontend-auth"); const sdk_1 = require("../../api/sdk"); const utils_1 = require("../../api/utils"); const version_1 = require("../../version"); const updateNotifier = require("update-notifier-cjs"); const magenta = getColor("magenta"); const yellow = getColor("yellow"); const green = getColor("green"); const red = getColor("red"); const cyan = getColor("cyan"); function checkForUpdates() { const pkgInfo = { pkg: { name: `@mindconnect/${version_1.MC_NAME}`, version: `${version_1.MC_VERSION}`, }, }; const notifier = updateNotifier(pkgInfo); if (notifier.update) { console.log(`\n\t There is an update available: ${magenta(notifier.update.latest + " ")} (${notifier.update.type})`); console.log(`\t Run ${magenta("npm install -g ")}${magenta(pkgInfo.pkg.name)} to update`); console.log(`\t or download the release for your system from`); console.log(`\t ${magenta("https://github.com/mindsphere/mindconnect-nodejs/releases")}\n`); } } exports.checkForUpdates = checkForUpdates; const serviceCredentialLog = (color = magenta) => { if (process.env.MDSP_PASSKEY || (process.env.MDSP_HOST && process.env.MDSP_SESSION && process.env.MDSP_XSRF_TOKEN)) { checkForUpdates(); return; } (0, console_1.log)(`\n Important: `); (0, console_1.log)(`\n Authentication with ${color("service credentials")} or ${color("app credentials")}:\n`); (0, console_1.log)(` \t- either append option [--passkey <your passkey>] to the command `); (0, console_1.log)(` \t- or create environment variable ${color("MDSP_PASSKEY")} with your current passkey`); (0, console_1.log)(`\n Authentication with ${yellow("borrowed session cookie and xsrf-token cookie")}: \n`); (0, console_1.log)(` \t- create environment variables ${yellow("MDSP_HOST")} , ${yellow("MDSP_SESSION")} and ${yellow("MDSP_XSRF_TOKEN")} using borrowed cookies `); (0, console_1.log)(`\n Full Documentation: \n`); (0, console_1.log)(` ${color("https://developer.siemens.com/industrial-iot-open-source/mindconnect-nodejs/cli/setting-up-the-cli.html")}\n`); checkForUpdates(); }; exports.serviceCredentialLog = serviceCredentialLog; function colorizeStatus(message) { switch (message) { case "SUCCESS": return green(message); case "IN_PROGRESS": return chalk.yellow(message); case "ERROR": return red(message); default: return message; } } exports.colorizeStatus = colorizeStatus; const subtractSecond = (date, seconds) => { const newDate = new Date(date); newDate.setUTCMilliseconds(date.getUTCMilliseconds() - Math.floor(seconds * 1000)); return newDate; }; exports.subtractSecond = subtractSecond; const displayCsvHelp = (color) => { const now = new Date(); (0, console_1.log)("\n Examples:\n"); (0, console_1.log)(` mdsp ts -f timeseries.csv \t\t\t\t\t upload timeseries from the csv file to mindsphere `); (0, console_1.log)(` mdsp upload-timeseries --file timeseries.csv --size 100 \t use http post size of 100 records `); (0, console_1.log)(`\n ${color("Data Format:")} (use your own data point ids from mindsphere)\n`); (0, console_1.log)(` timestamp, ${color("dataPointId")}, ${green("qualityCode")}, ${yellow("value")}`); (0, console_1.log)(` ${(0, exports.subtractSecond)(now, 2).toISOString()}, ${color("DP-Temperature")} ,${green("0")}, ${yellow("20.34")}`); (0, console_1.log)(` ${(0, exports.subtractSecond)(now, 1).toISOString()}, ${color("DP-Humidity")}, ${green("0")}, ${yellow("70")}`); (0, console_1.log)(` ${(0, exports.subtractSecond)(now, 0).toISOString()}, ${color("DP-Pressure")}, ${green("0")}, ${yellow("1012.3")}`); (0, console_1.log)(`\n Make sure that the timestamp is in ISO format. The headers and the casing (timestamp, dataPointId) are important.`, `\n The values must correspond with data types configured in mindsphere (in example: ${color("DP-Humidity")} must be an ${color("integer")})`); (0, console_1.log)(`\n ${color("Important:")}\n`); (0, console_1.log)(` You have to configure the data source and data mappings in mindsphere asset manager before you can upload the data`); (0, console_1.log)(` See also: ${color("https://documentation.mindsphere.io/resources/html/asset-manager/en-US/116404525451.html")}`); }; exports.displayCsvHelp = displayCsvHelp; const directoryReadyLog = ({ path, runCommand, jobCommand, }) => { (0, console_1.log)(`\nthe directory ${green(path)} is ${green("ready")}`); (0, console_1.log)(`you can now edit the template files in the directory`); (0, console_1.log)(`\nwhen you are done run:`); (0, console_1.log)(`\t mdsp ${runCommand} command to upload files and start the job`); (0, console_1.log)(`\nchecking progress:`); (0, console_1.log)(`\t mdsp ${jobCommand} to check the progress of the job`); }; exports.directoryReadyLog = directoryReadyLog; function modeInformation(asset, options, color) { const MAX_SIZE_FOR_TS = 100; console.log(`\nRunning ${options.timeseries ? `${yellow("standard")} TimeSeries ${yellow("(deprecated)")}` : `${color("bulk")} TimeSeries`} ingest for ${color(asset.name)} of type ${color("" + asset.typeId)} with twintype ${color("" + asset.twinType)}`); if (asset.twinType === sdk_1.AssetManagementModels.TwinType.Performance && options.timeseries) { if (parseInt(options.size, 10) > MAX_SIZE_FOR_TS) { options.size = MAX_SIZE_FOR_TS; } console.log(`\n${color("Important:")}`); console.log(`\nYou are using the ${color("standard timeseries")} ingest for the asset.`); console.log(`The calls to the API will be ${color("throttled")} to match your throttling limits.`); console.log(`The number of the records per message will be reduced to ${color(options.size)} per message.\n`); console.log(`Using this feature has a direct impact on ${color("your")} MindSphere resource consumption.`); console.log(`You might get a notice that you will need to upgrade your account's data ingest rate.`); console.log(`${yellow("Warning")} This feature is ${yellow("deprecated")}!\n`); } } exports.modeInformation = modeInformation; function getColor(name) { return chalk.level < 2 ? chalk[name] : chalk[`${name}Bright`]; } exports.getColor = getColor; function adjustColor(color, options, analyticcommand = false) { if ((process.env.MDSP_PASSKEY || options.passkey) && !analyticcommand) { return getColor("magenta"); } else if (process.env.MDSP_HOST && process.env.MDSP_SESSION && process.env.MDSP_XSRF_TOKEN) { return getColor("yellow"); } else { return color; } } exports.adjustColor = adjustColor; function getSdk(options) { let sdk; const magenta = getColor("magenta"); const yellow = getColor("yellow"); if (options.passkey) { (0, exports.verboseLog)(`The passkey was specified as command line option using ${magenta("service/app credentials")}`, options.verbose); const auth = (0, utils_1.loadAuth)(); options._selected_mode = "passkey"; sdk = new sdk_1.MindSphereSdk(Object.assign(Object.assign({}, auth), { basicAuth: (0, utils_1.decrypt)(auth, options.passkey) })); } else if (process.env.MDSP_PASSKEY && process.env.MDSP_PASSKEY !== "") { (0, exports.verboseLog)(`The passkey was specified in environment variable MDSP_PASSKEY using ${magenta("service/app credentials")}`, options.verbose); const auth = (0, utils_1.loadAuth)(); options.passkey = process.env.MDSP_PASSKEY; options._selected_mode = "passkey"; sdk = new sdk_1.MindSphereSdk(Object.assign(Object.assign({}, auth), { basicAuth: (0, utils_1.decrypt)(auth, options.passkey) })); } else if (process.env.MDSP_HOST && process.env.MDSP_SESSION && process.env.MDSP_XSRF_TOKEN) { (0, exports.verboseLog)(`Using borrowed ${yellow("SESSION")} and ${yellow("XSRF-TOKEN")} cookies from ${yellow(process.env.MDSP_HOST)} for authentication`, options.verbose); let host = process.env.MDSP_HOST || ""; if (!process.env.MDSP_HOST.toLowerCase().startsWith("https://")) { host = `https://${host}`; } sdk = new sdk_1.MindSphereSdk(new frontend_auth_1.FrontendAuth(host, process.env.MDSP_SESSION, process.env.MDSP_XSRF_TOKEN)); options._selected_mode = "cookie"; } else { throw new Error("The passkey was not provided and there are no environment variables"); } return sdk; } exports.getSdk = getSdk; function agentConfigLog({ gateway, host, tenant, agentid, color, }) { console.log("\nConfigure your agent at:\n"); console.log("\t" + color(`${gateway.replace(host, tenant + "-assetmanager")}/entity/${agentid}/plugin/uipluginassetmanagermclib`) + "\n"); } exports.agentConfigLog = agentConfigLog; const errorLog = (err, verbose) => { if (err.message) { console.error(`\n${red(err.message.toString())}`); if (verbose && err.stack) { console.error(red(err.stack)); } } else { console.error(red(err.toString())); } process.exit(1); }; exports.errorLog = errorLog; const verboseLog = (message, verbose, spinner) => { verbose && console.log(`... ${message}`); if (!verbose && spinner) { spinner.text = `... ${message}`; } }; exports.verboseLog = verboseLog; const proxyLog = (verbose, color) => { const proxy = process.env.HTTP_PROXY || process.env.http_proxy; const c = color; (0, exports.verboseLog)(proxy ? `Using ${c(proxy)} as proxy server` : "No proxy configured.", verbose); }; exports.proxyLog = proxyLog; const homeDirLog = (verbose, color) => { const c = color; (0, exports.verboseLog)(`Using configuration stored in ${c((0, utils_1.getHomeDotMcDir)())}`, verbose); }; exports.homeDirLog = homeDirLog; const retrylog = function (operation, c = cyan) { let x = 0; return () => { if (x > 0) { console.log(`...Retry no ${c("" + x)} for ${c(operation)} operation.`); } x++; }; }; exports.retrylog = retrylog; const humanFileSize = (size) => { const i = size === 0 ? 0 : Math.floor(Math.log(size) / Math.log(1024)); const calculatedSize = (size / Math.pow(1024, i)).toFixed(2); const suffix = ["B", "KB", "MB", "GB", "TB"][i]; return `${calculatedSize}${suffix}`; }; exports.humanFileSize = humanFileSize; function generateTestData(size, fn, variableName = "variable1", format = "string") { const startDate = new Date(); const results = []; for (let index = 0; index < size; index++) { const time = (0, exports.subtractSecond)(startDate, size - index); const value = fn(index); if (value !== undefined) { const item = { _time: time.toISOString(), }; item[variableName] = format === "string" ? value.toString() : value; results.push(item); } } return results; } exports.generateTestData = generateTestData; function buildFilter(options) { const filter = (options.filter && JSON.parse(options.filter)) || {}; let pointer = filter; if (options.assetname !== undefined && options.typeid !== undefined) { filter.and = {}; pointer = filter.and; } if (options.assetname) { pointer.name = { contains: `${options.assetname}` }; } if (options.typeid) { pointer.typeId = { contains: `${options.typeid}` }; } return filter; } exports.buildFilter = buildFilter; function printObjectInfo(title, dto, options, coloredProperties, color, depth = 0) { console.log(`${title}`); if (isPrimitive(dto)) { console.log(dto); return; } for (const [key, value] of Object.entries(dto)) { if (Array.isArray(value)) { for (let index = 0; index < value.length; index++) { const element = value[index]; if (isPrimitive(element)) { console.log(`${key}[${color(index)}]: ${element}`); } else { printObjectInfo(`${key}[${color(index)}]`, element, options, coloredProperties, color, depth + 1); } } } else if (typeof value === "object" && value !== null) { printObjectInfo(key, value, options, coloredProperties, color, depth + 1); } else { const words = key .split(/(?=[A-Z])/) .join(" ") .toLowerCase(); console.log(`${"\t".repeat(depth)}${words}: ${coloredProperties.indexOf(key) >= 0 ? color(value) : value}`); } } depth === 0 && (0, exports.verboseLog)(JSON.stringify(dto, null, 2), options.verbose); } exports.printObjectInfo = printObjectInfo; function isPrimitive(x) { return x !== Object(x); } exports.isPrimitive = isPrimitive; function humanReadableDate(comparisonDate) { const today = new Date(); const yesterday = (0, date_fns_1.subDays)(today, 1); const aWeekAgo = (0, date_fns_1.subDays)(today, 7); const twoWeeksAgo = (0, date_fns_1.subDays)(today, 14); const threeWeeksAgo = (0, date_fns_1.subDays)(today, 21); // Get the date in English locale to match English day of week keys const compare = comparisonDate; const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" }); let result = ""; if ((0, date_fns_1.isSameDay)(compare, today)) { result = rtf.format(0, "day"); } else if ((0, date_fns_1.isSameDay)(compare, yesterday)) { result = rtf.format(-1, "day"); } else if ((0, date_fns_1.isAfter)(compare, aWeekAgo)) { result = rtf.format(0, "week"); } else if ((0, date_fns_1.isAfter)(compare, twoWeeksAgo)) { result = rtf.format(-1, "week"); } else if ((0, date_fns_1.isAfter)(compare, threeWeeksAgo)) { result = rtf.format(-2, "week"); } return `${compare.toLocaleDateString()} ${result ? "(" + result + ") " : ""}`; } exports.humanReadableDate = humanReadableDate; //# sourceMappingURL=command-utils.js.map