diff --git a/.eslintrc.json b/.eslintrc.json index 66be45f..db75fc5 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -14,6 +14,7 @@ "prefer-arrow-callback": "error", "curly": ["error", "multi-or-nest", "consistent"], "consistent-return": ["error", {"treatUndefinedAsUnspecified": true}], - "no-buffer-constructor": "error" + "no-buffer-constructor": "error", + "prefer-const": ["error", {"destructuring": "all"}] } } diff --git a/lib/api-functions.js b/lib/api-functions.js index c1348be..5e5a853 100644 --- a/lib/api-functions.js +++ b/lib/api-functions.js @@ -139,8 +139,7 @@ function httpConReq( .get(options, res => { if (res.statusCode === 0) { // Workaround for some devices unexpectedly closing the connection - let req2; - req2 = http + const req2 = http .get(options, res2 => { callback(statusToError(res2.statusCode)); res2.resume(); @@ -155,7 +154,6 @@ function httpConReq( req2.abort(); }); }); - req2(); } else { callback(statusToError(res.statusCode)); } @@ -223,7 +221,8 @@ function connectionRequest(deviceId, callback) { // TR-098 data model else managementServer = device.InternetGatewayDevice.ManagementServer; - connectionRequestUrl = managementServer.ConnectionRequestURL._value; + if (managementServer.ConnectionRequestURL) + connectionRequestUrl = managementServer.ConnectionRequestURL._value; if (managementServer.UDPConnectionRequestAddress) { udpConnectionRequestAddress = managementServer.UDPConnectionRequestAddress._value; @@ -320,7 +319,7 @@ function insertTasks(tasks, callback) { return void callback(null, tasks || []); let counter = tasks.length; - for (let task of tasks) { + for (const task of tasks) { sanitizeTask(task, t => { if (t.uniqueKey) { db.tasksCollection.remove( diff --git a/lib/auth.js b/lib/auth.js index 1b8a98f..6f1c04a 100644 --- a/lib/auth.js +++ b/lib/auth.js @@ -86,7 +86,7 @@ function digest(username, password, uri, httpMethod, body, authHeader) { if (qop === "auth-int") ha2.update(":").update(body); ha2 = ha2.digest("hex"); - let hash = crypto.createHash("md5"); + const hash = crypto.createHash("md5"); hash .update(ha1) .update(":") diff --git a/lib/cache.js b/lib/cache.js index 2652dd7..f5ab60f 100644 --- a/lib/cache.js +++ b/lib/cache.js @@ -142,17 +142,17 @@ function redisLock(lockName, ttl, callback) { } function mongoGet(key, callback) { - let expire = new Date(Date.now() - mongoTimeOffset); + const expire = new Date(Date.now() - mongoTimeOffset); if (Array.isArray(key)) { mongoCollection.find({ _id: { $in: key } }).toArray((err, res) => { if (err) return void callback(err); - let indices = {}; + const indices = {}; key.forEach((v, i) => { indices[v] = i; }); - let values = []; + const values = []; res.forEach(r => { if (r["expire"] > expire) values[indices[r["_id"]]] = r["value"]; }); @@ -183,7 +183,7 @@ function mongoSet(key, value, ttl, callback) { if (!ttl) ttl = MAX_CACHE_TTL; - let expire = new Date(Date.now() - mongoTimeOffset + ttl * 1000); + const expire = new Date(Date.now() - mongoTimeOffset + ttl * 1000); mongoCollection.save({ _id: key, value: value, expire: expire }, callback); } @@ -216,7 +216,7 @@ function mongoLock(lockName, ttl, callback) { throw err || new Error("Lock expired"); }); } else { - let expire = new Date(Date.now() - mongoTimeOffset + extendTtl * 1000); + const expire = new Date(Date.now() - mongoTimeOffset + extendTtl * 1000); mongoCollection.update( { _id: lockName, value: token }, { expire: expire }, @@ -228,8 +228,8 @@ function mongoLock(lockName, ttl, callback) { } } - let expireTest = new Date(Date.now() - mongoTimeOffset); - let expireSet = new Date(Date.now() - mongoTimeOffset + ttl * 1000); + const expireTest = new Date(Date.now() - mongoTimeOffset); + const expireSet = new Date(Date.now() - mongoTimeOffset + ttl * 1000); mongoCollection.update( { _id: lockName, expire: { $lte: expireTest } }, diff --git a/lib/cluster.js b/lib/cluster.js index 6410465..e1a7a15 100644 --- a/lib/cluster.js +++ b/lib/cluster.js @@ -28,13 +28,13 @@ let respawnTimestamp = 0; let tooManyCrashesTimestamp = 0; function getDependencyVersions() { - let dependencies = [`node@${process.versions.node}`]; + const dependencies = [`node@${process.versions.node}`]; try { - let npmls = JSON.parse( + const npmls = JSON.parse( require("child_process").execSync("npm ls --prod --json --depth 0") ); - for (let k in npmls.dependencies) + for (const k in npmls.dependencies) dependencies.push(`${k}@${npmls.dependencies[k].version}`); } catch (err) { // Continue regardless of error @@ -44,9 +44,9 @@ function getDependencyVersions() { } function getConfig() { - let conf = []; + const conf = []; const keys = Object.keys(process.env); - for (let k of keys) { + for (const k of keys) { if (k.startsWith("GENIEACS_")) { const name = k.slice(9); const value = process.env[k]; @@ -59,7 +59,7 @@ function getConfig() { } function restartWorker(worker, code, signal) { - let msg = { + const msg = { message: "Worker died", pid: worker.process.pid }; @@ -81,7 +81,7 @@ function restartWorker(worker, code, signal) { if (now - tooManyCrashesTimestamp > 60000) { process.exitCode = 1; cluster.removeListener("exit", restartWorker); - for (let pid in cluster.workers) cluster.workers[pid].kill(); + for (const pid in cluster.workers) cluster.workers[pid].kill(); logger.error({ message: "Too many crashes, exiting", @@ -142,7 +142,7 @@ function start(service) { }); cluster.removeListener("exit", restartWorker); - for (let pid in cluster.workers) cluster.workers[pid].kill(); + for (const pid in cluster.workers) cluster.workers[pid].kill(); }); cluster.setupMaster({ @@ -165,7 +165,7 @@ process.on("uncaughtException", err => { }); process.exitCode = 1; cluster.removeListener("exit", restartWorker); - for (let pid in cluster.workers) cluster.workers[pid].kill(); + for (const pid in cluster.workers) cluster.workers[pid].kill(); }); exports.start = start; diff --git a/lib/common.js b/lib/common.js index 50cf32f..15a3609 100644 --- a/lib/common.js +++ b/lib/common.js @@ -36,7 +36,7 @@ function generateDeviceId(deviceIdStruct) { return str.replace(/[^A-Za-z0-9_]/g, chr => { const buf = Buffer.from(chr, "utf8"); let rep = ""; - for (let b of buf) rep += "%" + b.toString(16).toUpperCase(); + for (const b of buf) rep += "%" + b.toString(16).toUpperCase(); return rep; }); } @@ -139,7 +139,7 @@ function parsePath(pattern, start, res) { path.alias |= 1 << path.length; i = parseAlias(pattern, i + 1, path) + 1; } else { - let j = i; + const j = i; while (i < pattern.length && pattern[i] !== ":" && pattern[i] !== ".") ++i; @@ -169,7 +169,7 @@ function addPathMeta(path) { path.alias = 0; path.wildcard = 0; - for (let [i, p] of path.entries()) { + for (const [i, p] of path.entries()) { if (Array.isArray(p)) { path.alias |= 1 << i; for (let j = 0; j < p.length; j += 2) addPathMeta(p[j]); diff --git a/lib/config.js b/lib/config.js index 560357d..66f8904 100644 --- a/lib/config.js +++ b/lib/config.js @@ -138,7 +138,7 @@ function setConfig(name, value, commandLineArgument) { } let _value = null; - for (let [optionName, optionDetails] of Object.entries(options)) { + for (const [optionName, optionDetails] of Object.entries(options)) { let n = optionName; if (commandLineArgument) n = n.toLowerCase().replace(/_/g, "-"); diff --git a/lib/cwmp.js b/lib/cwmp.js index b05ece0..cb3a2ce 100644 --- a/lib/cwmp.js +++ b/lib/cwmp.js @@ -288,7 +288,7 @@ function applyPresets(sessionContext) { const RETRY_DELAY = config.get("RETRY_DELAY", sessionContext.deviceId); if (sessionContext.faults) { - for (let [channel, fault] of Object.entries(sessionContext.faults)) { + for (const [channel, fault] of Object.entries(sessionContext.faults)) { let retryTimestamp = 0; if (!fault.retryNow) { retryTimestamp = @@ -327,7 +327,7 @@ function applyPresets(sessionContext) { } let eventsMatch = true; - for (let [k, v] of Object.entries(preset.events)) { + for (const [k, v] of Object.entries(preset.events)) { if (!v !== !deviceEvents[k.replace(/\s+/g, "_")]) { eventsMatch = false; break; @@ -346,7 +346,7 @@ function applyPresets(sessionContext) { } filteredPresets.push(preset); - for (let k of Object.keys(preset.precondition)) { + for (const k of Object.keys(preset.precondition)) { sessionContext.channels[preset.channel] = 0; const p = k.split(/([^a-zA-Z0-9\-_.].*)/, 1)[0]; parameters[p] = common.parsePath(p); @@ -354,7 +354,7 @@ function applyPresets(sessionContext) { } const declarations = []; - for (let v of Object.values(parameters)) + for (const v of Object.values(parameters)) declarations.push([v, 1, { value: 1 }]); session.rpcRequest( @@ -374,7 +374,7 @@ function applyPresets(sessionContext) { session.clearProvisions(sessionContext); const parameterValues = {}; - for (let [k, v] of Object.entries(parameters)) { + for (const [k, v] of Object.entries(parameters)) { const unpacked = device.unpack(deviceData, v); if (!unpacked[0]) continue; const attrs = deviceData.attributes.get(unpacked[0]); @@ -398,7 +398,7 @@ function applyPresets(sessionContext) { } } - for (let [channel, provisions] of Object.entries( + for (const [channel, provisions] of Object.entries( appendProvisionsToFaults )) { if ( @@ -484,7 +484,7 @@ function nextRpc(sessionContext) { if (acsRequest) return void sendAcsRequest(sessionContext, id, acsRequest); - for (let [channel, flags] of Object.entries(sessionContext.channels)) { + for (const [channel, flags] of Object.entries(sessionContext.channels)) { if (flags && sessionContext.faults[channel]) { delete sessionContext.faults[channel]; if (!sessionContext.faultsTouched) sessionContext.faultsTouched = {}; @@ -980,8 +980,8 @@ function processRequest(sessionContext, rpc) { session.timeoutOperations(sessionContext, (err, faults, operations) => { if (err) return void throwError(err, sessionContext.httpResponse); - for (let i of faults) { - for (let [k, v] of Object.entries(operations[i].retries)) + for (const i of faults) { + for (const [k, v] of Object.entries(operations[i].retries)) sessionContext.retries[k] = v; recordFault( @@ -1118,7 +1118,7 @@ function listener(httpRequest, httpResponse) { return; } - let parseWarnings = []; + const parseWarnings = []; let rpc; try { rpc = soap.request( @@ -1198,7 +1198,7 @@ function listener(httpRequest, httpResponse) { _sessionContext.cacheUntil = cacheUntil; _sessionContext.faults = faults; _sessionContext.retries = {}; - for (let [k, v] of Object.entries(_sessionContext.faults)) { + for (const [k, v] of Object.entries(_sessionContext.faults)) { if (v.expiry >= _sessionContext.timestamp) { // Delete expired faults delete _sessionContext.faults[k]; diff --git a/lib/db.js b/lib/db.js index 68daa4a..2c7b5d8 100644 --- a/lib/db.js +++ b/lib/db.js @@ -144,7 +144,7 @@ function fetchDevice(id, timestamp, patterns, callback) { const projectionTree = {}; function func(path, pats, projTree) { const children = {}; - for (let pat of pats) { + for (const pat of pats) { const fragment = pat[0][path.length] || "*"; if (fragment === "*") { if (pat[1] << path.length) projection[path.join(".")] = 1; @@ -172,7 +172,7 @@ function fetchDevice(id, timestamp, patterns, callback) { } } - for (let [k, v] of Object.entries(children)) + for (const [k, v] of Object.entries(children)) func(path.concat(k), v, projTree[k]); } @@ -187,7 +187,7 @@ function fetchDevice(id, timestamp, patterns, callback) { projection = optimizeProjection(projection); - for (let k of Object.keys(projection)) { + for (const k of Object.keys(projection)) { if (k === "" || k === "Events" || k.startsWith("Events.")) { if (k === "" || k === "Events" || k === "Events._writable") { res.push([ @@ -343,7 +343,7 @@ function fetchDevice(id, timestamp, patterns, callback) { res.push([path, t, attrs]); } - for (let [k, v] of Object.entries(obj)) { + for (const [k, v] of Object.entries(obj)) { if (!k.startsWith("_")) { obj["_object"] = true; storeParams( @@ -358,7 +358,7 @@ function fetchDevice(id, timestamp, patterns, callback) { } if (!descendantsFetched) { - for (let k of Object.keys(projTree)) { + for (const k of Object.keys(projTree)) { const p = path.concat(k); loaded.push([p, ((1 << path.length) - 1) ^ ((1 << MAX_DEPTH) - 1)]); if ((obj["_object"] || !path.length) && obj["_timestamp"]) @@ -369,7 +369,7 @@ function fetchDevice(id, timestamp, patterns, callback) { } } - for (let [k, v] of Object.entries(device)) { + for (const [k, v] of Object.entries(device)) { switch (k) { case "_lastInform": res.push([ @@ -519,7 +519,7 @@ function fetchDevice(id, timestamp, patterns, callback) { function saveDevice(deviceId, deviceData, isNew, sessionTimestamp, callback) { const update = { $set: {}, $unset: {}, $addToSet: {}, $pull: {} }; - for (let diff of deviceData.timestamps.diff()) { + for (const diff of deviceData.timestamps.diff()) { if (diff[0].wildcard !== 1 << (diff[0].length - 1)) continue; if ( @@ -552,7 +552,7 @@ function saveDevice(deviceId, deviceData, isNew, sessionTimestamp, callback) { } } - for (let diff of deviceData.attributes.diff()) { + for (const diff of deviceData.attributes.diff()) { if (diff[1] === diff[2]) continue; const path = diff[0]; @@ -647,7 +647,7 @@ function saveDevice(deviceId, deviceData, isNew, sessionTimestamp, callback) { continue; } - for (let attrName of Object.keys(diff[2])) { + for (const attrName of Object.keys(diff[2])) { // Param timestamps may be greater than session timestamp to track revisions if (diff[2][attrName][0] > sessionTimestamp) diff[2][attrName][0] = sessionTimestamp; @@ -694,7 +694,7 @@ function saveDevice(deviceId, deviceData, isNew, sessionTimestamp, callback) { } if (diff[1]) { - for (let attrName of Object.keys(diff[1])) { + for (const attrName of Object.keys(diff[1])) { if ( diff[1][attrName][1] != null && (!diff[2] || !diff[2][attrName] || !diff[2][attrName][1]) @@ -716,16 +716,16 @@ function saveDevice(deviceId, deviceData, isNew, sessionTimestamp, callback) { // to regular parameters or vice versa. Reason being that _timestamp // represents two different things depending on whether the parameter // is an object or not. - for (let k of Object.keys(update["$unset"])) + for (const k of Object.keys(update["$unset"])) if (update["$set"][k] != null) delete update["$unset"][k]; // Remove empty keys - for (let [k, v] of Object.entries(update)) { + for (const [k, v] of Object.entries(update)) { if (k === "$addToSet") { - for (let [kk, vv] of Object.entries(v)) + for (const [kk, vv] of Object.entries(v)) if (!vv["$each"].length) delete v[kk]; } else if (k === "$pull") { - for (let [kk, vv] of Object.entries(v)) + for (const [kk, vv] of Object.entries(v)) if (!vv["$in"].length) delete v[kk]; } if (!Object.keys(v).length) delete update[k]; diff --git a/lib/default-provisions.js b/lib/default-provisions.js index 7c2edb3..1b71de6 100644 --- a/lib/default-provisions.js +++ b/lib/default-provisions.js @@ -26,13 +26,13 @@ const scheduling = require("./scheduling"); const MAX_DEPTH = config.get("MAX_DEPTH"); function refresh(sessionContext, provision, declarations) { - let path = common.parsePath(provision[1]).slice(); - let l = path.length; + const path = common.parsePath(provision[1]).slice(); + const l = path.length; path.length = MAX_DEPTH; path.fill("*", l); - let every = 1000 * (provision[2] || 1); - let offset = scheduling.variance(sessionContext.deviceId, every); - let t = scheduling.interval(sessionContext.timestamp, every, offset); + const every = 1000 * (provision[2] || 1); + const offset = scheduling.variance(sessionContext.deviceId, every); + const t = scheduling.interval(sessionContext.timestamp, every, offset); for (let i = l; i < path.length; ++i) { declarations.push([ @@ -46,14 +46,14 @@ function refresh(sessionContext, provision, declarations) { } function value(sessionContext, provision, declarations) { - let path = common.parsePath(provision[1]); + const path = common.parsePath(provision[1]); declarations.push([path, 1, { value: 1 }, null, { value: [provision[2]] }]); return true; } function tag(sessionContext, provision, declarations) { - let path = ["Tags", provision[1]]; + const path = ["Tags", provision[1]]; declarations.push([path, 1, { value: 1 }, null, { value: [provision[2]] }]); return true; @@ -84,7 +84,7 @@ function reset(sessionContext, provision, declarations) { } function download(sessionContext, provision, declarations) { - let alias = [ + const alias = [ ["FileType"], provision[1] || "", ["FileName"], @@ -116,14 +116,14 @@ function instances( if (Number.isNaN(count)) return true; - let path = common.parsePath(provision[1]); + const path = common.parsePath(provision[1]); if (provision[2][0] === "+" || provision[2][0] === "-") { declarations.push([path, 1]); if (endRevision === startRevision) return false; - let unpacked = device.unpack( + const unpacked = device.unpack( sessionContext.deviceData, path, startRevision + 1 diff --git a/lib/device.js b/lib/device.js index 3cb3213..781a7bc 100644 --- a/lib/device.js +++ b/lib/device.js @@ -91,7 +91,7 @@ function getAliasDeclarations(path, timestamp) { for (let i = prefix.length; i < pattern.length; ++i) { if (Array.isArray(pattern[i])) { - let pat = pattern[i]; + const pat = pattern[i]; pattern[i] = "*"; for (let j = 0; j < pat.length; j += 2) recursive(pat[j], pattern.slice(0, i + 1)); @@ -110,10 +110,10 @@ function getAliasDeclarations(path, timestamp) { function unpack(deviceData, path, revision) { let allMatches = []; if (!path.alias) { - for (let p of deviceData.paths.find(path, false, true)) + for (const p of deviceData.paths.find(path, false, true)) if (deviceData.attributes.has(p, revision)) allMatches.push(p); } else { - let wildcardPath = path.slice(); + const wildcardPath = path.slice(); wildcardPath.wildcard = path.wildcard; for (let i = 0; i < wildcardPath.length; ++i) { if (Array.isArray(wildcardPath[i])) { @@ -122,13 +122,13 @@ function unpack(deviceData, path, revision) { } } - for (let p of deviceData.paths.find(wildcardPath, false, true)) + for (const p of deviceData.paths.find(wildcardPath, false, true)) if (deviceData.attributes.has(p, revision)) allMatches.push(p); for (let i = path.length - 1; i >= 0; --i) { if (Array.isArray(path[i])) { for (let j = 0; j < path[i].length; j += 2) { - let p = wildcardPath.slice(0, i + 1).concat(path[i][j]); + const p = wildcardPath.slice(0, i + 1).concat(path[i][j]); p.alias = ((wildcardPath.alias & ((1 << (i + 1)) - 1)) + path[i][j].alias) << (i + 1); @@ -136,10 +136,10 @@ function unpack(deviceData, path, revision) { ((wildcardPath.wildcard & ((1 << (i + 1)) - 1)) + path[i][j].wildcard) << (i + 1); - let unpacked = unpack(deviceData, p, revision); - let filtered = []; - for (let up of unpacked) { - let attributes = deviceData.attributes.get(up, revision); + const unpacked = unpack(deviceData, p, revision); + const filtered = []; + for (const up of unpacked) { + const attributes = deviceData.attributes.get(up, revision); if ( attributes && attributes.value && @@ -171,8 +171,9 @@ function unpack(deviceData, path, revision) { if (a === b) continue; // Use numeric sorting for numbers - let ia = parseInt(a), - ib = parseInt(b); + const ia = parseInt(a); + const ib = parseInt(b); + if (ia.toString() === a && ib.toString() === b) { a = ia; b = ib; @@ -188,7 +189,7 @@ function unpack(deviceData, path, revision) { } function clear(deviceData, path, timestamp, attributes, changeFlags = 0) { - let changeTrackers = {}; + const changeTrackers = {}; timestamp = timestamp || 0; @@ -200,16 +201,16 @@ function clear(deviceData, path, timestamp, attributes, changeFlags = 0) { attributes.value = attributes.object; } - for (let p of deviceData.paths.find( + for (const p of deviceData.paths.find( path, true, true, descendantsTimestamp ? 99 : path.length )) { - let tracker = deviceData.trackers.get(p); - for (let k in tracker) changeTrackers[k] |= tracker[k]; + const tracker = deviceData.trackers.get(p); + for (const k in tracker) changeTrackers[k] |= tracker[k]; - let currentTimestamp = deviceData.timestamps.get(p); + const currentTimestamp = deviceData.timestamps.get(p); if (currentTimestamp === undefined) continue; if ( @@ -220,10 +221,10 @@ function clear(deviceData, path, timestamp, attributes, changeFlags = 0) { deviceData.attributes.delete(p); changeFlags |= 1; } else if (attributes && p.length == path.length) { - let currentAttributes = deviceData.attributes.get(p); + const currentAttributes = deviceData.attributes.get(p); if (currentAttributes) { let newAttrs; - for (let attrName in attributes) { + for (const attrName in attributes) { if ( attrName in currentAttributes && attributes[attrName] > currentAttributes[attrName][0] @@ -242,7 +243,7 @@ function clear(deviceData, path, timestamp, attributes, changeFlags = 0) { // Note: For performance, we're merging all changes together rather than // mark changes based the exact parameters affected. - for (let k in changeTrackers) + for (const k in changeTrackers) if (changeTrackers[k] & changeFlags) deviceData.changes.add(k); } @@ -264,7 +265,7 @@ function compareEquality(a, b) { function set(deviceData, path, timestamp, attributes, toClear) { path = deviceData.paths.add(path); - let currentTimestamp = deviceData.timestamps.get(path); + const currentTimestamp = deviceData.timestamps.get(path); let currentAttributes; @@ -289,10 +290,10 @@ function set(deviceData, path, timestamp, attributes, toClear) { ) attributes.value = [attributes.object[0]]; - let newAttributes = Object.assign({}, currentAttributes, attributes); + const newAttributes = Object.assign({}, currentAttributes, attributes); if (currentAttributes) { - for (let attrName in attributes) { + for (const attrName in attributes) { timestamp = Math.max(timestamp, attributes[attrName][0]); if (!(attrName in currentAttributes)) changeFlags |= CHANGE_FLAGS[attrName]; @@ -331,7 +332,7 @@ function set(deviceData, path, timestamp, attributes, toClear) { deviceData.attributes.delete(path); changeFlags |= 1; } else if (path.wildcard) { - for (let p of deviceData.paths.find(path, false, true, path.length)) { + for (const p of deviceData.paths.find(path, false, true, path.length)) { if (timestamp > deviceData.timestamps.get(p)) { toClear = toClear || []; toClear.push([p, timestamp]); @@ -348,9 +349,9 @@ function set(deviceData, path, timestamp, attributes, toClear) { toClear = toClear || []; toClear.push([path, 0, { object: attributes.object[0] }, changeFlags]); } else { - for (let p of deviceData.paths.find(path, true, false, path.length)) { - let tracker = deviceData.trackers.get(p); - for (let k in tracker) + for (const p of deviceData.paths.find(path, true, false, path.length)) { + const tracker = deviceData.trackers.get(p); + for (const k in tracker) if (tracker[k] & changeFlags) deviceData.changes.add(k); } } @@ -363,7 +364,8 @@ function track(deviceData, path, marker, attributes) { path = deviceData.paths.add(path); let f = 1; - if (attributes) for (let attrName of attributes) f |= CHANGE_FLAGS[attrName]; + if (attributes) + for (const attrName of attributes) f |= CHANGE_FLAGS[attrName]; let cur = deviceData.trackers.get(path); if (!cur) { @@ -376,11 +378,11 @@ function track(deviceData, path, marker, attributes) { function clearTrackers(deviceData, tracker) { if (Array.isArray(tracker)) { - for (let v of deviceData.trackers.values()) - for (let t of tracker) delete v[t]; - for (let t of tracker) deviceData.changes.delete(t); + for (const v of deviceData.trackers.values()) + for (const t of tracker) delete v[t]; + for (const t of tracker) deviceData.changes.delete(t); } else { - for (let v of deviceData.trackers.values()) delete v[tracker]; + for (const v of deviceData.trackers.values()) delete v[tracker]; deviceData.changes.delete(tracker); } } diff --git a/lib/extension-wrapper.js b/lib/extension-wrapper.js index d441bde..7e27443 100644 --- a/lib/extension-wrapper.js +++ b/lib/extension-wrapper.js @@ -27,7 +27,7 @@ function errorToFault(err) { if (!err.name) return { code: "ext", message: `${err}` }; - let fault = { + const fault = { code: `ext.${err.name}`, message: err.message, detail: { @@ -39,7 +39,7 @@ function errorToFault(err) { if (err.stack) { fault.detail.stack = err.stack; // Trim the stack trace - let stackTrimIndex = fault.detail.stack.match( + const stackTrimIndex = fault.detail.stack.match( /\s+at\s[^\s]+\s\(.*extension-wrapper\.js:.+\)/ ); if (stackTrimIndex) @@ -50,7 +50,7 @@ function errorToFault(err) { } process.on("uncaughtException", err => { - let fault = errorToFault(err); + const fault = errorToFault(err); jobs.forEach(jobId => { process.send([jobId, fault]); }); @@ -62,7 +62,7 @@ process.on("message", message => { jobs.add(message[0]); if (!script) { - let cwd = process.env["GENIEACS_CONFIG_DIR"] + "/ext"; + const cwd = process.env["GENIEACS_CONFIG_DIR"] + "/ext"; process.chdir(cwd); script = require(`${cwd}/${fileName}`); } @@ -70,7 +70,7 @@ process.on("message", message => { const funcName = message[1][0]; if (!script[funcName]) { - let fault = { + const fault = { code: "ext", message: `No such function '${funcName}' in extension '${fileName}'` }; diff --git a/lib/extensions.js b/lib/extensions.js index 4037a64..2ebc1a4 100644 --- a/lib/extensions.js +++ b/lib/extensions.js @@ -29,7 +29,7 @@ const processes = {}; const jobs = {}; function messageHandler(message) { - let func = jobs[message[0]]; + const func = jobs[message[0]]; if (func) { delete jobs[message[0]]; func(null, message[1], message[2]); @@ -37,10 +37,10 @@ function messageHandler(message) { } function run(args, callback) { - let scriptName = args[0]; + const scriptName = args[0]; if (!processes[scriptName]) { - let p = childProcess.fork("lib/extension-wrapper", [scriptName]); + const p = childProcess.fork("lib/extension-wrapper", [scriptName]); processes[scriptName] = p; p.on("error", () => { @@ -60,7 +60,7 @@ function run(args, callback) { p.on("message", messageHandler); } - let id = crypto.randomBytes(8).toString("hex"); + const id = crypto.randomBytes(8).toString("hex"); jobs[id] = callback; setTimeout(() => { if (id in jobs) { @@ -75,11 +75,11 @@ function run(args, callback) { function kill(process, callback) { if (process.signalCode !== null || process.exitCode !== null) return; - let timeToKill = Date.now() + 5000; + const timeToKill = Date.now() + 5000; process.kill(); - let t = setInterval(() => { + const t = setInterval(() => { if (process.signalCode !== null || process.exitCode !== null) { clearInterval(t); if (callback) callback(); @@ -93,7 +93,7 @@ function kill(process, callback) { function killAll(callback) { let counter = 1; - for (let n in processes) { + for (const n in processes) { ++counter; kill(processes[n], () => { if (--counter == 0 && callback) callback(); diff --git a/lib/gpn-heuristic.js b/lib/gpn-heuristic.js index c91728e..83c26ed 100644 --- a/lib/gpn-heuristic.js +++ b/lib/gpn-heuristic.js @@ -34,11 +34,11 @@ function estimateGpnCount(gpnPatterns, depth = 0) { let wildcardDiscovered = false; let gpnCount = 0; - for (let pattern of gpnPatterns) { + for (const pattern of gpnPatterns) { const path = pattern[0]; const flags = pattern[1] >> depth; - let k = path[depth]; + const k = path[depth]; if (!k) { if (flags & 1) gpnCount = 1; @@ -67,8 +67,8 @@ function estimateGpnCount(gpnPatterns, depth = 0) { estimateGpnCount(wildcardChildren, depth + 1) * WILDCARD_MULTIPLIER; } - for (let k of Object.keys(children)) { - let c = estimateGpnCount(children[k].concat(wildcardChildren), depth + 1); + for (const k of Object.keys(children)) { + const c = estimateGpnCount(children[k].concat(wildcardChildren), depth + 1); wildcardGpnCount -= c; gpnCount += c; } diff --git a/lib/instance-set.js b/lib/instance-set.js index 91641aa..a17bd0d 100644 --- a/lib/instance-set.js +++ b/lib/instance-set.js @@ -32,10 +32,10 @@ class InstanceSet { } superset(instance) { - let res = []; - for (let inst of this.set) { + const res = []; + for (const inst of this.set) { let match = true; - for (let k in instance) { + for (const k in instance) { if (inst[k] !== instance[k]) { match = false; break; @@ -46,8 +46,8 @@ class InstanceSet { } res.sort((a, b) => { - let keysA = Object.keys(a); - let keysB = Object.keys(b); + const keysA = Object.keys(a); + const keysB = Object.keys(b); if (keysA.length != keysB.length) return keysB.length - keysA.length; @@ -68,11 +68,11 @@ class InstanceSet { } subset(instance) { - let res = []; + const res = []; - for (let inst of this.set) { + for (const inst of this.set) { let match = true; - for (let k in inst) { + for (const k in inst) { if (inst[k] !== instance[k]) { match = false; break; @@ -83,8 +83,8 @@ class InstanceSet { } res.sort((a, b) => { - let keysA = Object.keys(a); - let keysB = Object.keys(b); + const keysA = Object.keys(a); + const keysB = Object.keys(b); if (keysA.length != keysB.length) return keysA.length - keysB.length; diff --git a/lib/local-cache.js b/lib/local-cache.js index cf574cb..bc241a3 100644 --- a/lib/local-cache.js +++ b/lib/local-cache.js @@ -35,8 +35,8 @@ let presets, provisions, virtualParameters, files; function computeHash() { // MD5 hash for presets, provisions, virtual parameters for detecting changes - let h = crypto.createHash("md5"); - for (let p of presets) { + const h = crypto.createHash("md5"); + for (const p of presets) { h.update(JSON.stringify(p.name)); h.update(JSON.stringify(p.channel)); h.update(JSON.stringify(p.schedule)); @@ -49,18 +49,18 @@ function computeHash() { keys = Object.keys(provisions).sort(); h.update(JSON.stringify(keys)); - for (let k of keys) h.update(provisions[k].md5); + for (const k of keys) h.update(provisions[k].md5); keys = Object.keys(virtualParameters).sort(); h.update(JSON.stringify(keys)); - for (let k of keys) h.update(virtualParameters[k].md5); + for (const k of keys) h.update(virtualParameters[k].md5); hash = h.digest("hex"); } function flattenObject(src, prefix = "", dst = {}) { - for (let k of Object.keys(src)) { - let v = src[k]; + for (const k of Object.keys(src)) { + const v = src[k]; if (typeof v === "object" && !Array.isArray(v)) flattenObject(v, `${prefix}${k}.`, dst); else dst[`${prefix}${k}`] = v; @@ -122,10 +122,10 @@ function refresh(callback) { }); presets = []; - for (let preset of res) { + for (const preset of res) { let schedule = null; if (preset.schedule) { - let parts = preset.schedule.trim().split(/\s+/); + const parts = preset.schedule.trim().split(/\s+/); schedule = { md5: crypto .createHash("md5") @@ -146,14 +146,14 @@ function refresh(callback) { } } - let events = preset.events || {}; - let precondition = query.convertMongoQueryToFilters( + const events = preset.events || {}; + const precondition = query.convertMongoQueryToFilters( JSON.parse(preset.precondition) ); - let _provisions = preset.provisions || []; + const _provisions = preset.provisions || []; // Generate provisions from the old configuration format - for (let c of preset.configurations) { + for (const c of preset.configurations) { switch (c.type) { case "age": _provisions.push(["refresh", c.name, c.age]); @@ -176,15 +176,15 @@ function refresh(callback) { break; case "add_object": - for (let obj of objects) { + for (const obj of objects) { if (obj["_id"] === c.object) { - let alias = obj["_keys"] + const alias = obj["_keys"] .map(k => `${k}:${JSON.stringify(obj[k])}`) .join(","); - let p = `${c.name}.[${alias}]`; + const p = `${c.name}.[${alias}]`; _provisions.push(["instances", p, 1]); - for (let k in obj) { + for (const k in obj) { if ( !k.startsWith("_") && !(obj["_keys"].indexOf(k) !== -1) @@ -197,12 +197,12 @@ function refresh(callback) { break; case "delete_object": - for (let obj of objects) { + for (const obj of objects) { if (obj["_id"] === c.object) { - let alias = obj["_keys"] + const alias = obj["_keys"] .map(k => `${k}:${JSON.stringify(obj[k])}`) .join(","); - let p = `${c.name}.[${alias}]`; + const p = `${c.name}.[${alias}]`; _provisions.push(["instances", p, 0]); } } @@ -245,7 +245,7 @@ function refresh(callback) { } provisions = {}; - for (let r of res) { + for (const r of res) { provisions[r._id] = {}; provisions[r._id].md5 = crypto .createHash("md5") @@ -275,7 +275,7 @@ function refresh(callback) { } virtualParameters = {}; - for (let r of res) { + for (const r of res) { virtualParameters[r._id] = {}; virtualParameters[r._id].md5 = crypto .createHash("md5") @@ -305,7 +305,7 @@ function refresh(callback) { } files = {}; - for (let r of res) { + for (const r of res) { const id = r.filename || r._id.toString(); files[id] = {}; files[id].length = r.length; diff --git a/lib/logger.js b/lib/logger.js index 63660f5..a0eaf91 100644 --- a/lib/logger.js +++ b/lib/logger.js @@ -221,8 +221,8 @@ function formatSimple(details, systemd) { let meta = ""; - let kv = []; - for (let k of keys) + const kv = []; + for (const k of keys) if (!skip[k]) kv.push(`${k}=${JSON.stringify(details[k])}`); if (kv.length) meta = `; ${kv.join(" ")}`; diff --git a/lib/nbi.js b/lib/nbi.js index b805ea6..f4fad47 100644 --- a/lib/nbi.js +++ b/lib/nbi.js @@ -592,7 +592,7 @@ function listener(request, response) { let projection = null; if (urlParts.query.projection) { projection = {}; - for (let p of urlParts.query.projection.split(",")) + for (const p of urlParts.query.projection.split(",")) projection[p.trim()] = 1; } @@ -601,7 +601,7 @@ function listener(request, response) { if (urlParts.query.sort) { const s = JSON.parse(urlParts.query.sort); const sort = {}; - for (let [k, v] of Object.entries(s)) { + for (const [k, v] of Object.entries(s)) { if (k[k.lastIndexOf(".") + 1] !== "_" && collectionName === "devices") sort[`${k}._value`] = v; else sort[k] = v; diff --git a/lib/path-set.js b/lib/path-set.js index c00b15d..7525e95 100644 --- a/lib/path-set.js +++ b/lib/path-set.js @@ -29,7 +29,7 @@ class PathSet { } add(path) { - let p = this.get(path); + const p = this.get(path); if (p) return p; @@ -40,7 +40,7 @@ class PathSet { let wildcard = 0; for (let i = 0; i < path.length; ++i) { - let fragment = path[i]; + const fragment = path[i]; if (fragment === "*") wildcard = wildcard | (1 << i); if (!this.fragmentIndex[i]) this.fragmentIndex[i] = {}; @@ -64,14 +64,14 @@ class PathSet { if (this.lengthIndex[pattern.length].has(pattern)) return pattern; - let sets = []; + const sets = []; sets.push(this.lengthIndex[pattern.length]); for (let i = 0; i < pattern.length; ++i) { if (!this.fragmentIndex[i]) return null; - let fragment = pattern[i]; + const fragment = pattern[i]; if (!this.fragmentIndex[i][fragment]) return null; @@ -82,9 +82,9 @@ class PathSet { return a.size - b.size; }); - let smallestSet = sets.shift(); + const smallestSet = sets.shift(); for (let path of smallestSet) { - for (let s of sets) { + for (const s of sets) { if (!s.has(path)) { path = null; break; @@ -98,8 +98,8 @@ class PathSet { } find(pattern, superset = false, subset = false, depth = pattern.length) { - let res = []; - let groups = [[]]; + const res = []; + const groups = [[]]; for (let i = pattern.length; i <= depth; ++i) if (this.lengthIndex[i]) groups[0].push(this.lengthIndex[i]); @@ -109,11 +109,11 @@ class PathSet { for (let i = 0; i < pattern.length; ++i) { if (!this.fragmentIndex[i]) return res; - let fragment = pattern[i]; + const fragment = pattern[i]; if (fragment === "*" && subset) continue; - let g = []; + const g = []; if (this.fragmentIndex[i][fragment]) g.push(this.fragmentIndex[i][fragment]); @@ -137,12 +137,12 @@ class PathSet { ); }); - let smallestGroup = groups.shift(); - for (let set of smallestGroup) { + const smallestGroup = groups.shift(); + for (const set of smallestGroup) { for (let path of set) { - for (let group of groups) { + for (const group of groups) { let found = false; - for (let s of group) { + for (const s of group) { if (s.has(path)) { found = true; break; diff --git a/lib/query.js b/lib/query.js index fe24064..366c7a3 100644 --- a/lib/query.js +++ b/lib/query.js @@ -37,15 +37,15 @@ function stringToRegexp(input, flags) { function normalize(input) { if (common.typeOf(input) === common.STRING_TYPE) { const vals = [input]; - let m = /^\/(.*?)\/(g?i?m?y?)$/.exec(input); + const m = /^\/(.*?)\/(g?i?m?y?)$/.exec(input); if (m) vals.push({ $regex: new RegExp(m[1], m[2]) }); if (+input === parseFloat(input)) vals.push(+input); - let d = new Date(input); + const d = new Date(input); if (input.length >= 8 && d.getFullYear() > 1983) vals.push(d); - let r = stringToRegexp(input); + const r = stringToRegexp(input); if (r !== false) vals.push({ $regex: r }); return vals; @@ -56,7 +56,7 @@ function normalize(input) { function expandValue(value) { if (common.typeOf(value) === common.ARRAY_TYPE) { let a = []; - for (let j of value) a = a.conact(expandValue(j)); + for (const j of value) a = a.conact(expandValue(j)); return [a]; } else if (common.typeOf(value) !== common.OBJECT_TYPE) { const n = normalize(value); @@ -68,7 +68,7 @@ function expandValue(value) { const indices = []; const keys = []; const values = []; - for (let [k, v] of Object.entries(value)) { + for (const [k, v] of Object.entries(value)) { keys.push(k); values.push(expandValue(v)); indices.push(0); @@ -95,7 +95,7 @@ function permute(param, val) { if (param[param.lastIndexOf(".") + 1] !== "_") param += "._value"; - for (let v of values) { + for (const v of values) { const obj = {}; obj[param] = v; conditions.push(obj); @@ -106,7 +106,7 @@ function permute(param, val) { function expand(query) { const newQuery = {}; - for (let [k, v] of Object.entries(query)) { + for (const [k, v] of Object.entries(query)) { if (k[0] === "$") { // Operator newQuery[k] = v.map(e => expand(e)); @@ -117,7 +117,7 @@ function expand(query) { if (v && (v["$ne"] != null || v["$not"] != null)) { if (Object.keys(v).length > 1) throw new Error("Cannot mix $ne or $not with other operators"); - for (let c of conditions) newQuery["$an"].push(c); + for (const c of conditions) newQuery["$an"].push(c); } else { newQuery["$and"].push({ $or: conditions }); } @@ -159,7 +159,7 @@ function testExpressions(params, expressions, lop) { function test(params, query) { let res; - for (let [k, v] of Object.entries(query)) { + for (const [k, v] of Object.entries(query)) { if (k.charAt(0) === "$") { // Logical operator res = testExpressions(params, v, k); @@ -174,7 +174,7 @@ function test(params, query) { else res = v === value; } } else { - for (let [k2, v2] of Object.entries(v)) { + for (const [k2, v2] of Object.entries(v)) { switch (k2) { case "$ne": if (common.typeOf(value) === common.ARRAY_TYPE) @@ -234,7 +234,7 @@ function matchType(src, dst) { } function testFilter(obj, filter) { - for (let [k, v] of Object.entries(filter)) { + for (const [k, v] of Object.entries(filter)) { const [param, op] = k.split(/([^a-zA-Z0-9\-_.].*)/, 2); const val = matchType(obj[param], v); switch (op) { @@ -269,7 +269,7 @@ function convertMongoQueryToFilters(query, filters) { for (let [k, v] of Object.entries(query)) { if (k[0] === "$") { if (k === "$and") - for (let vv of v) convertMongoQueryToFilters(vv, filters); + for (const vv of v) convertMongoQueryToFilters(vv, filters); else throw new Error(`Operator ${k} not supported`); } else if (k === "_tags") { if (common.typeOf(v) === common.OBJECT_TYPE) { @@ -313,7 +313,7 @@ function convertMongoQueryToFilters(query, filters) { } if (common.typeOf(v) === common.OBJECT_TYPE) { - for (let [kk, vv] of Object.entries(v)) { + for (const [kk, vv] of Object.entries(v)) { switch (kk) { case "$eq": filters[k] = vv; @@ -347,13 +347,13 @@ function convertMongoQueryToFilters(query, filters) { } function sanitizeQueryTypes(query, types) { - for (let [k, v] of Object.entries(query)) { + for (const [k, v] of Object.entries(query)) { if (k[0] === "$") { // Logical operator - for (let vv of v) sanitizeQueryTypes(vv, types); + for (const vv of v) sanitizeQueryTypes(vv, types); } else if (k in types) { if (common.typeOf(v) === common.OBJECT_TYPE) { - for (let [kk, vv] of Object.entries(v)) { + for (const [kk, vv] of Object.entries(v)) { switch (kk) { case "$in": case "$nin": diff --git a/lib/sandbox.js b/lib/sandbox.js index fce7ba8..f2eb5b4 100644 --- a/lib/sandbox.js +++ b/lib/sandbox.js @@ -56,7 +56,7 @@ function runExtension(sessionContext, key, extCall, callback) { const callbacks = re[key]; delete re[key]; if (!err && !fault) sessionContext.extensionsCache[key] = res; - for (let c of callbacks) c(err, fault); + for (const c of callbacks) c(err, fault); }); } } @@ -83,7 +83,7 @@ class SandboxDate { let offset = 0; if (variance) offset = scheduling.variance(state.sessionContext.deviceId, variance); - let cron = scheduling.parseCron(intervalOrCron); + const cron = scheduling.parseCron(intervalOrCron); t = scheduling.cron(t, cron, offset)[0]; } else if (intervalOrCron) { throw new Error("Invalid Date.now() argument"); @@ -105,7 +105,7 @@ random.seed = function(s) { class ParameterWrapper { constructor(path, attributes, unpacked, unpackedRevision) { - for (let attrName of attributes) { + for (const attrName of attributes) { Object.defineProperty(this, attrName, { get: function() { if (state.uncommitted) commit(); @@ -121,7 +121,7 @@ class ParameterWrapper { if (!unpacked.length) return UNDEFINED; - let attr = state.sessionContext.deviceData.attributes.get( + const attr = state.sessionContext.deviceData.attributes.get( unpacked[0], state.revision )[attrName]; @@ -183,7 +183,7 @@ class ParameterWrapper { ); } - for (let p of unpacked) + for (const p of unpacked) yield new ParameterWrapper(p, attributes, [p], state.revision); }; } @@ -195,12 +195,12 @@ function declare(path, timestamps, values) { if (!values) values = {}; - let parsedPath = common.parsePath(path); + const parsedPath = common.parsePath(path); - let declaration = [parsedPath, 1]; - let attrs = {}; + const declaration = [parsedPath, 1]; + const attrs = {}; - for (let attrName in values) { + for (const attrName in values) { if (!timestamps[attrName]) timestamps[attrName] = 1; if (attrName === "path") { @@ -214,7 +214,7 @@ function declare(path, timestamps, values) { } } - for (let attrName in timestamps) { + for (const attrName in timestamps) { if (attrName === "path") { declaration[1] = timestamps.path; } else { @@ -251,8 +251,8 @@ function commit() { function ext() { ++state.extCounter; - let extCall = Array.from(arguments).map(String); - let key = `${state.revision}: ${JSON.stringify(extCall)}`; + const extCall = Array.from(arguments).map(String); + const key = `${state.revision}: ${JSON.stringify(extCall)}`; if (key in state.sessionContext.extensionsCache) return state.sessionContext.extensionsCache[key]; @@ -296,7 +296,7 @@ function errorToFault(err) { if (!err.name) return { code: "script", message: `${err}` }; - let fault = { + const fault = { code: `script.${err.name}`, message: err.message, detail: { @@ -308,7 +308,7 @@ function errorToFault(err) { if (err.stack) { fault.detail.stack = err.stack; // Trim the stack trace at the self-executing anonymous wrapper function - let stackTrimIndex = fault.detail.stack.match( + const stackTrimIndex = fault.detail.stack.match( /\s+at\s[^\s]+\s+at\s[^\s]+\s\(vm\.js.+\)/ ); if (stackTrimIndex) @@ -339,7 +339,7 @@ function run( extCounter: extCounter }; - for (let n of Object.keys(context)) delete context[n]; + for (const n of Object.keys(context)) delete context[n]; Object.assign(context, globals); @@ -354,8 +354,8 @@ function run( else return void callback(null, errorToFault(err)); } - let _state = state; - let args = Array.from(arguments); + const _state = state; + const args = Array.from(arguments); // Need to maintain a counter of ext() calls to avoid calling certain // functions (e.g. log()) multiple times as calling ext() results in @@ -363,7 +363,7 @@ function run( args[6] = 0 - (state.extCounter - extCounter); let counter = 3; - for (let key of Object.keys(_state.extensions)) { + for (const key of Object.keys(_state.extensions)) { counter += 2; runExtension( _state.sessionContext, diff --git a/lib/scheduling.js b/lib/scheduling.js index d30b586..4329ac0 100644 --- a/lib/scheduling.js +++ b/lib/scheduling.js @@ -44,7 +44,7 @@ function interval(timestamp, intrvl, offset = 0) { } function parseCron(cronExp) { - let parts = cronExp.trim().split(/\s+/); + const parts = cronExp.trim().split(/\s+/); if (parts.length === 5) parts.unshift("*"); return later.schedule(later.parse.cron(parts.join(" "), true)); @@ -54,10 +54,10 @@ function cron(timestamp, schedule, offset = 0) { // TODO later.js doesn't throw erorr if expression is invalid! const ret = [0, 0]; - let prev = schedule.prev(1, new Date(timestamp + offset)); + const prev = schedule.prev(1, new Date(timestamp + offset)); if (prev) ret[0] = prev.setMilliseconds(0) - offset; - let next = schedule.next(1, new Date(timestamp + offset + 1000)); + const next = schedule.next(1, new Date(timestamp + offset + 1000)); if (next) ret[1] = next.setMilliseconds(0) - offset; return ret; diff --git a/lib/server.js b/lib/server.js index 324fecd..64be8d8 100644 --- a/lib/server.js +++ b/lib/server.js @@ -52,7 +52,7 @@ function closeServer(timeout, callback) { server.removeListener("request", listener); server.setTimeout(1); - let cb = callback; + const cb = callback; callback = null; setTimeout(cb, 1000); }, timeout).unref(); @@ -60,7 +60,7 @@ function closeServer(timeout, callback) { server.close(() => { if (!callback) return; - let cb = callback; + const cb = callback; callback = null; cb(); }); diff --git a/lib/session.js b/lib/session.js index e0fae1b..55e4bc6 100644 --- a/lib/session.js +++ b/lib/session.js @@ -412,7 +412,7 @@ function revertDownloadParameters(sessionContext, instance, callback) { "Download" ]); - let toClear = device.set(sessionContext.deviceData, p, timestamp, { + const toClear = device.set(sessionContext.deviceData, p, timestamp, { value: [ timestamp, [ @@ -2080,7 +2080,7 @@ function loadPath(sessionContext, path, depth) { if (trimWildcard < path.length) path = path.slice(0, trimWildcard); for (let i = 0; i <= path.length; ++i) { - let d = i === path.length ? 99 : i; + const d = i === path.length ? 99 : i; for (const sup of sessionContext.deviceData.paths.find( path.slice(0, i), true, diff --git a/lib/soap.js b/lib/soap.js index 9a97979..1426259 100644 --- a/lib/soap.js +++ b/lib/soap.js @@ -102,8 +102,8 @@ function event(xml) { function parameterInfoList(xml) { return xml.find("ParameterInfoStruct").map(e => { - let param = e.get("Name").text(); - let value = e.get("Writable").text(); + const param = e.get("Name").text(); + const value = e.get("Writable").text(); let parsed = parseBool(value); if (parsed === null) { @@ -122,8 +122,8 @@ function parameterValueList(xml) { return xml.find("ParameterValueStruct").map(e => { const valueElement = e.get("Value"); const valueType = valueElement.attr("type").value(); - let param = e.get("Name").text(); - let value = valueElement.text(); + const param = e.get("Name").text(); + const value = valueElement.text(); let parsed = value; if (valueType === "xsd:boolean") { parsed = parseBool(value); @@ -447,7 +447,7 @@ function request(data, cwmpVersion, warn) { } } - let idElement = xml.get( + const idElement = xml.get( "/soap-env:Envelope/soap-env:Header/cwmp:ID", NAMESPACES[rpc.cwmpVersion] ); diff --git a/lib/versioned-map.js b/lib/versioned-map.js index ac07cd6..6376925 100644 --- a/lib/versioned-map.js +++ b/lib/versioned-map.js @@ -142,7 +142,7 @@ class VersionedMap { var res = {}; - for (let i in v) { + for (const i in v) { if (v[i] === NONEXISTENT) res.delete |= 1 << i; else res[i] = v[i]; } @@ -154,11 +154,11 @@ class VersionedMap { var del = 0; var rev = []; var minKey = 999; - for (let k in revisions) { + for (const k in revisions) { if (k === "delete") { del = revisions[k]; } else { - let r = parseInt(k); + const r = parseInt(k); minKey = Math.min(minKey, r); for (let i = this._sizeDiff.length; i <= r; ++i) this._sizeDiff[i] = this._sizeDiff[i - 1]; @@ -195,8 +195,8 @@ class VersionedMap { } *diff() { - for (let pair of this.map) { - let current = pair[1][pair[1].length - 1]; + for (const pair of this.map) { + const current = pair[1][pair[1].length - 1]; if (current === NONEXISTENT) { if (0 in pair[1]) yield [pair[0], pair[1][0]]; else yield [pair[0]]; @@ -216,14 +216,14 @@ class VersionedMap { this._sizeDiff[revision] = this._sizeDiff[this._sizeDiff.length - 1]; this._sizeDiff.splice(revision + 1, this._sizeDiff.length); - let d = this.dirty >> revision; + const d = this.dirty >> revision; this.dirty = this.dirty ^ (d << revision); this.dirty |= +!!d << revision; - for (let pair of this.map) { - let k = pair[0]; - let v = pair[1]; - let last = v[v.length - 1]; + for (const pair of this.map) { + const k = pair[0]; + const v = pair[1]; + const last = v[v.length - 1]; if (last === NONEXISTENT) { v.splice(revision, v.length); if (v.some(() => true)) v[revision] = NONEXISTENT;