Skip to content
代码片段 群组 项目
提交 b75c365e 编辑于 作者: Timotej Ecimovic's avatar Timotej Ecimovic
浏览文件

Post snapshot of the zap tool.

上级 947bd858
No related branches found
No related tags found
无相关合并请求
显示
25656 个添加0 个删除
//Usage 'node ./license-check.js --production'
var fs = require('fs');
var checker = require('./node_modules/license-checker/lib/index');
var args = require('./node_modules/license-checker/lib/args').parse();
var whiteList = fs.readFileSync('license-whitelist.txt').toString().split('\n');
var fail = false;
checker.init(args, function(err, json) {
for (x in json) {
var license = json[x].licenses;
if (!x.includes("zap@") && !whiteList.includes(license.toString())) {
console.log("New License Found for module: " + x + " license:\"" + json[x].licenses +'"');
fail = true;
}
}
if (fail) {
console.log("License check FAILED");
} else {
console.log("License check SUCCESS");
}
});
BSD-2-Clause
CC-BY-3.0
Apache-2.0
BSD-3-Clause
CC0-1.0
ISC
MIT
Unlicense
AFLv2.1,BSD
(BSD-2-Clause OR MIT OR Apache-2.0)
(MIT AND CC-BY-3.0)
MIT*
(WTFPL OR MIT)
WTFPL OR ISC
WTFPL
(MIT OR CC0-1.0)
\ No newline at end of file
此差异已折叠。
{
"name": "zap",
"version": "0.99.1",
"description": "Configuration tool for the Zigbee Cluster Library",
"productName": "zap",
"cordovaId": "",
"capacitorId": "",
"author": "Timotej Ecimovic <timotej.ecimovic@silabs.com>",
"private": true,
"scripts": {
"lic": "node license-check.js --production",
"lint": "eslint --ext .js,.vue src",
"electron-dev": "quasar dev -m electron",
"electron-build": "quasar build -m electron",
"test": "jest --updateSnapshot",
"test:unit": "jest --updateSnapshot",
"test:unit:verbose": "jest --updateSnapshot --verbose false",
"test:unit:coverage": "jest --coverage",
"test:unit:watch": "jest --watch",
"test:unit:watchAll": "jest --watchAll",
"serve:test:coverage": "quasar serve test/jest/coverage/lcov-report/ --port 8788",
"concurrently:dev:jest": "concurrently \"quasar dev\" \"jest --watch\"",
"postinstall": "electron-builder install-app-deps",
"zcl-validate": "zcl/script/validate",
"zcl-format": "zcl/script/format",
"headlessServer": "quasar dev -m electron -- --httpPort 8081 --noUI --xmlRoot=./zcl/zcl-studio.properties",
"browser": "quasar dev",
"zap": "quasar build && quasar dev -m electron",
"build-spa": "quasar build",
"doc": "jsdoc src-electron -r -d ./generated-html/",
"apidoc": "jsdoc2md src-electron/**/*.js > docs/api.md"
},
"dependencies": {
"@quasar/extras": "^1.5.2",
"axios": "^0.18.1",
"body-parser": "^1.19.0",
"crc": "^3.8.0",
"electron-builder": "^20.44.4",
"express": "^4.17.1",
"express-session": "^1.17.0",
"node-abi": "^2.15.0",
"node-gyp": "^6.1.0",
"node-pre-gyp": "^0.14.0",
"pino": "^5.16.0",
"properties": "^1.2.1",
"quasar": "^1.9.3",
"sqlite3": "^4.1.1",
"xml2js": "^0.4.23",
"yargs": "^15.1.0"
},
"devDependencies": {
"@quasar/app": "^1.5.8",
"@quasar/quasar-app-extension-testing": "^1.0.0",
"@quasar/quasar-app-extension-testing-unit-jest": "^1.0.0",
"@vue/eslint-config-standard": "^4.0.0",
"babel-eslint": "^10.0.1",
"devtron": "^1.4.0",
"electron": "^8.2.0",
"electron-debug": "^3.0.1",
"electron-devtools-installer": "^2.2.4",
"electron-packager": "^14.2.1",
"electron-rebuild": "^1.10.0",
"eslint": "^5.10.0",
"eslint-loader": "^2.1.1",
"eslint-plugin-vue": "^5.0.0",
"file-loader": "^5.1.0",
"jsdoc": "^3.6.3",
"jsdoc-to-markdown": "^5.0.3",
"license-checker": "^25.0.1"
},
"engines": {
"node": ">= 8.9.0",
"npm": ">= 5.6.0",
"yarn": ">= 1.6.0"
},
"browserslist": [
"last 1 version, not dead, ie >= 11"
]
}
// Configuration for your app
// https://quasar.dev/quasar-cli/quasar-conf-js
module.exports = function (ctx) {
return {
// Source files of application
sourceFiles: {
rootComponent: 'src/App.vue',
router: 'src/router',
store: 'src/store',
indexHtmlTemplate: 'src/index.template.html',
registerServiceWorker: 'src-pwa/register-service-worker.js',
serviceWorker: 'src-pwa/custom-service-worker.js',
electronMainDev: 'src-electron/main-process/electron-main.dev.js',
electronMainProd: 'src-electron/main-process/electron-main.js'
},
// app boot file (/src/boot)
// --> boot files are part of "main.js"
// https://quasar.dev/quasar-cli/cli-documentation/boot-files
boot: ['axios'],
// https://quasar.dev/quasar-cli/quasar-conf-js#Property%3A-css
css: [
'app.sass'
],
// https://github.com/quasarframework/quasar/tree/dev/extras
extras: [
// 'ionicons-v4',
'mdi-v4',
// 'fontawesome-v5',
// 'eva-icons',
// 'themify',
// 'roboto-font-latin-ext', // this or either 'roboto-font', NEVER both!
'roboto-font', // optional, you are not bound to it
'material-icons' // optional, you are not bound to it
],
// https://quasar.dev/quasar-cli/quasar-conf-js#Property%3A-framework
framework: {
iconSet: 'mdi-v4', // Quasar icon set
lang: 'en-us', // Quasar language pack
// Possible values for "all":
// * 'auto' - Auto-import needed Quasar components & directives
// (slightly higher compile time; next to minimum bundle size; most convenient)
// * false - Manually specify what to import
// (fastest compile time; minimum bundle size; most tedious)
// * true - Import everything from Quasar
// (not treeshaking Quasar; biggest bundle size; convenient)
all: 'auto',
components: [],
directives: [],
// Quasar plugins
plugins: []
},
// https://quasar.dev/quasar-cli/cli-documentation/supporting-ie
supportIE: false,
// Full list of options: https://quasar.dev/quasar-cli/quasar-conf-js#Property%3A-build
build: {
scopeHoisting: true,
vueRouterMode: 'hash', // available values: 'hash', 'history'
showProgress: true,
gzip: false,
analyze: false,
// Options below are automatically set depending on the env, set them if you want to override
// preloadChunks: false,
// extractCSS: false,
// https://quasar.dev/quasar-cli/cli-documentation/handling-webpack
extendWebpack(cfg) {
cfg.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /node_modules/,
options: {
formatter: require('eslint').CLIEngine.getFormatter('stylish')
}
})
cfg.module.rules.push({
enforce: 'pre',
test: /\.(sql)$/,
loader: 'file-loader',
exclude: /node_modules/,
options: {
name: '[path][name].[ext]',
},
})
}
},
// Full list of options: https://quasar.dev/quasar-cli/quasar-conf-js#Property%3A-devServer
devServer: {
https: false,
port: 8080,
open: true // opens browser window automatically
},
// animations: 'all', // --- includes all animations
// https://quasar.dev/options/animations
animations: [],
// https://quasar.dev/quasar-cli/developing-ssr/configuring-ssr
ssr: {
pwa: false
},
// https://quasar.dev/quasar-cli/developing-pwa/configuring-pwa
pwa: {
workboxPluginMode: 'GenerateSW', // 'GenerateSW' or 'InjectManifest'
workboxOptions: {}, // only for GenerateSW
manifest: {
name: 'zap',
short_name: 'zap',
description: 'Configuration tool for the Zigbee Cluster Library',
display: 'standalone',
orientation: 'portrait',
background_color: '#ffffff',
theme_color: '#027be3',
icons: [
{
'src': 'statics/icons/icon-128x128.png',
'sizes': '128x128',
'type': 'image/png'
},
{
'src': 'statics/icons/icon-192x192.png',
'sizes': '192x192',
'type': 'image/png'
},
{
'src': 'statics/icons/icon-256x256.png',
'sizes': '256x256',
'type': 'image/png'
},
{
'src': 'statics/icons/icon-384x384.png',
'sizes': '384x384',
'type': 'image/png'
},
{
'src': 'statics/icons/icon-512x512.png',
'sizes': '512x512',
'type': 'image/png'
}
]
}
},
// Full list of options: https://quasar.dev/quasar-cli/developing-cordova-apps/configuring-cordova
cordova: {
// noIosLegacyBuildFlag: true, // uncomment only if you know what you are doing
id: ''
},
// Full list of options: https://quasar.dev/quasar-cli/developing-capacitor-apps/configuring-capacitor
capacitor: {
hideSplashscreen: true
},
// Full list of options: https://quasar.dev/quasar-cli/developing-electron-apps/configuring-electron
electron: {
bundler: 'packager', // 'packager' or 'builder'
packager: {
// https://github.com/electron-userland/electron-packager/blob/master/docs/api.md#options
asar: false,
// OS X / Mac App Store
// appBundleId: '',
// appCategoryType: '',
// osxSign: '',
// protocol: 'myapp://path',
// Windows only
// win32metadata: { ... }
platform: 'darwin,linux,win32',
arch: 'ia32,x64',
extraResource: 'src-electron/db/zap-schema.sql',
afterCopy: [(buildPath, electronVersion, platform, arch, callback) => {
require('electron-rebuild').rebuild({ buildPath, electronVersion, arch })
.then(() => callback())
.catch((error) => callback(error));
}]
},
builder: {
// https://www.electron.build/configuration/configuration
appId: 'zap'
},
// keep in sync with electron-main
// > BrowserWindow > webPreferences > nodeIntegration
// More info: https://quasar.dev/quasar-cli/developing-electron-apps/node-integration
nodeIntegration: false,
extendWebpack(cfg) {
// do something with Electron main process Webpack cfg
// chainWebpack also available besides this extendWebpack
cfg.module.rules.push({
enforce: 'pre',
test: /\.(png|jpe?g|gif|sql)$/,
loader: 'file-loader',
exclude: /node_modules/,
options: {
name: '[path][name].[ext]',
},
})
}
}
}
}
{
"@quasar/testing": {
"harnesses": [
"unit-jest"
]
},
"@quasar/testing-unit-jest": {
"babel": "babelrc",
"options": [
"scripts"
]
}
}
\ No newline at end of file
{
"unit-jest": {
"runnerCommand": "jest"
}
}
\ No newline at end of file
// Copyright (c) 2020 Silicon Labs. All rights reserved.
/**
* This module provides generic DB functions for performing SQL queries.
*
* @module JS API: low level database access
*/
import { logError, logInfo } from '../main-process/env.js'
var sq = require('sqlite3')
var fs = require('fs')
/**
* Returns a promise to begin a transaction
*
* @export
* @param {*} db
* @returns A promise that resolves without an argument and rejects with an error from BEGIN TRANSACTION query.
*/
export function dbBeginTransaction(db) {
return new Promise((resolve, reject) => {
db.run("BEGIN TRANSACTION", [], function (err) {
if (err) {
logError('Failed to BEGIN TRANSACTION')
reject(err)
} else {
logInfo('Executed BEGIN TRANSACTION')
resolve()
}
})
})
}
/**
* Returns a promise to execute a commit.
*
* @export
* @param {*} db
* @returns A promise that resolves without an argument or rejects with an error from COMMIT query.
*/
export function dbCommit(db) {
return new Promise((resolve, reject) => {
db.run("COMMIT", [], function (err) {
if (err) {
logError('Failed to COMMIT')
reject(err)
} else {
logInfo('Executed COMMIT')
resolve()
}
})
})
}
/**
* Returns a promise to execute a DELETE FROM query.
*
* @export
* @param {*} db
* @param {*} query
* @param {*} args
* @returns A promise that resolve with the number of delete rows, or rejects with an error from query.
*/
export function dbRemove(db, query, args) {
return new Promise((resolve,reject) => {
db.run(query, args, function (err) {
if (err) {
logError(`Failed remove: ${query}: ${args}`)
reject(err)
} else {
logInfo(`Executed remove: ${query}: ${args}`)
resolve(this.changes)
}
})
})
}
/**
* Returns a promise to execute an update query.
*
* @export
* @param {*} db
* @param {*} query
* @param {*} args
* @returns A promise that resolves without an argument, or rejects with an error from the query.
*/
export function dbUpdate(db, query, args) {
return new Promise((resolve, reject) => {
db.run(query, args, function (err) {
if (err) {
logError(`Failed update: ${query}: ${args}`)
reject(err)
} else {
logInfo(`Executed update: ${query}: ${args}`)
resolve()
}
})
})
}
/**
* Returns a promise to execute an insert query.
*
* @export
* @param {*} db
* @param {*} query
* @param {*} args
* @returns A promise that resolves with the rowid from the inserted row, or rejects with an error from the query.
*/
export function dbInsert(db, query, args) {
return new Promise((resolve, reject) => {
db.run(query, args, function (err) {
if (err) {
logError(`Failed insert: ${query}: ${args}`)
reject(err)
} else {
logInfo(`Executed insert: ${query}: ${args} => rowid: ${this.lastID}`)
resolve(this.lastID)
}
})
})
}
/**
* Returns a promise to execute a query to perform a select that returns all rows that match a query.
*
* @export
* @param {*} db
* @param {*} query
* @param {*} args
* @returns A promise that resolves with the rows that got retrieved from the database, or rejects with an error from the query.
*/
export function dbAll(db, query, args) {
return new Promise((resolve, reject) => {
db.all(query, args, (err, rows) => {
if (err) {
logInfo(`Failed all: ${query}: ${args}`)
reject(err)
} else {
logInfo(`Executed all: ${query}: ${args}`)
resolve(rows)
}
})
})
}
/**
* Returns a promise to execute a query to perform a select that returns first row that matches a query.
*
* @export
* @param {*} db
* @param {*} query
* @param {*} args
* @returns A promise that resolves with a single row that got retrieved from the database, or rejects with an error from the query.
*/
export function dbGet(db, query, args) {
return new Promise((resolve, reject) => {
db.get(query, args, (err, row) => {
if (err) {
logError(`Failed get: ${query}: ${args}`)
reject(err)
} else {
logInfo(`Executed get: ${query}: ${args}`)
resolve(row)
}
})
})
}
/**
* Returns a promise to perfom a prepared statement, using data from array for SQL parameters.
* It resolves with an array of rowids, or rejects with an error.
*
* @export
* @param {*} db
* @param {*} sql
* @param {*} arrayOfArrays
* @returns A promise that resolves with the array of rowids for the rows that got inserted, or rejects with an error from the query.
*/
export function dbMultiInsert(db, sql, arrayOfArrays) {
return new Promise((resolve, reject) => {
logInfo(`Preparing statement: ${sql} to insert ${arrayOfArrays.length} records.`)
var lastIds = []
var statement = db.prepare(sql, function (err) {
if (err) reject(err)
for (const singleArray of arrayOfArrays) {
statement.run(singleArray, (err) => {
if (err) reject(err)
lastIds.push(this.lastID)
})
}
statement.finalize((err) => {
if (err) reject(err)
resolve(lastIds)
})
})
})
}
/**
* Returns a promise that will resolve when the database in question is closed.
* Rejects with an error if closing fails.
*
* @export
* @param {*} database
* @returns A promise that resolves without an argument or rejects with error from the database closing.
*/
export function closeDatabase(database) {
return new Promise((resolve, reject) => {
database.close((err) => {
if (err) return reject(err)
resolve()
})
})
}
/**
* Returns a promise to initialize a database.
*
* @export
* @param {*} sqlitePath
* @returns A promise that resolves with the database object that got created, or rejects with an error if something went wrong.
*/
export function initDatabase(sqlitePath) {
return new Promise((resolve, reject) => {
logInfo('Temporarily, we are forcibly deleting the sqlite file every time we start up the app. This goes away after a while, obviously.')
if (fs.existsSync(sqlitePath)) {
fs.unlinkSync(sqlitePath)
}
var db = new sq.Database(sqlitePath,
(err) => {
if (err) {
return reject(err)
} else {
logInfo(`Connected to the database at: ${sqlitePath}`)
resolve(db)
}
}
)
})
}
/**
* Returns a promise to insert or replace a version of the application into the database.
*
* @param {*} db
* @param {*} version
* @returns A promise that resolves with a rowid of created setting row or rejects with error if something goes wrong.
*/
function insertOrReplaceVersion(db, version) {
return dbInsert(db, "INSERT OR REPLACE INTO SETTING ( CATEGORY, KEY, VALUE ) VALUES ( 'APP', 'VERSION', ?)", version)
}
/**
* Returns a promise to load schema into a blank database, and inserts a version to the settings table.j
*
* @export
* @param {*} db
* @param {*} schema
* @param {*} appVersion
* @returns A promise that resolves with the same db that got passed in, or rejects with an error.
*/
export function loadSchema(db, schema, appVersion) {
return new Promise((resolve, reject) => {
fs.readFile(schema, 'utf8', (err, data) => {
if (err) return reject(err)
db.serialize(() => {
logInfo('Populate schema.')
db.exec(data, (err) => {
if (err) {
logError('Failed to populate schema')
logError(err)
}
resolve(db)
})
})
});
})
.then(db => insertOrReplaceVersion(db, appVersion))
.then(rowid => Promise.resolve(db))
}
\ No newline at end of file
// Copyright (c) 2020 Silicon Labs. All rights reserved.
/**
* Contains all the application queries.
*
* @module JS API: database queries
*/
import { dbAll, dbGet, dbInsert, dbMultiInsert, dbRemove, dbUpdate } from './db-api.js'
export function forPathCrc(db, path, crcCallback, noneCallback) {
dbGet(db, "SELECT PACKAGE_ID, PATH, CRC FROM PACKAGE WHERE PATH = ?", [path]).then(row => {
if (row == null) {
noneCallback()
} else {
crcCallback(row.CRC, row.PACKAGE_ID)
}
})
}
export function getPathCrc(db, path) {
return dbGet(db, "SELECT CRC FROM PACKAGE WHERE PATH = ?", [path]).then(row => new Promise((resolve, reject) => {
if (row == null) {
resolve(null)
} else {
resolve(row.CRC)
}
}))
}
export function insertPathCrc(db, path, crc) {
return dbInsert(db, "INSERT INTO PACKAGE ( PATH, CRC ) VALUES (?, ?)", [path, crc])
}
export function updatePathCrc(db, path, crc) {
return dbInsert(db, "UPDATE PACKAGE SET CRC = ? WHERE PATH = ?", [path, crc])
}
export function selectAllEnums(db) {
return dbAll(db, 'SELECT ENUM_ID, NAME, TYPE FROM ENUM ORDER BY NAME', [])
}
export function selectAllEnumItemsById(db, id) {
return dbAll(db, 'SELECT NAME FROM ENUM_ITEM WHERE ENUM_REF=?', [id]);
}
export function selectAllEnumItems(db) {
return dbAll(db, 'SELECT NAME, VALUE, ENUM_REF FROM ENUM_ITEM ORDER BY ENUM_REF', []);
}
export function selectEnumById(db, id) {
return dbGet(db, 'SELECT ENUM_ID, NAME, TYPE FROM ENUM WHERE ENUM_ID = ? ORDER BY NAME', [id])
}
export function selectAllBitmaps(db) {
return dbAll(db, 'SELECT BITMAP_ID, NAME, TYPE FROM BITMAP ORDER BY NAME', [])
}
export function selectAllBitmapFields(db) {
return dbAll(db, 'SELECT NAME, MASK, BITMAP_REF FROM BITMAP_FIELD ORDER BY NAME', [])
}
export function selectBitmapById(db, id) {
return dbGet(db, 'SELECT BITMAP_ID, NAME, TYPE FROM BITMAP WHERE BITMAP_ID = ? ORDER BY NAME', [id])
}
export function selectAllDomains(db) {
return dbAll(db, 'SELECT DOMAIN_ID, NAME FROM DOMAIN ORDER BY NAME', [])
}
export function selectDomainById(db, id) {
return dbGet(db, 'SELECT DOMAIN_ID, NAME FROM DOMAIN WHERE DOMAIN_ID = ? ORDER BY NAME', [id])
}
export function selectAllStructs(db) {
return dbAll(db, 'SELECT STRUCT_ID, NAME FROM STRUCT ORDER BY NAME', [])
}
export function selectStructById(db, id) {
return dbGet(db, 'SELECT STRUCT_ID, NAME FROM STRUCT WHERE STRUCT_ID = ? ORDER BY NAME', [id])
}
export function selectAllClusters(db) {
return dbAll(db, 'SELECT CLUSTER_ID, CODE, MANUFACTURER_CODE, NAME, DESCRIPTION, DEFINE FROM CLUSTER ORDER BY CODE', [])
}
export function selectClusterById(db, id) {
return dbGet(db, 'SELECT CLUSTER_ID, CODE, MANUFACTURER_CODE, NAME, DESCRIPTION FROM CLUSTER WHERE CLUSTER_ID = ?', [id])
}
export function selectAllDeviceTypes(db) {
return dbAll(db, 'SELECT DEVICE_TYPE_ID, CODE, PROFILE_ID, NAME, DESCRIPTION FROM DEVICE_TYPE ORDER BY CODE', [])
}
export function selectDeviceTypeById(db, id) {
return dbGet(db, 'SELECT DEVICE_TYPE_ID, CODE, PROFILE_ID, NAME, DESCRIPTION FROM DEVICE_TYPE WHERE DEVICE_TYPE_ID = ?', [id])
}
export function selectCountFrom(db, table) {
return dbGet(db, `SELECT COUNT(*) FROM ${table}`).then(x => x['COUNT(*)'])
}
export function selectAttributesByClusterId(db, clusterId) {
return dbAll(db, `SELECT ATTRIBUTE_ID, CLUSTER_REF, CODE, MANUFACTURER_CODE, NAME, TYPE, SIDE, DEFINE, MIN, MAX, IS_WRITABLE, DEFAULT_VALUE, IS_OPTIONAL FROM ATTRIBUTE WHERE CLUSTER_REF = ? ORDER BY CODE`, [clusterId])
}
export function selectCommandsByClusterId(db, clusterId) {
return dbAll(db, `SELECT COMMAND_ID, CLUSTER_REF, CODE, MANUFACTURER_CODE, NAME, DESCRIPTION, SOURCE, IS_OPTIONAL FROM COMMAND WHERE CLUSTER_REF = ? ORDER BY CODE`, [clusterId])
}
// Inserts clusters into the database.
// data is an array of objects that must contain: code, name, description, define
// It also contains commands: and attributes:
//
export function insertClusters(db, packageId, data) {
return dbMultiInsert(db, "INSERT INTO CLUSTER (PACKAGE_REF, CODE, NAME, DESCRIPTION, DEFINE) VALUES (?, ?, ?, ?, ?)", data.map(cluster => [packageId, cluster.code, cluster.name, cluster.description, cluster.define]))
.then(lastIdsArray => {
var commandsToLoad = []
var attributesToLoad = []
var argsForCommands = []
var argsToLoad = []
var i
for (i = 0; i < lastIdsArray.length; i++) {
var lastId = lastIdsArray[i]
if ('commands' in data[i]) {
var commands = data[i].commands
commandsToLoad.push(...commands.map(command => [lastId, command.code, command.name, command.description, command.source, command.isOptional]))
argsForCommands.push(...commands.map(command => command.args))
}
if ('attributes' in data[i]) {
var attributes = data[i].attributes
attributesToLoad.push(...attributes.map(attribute => [
lastId,
attribute.code,
attribute.name,
attribute.type,
attribute.side,
attribute.define,
attribute.min,
attribute.max,
attribute.isWritable,
attribute.defaultValue,
attribute.isOptional
]))
}
}
var pCommand = dbMultiInsert(db,
"INSERT INTO COMMAND (CLUSTER_REF, CODE, NAME, DESCRIPTION, SOURCE, IS_OPTIONAL) VALUES (?,?,?,?,?,?)",
commandsToLoad).then(lids => {
var i
for (i = 0; i < lids.length; i++) {
var lastId = lids[i]
var args = argsForCommands[i]
if (args != undefined && args != null) {
argsToLoad.push(...args.map(arg => [lastId, arg.name, arg.type, arg.isArray]))
}
}
return dbMultiInsert(db,
"INSERT INTO COMMAND_ARG (COMMAND_REF, NAME, TYPE, IS_ARRAY) VALUES (?,?,?,?)",
argsToLoad)
})
var pAttribute = dbMultiInsert(db,
"INSERT INTO ATTRIBUTE (CLUSTER_REF, CODE, NAME, TYPE, SIDE, DEFINE, MIN, MAX, IS_WRITABLE, DEFAULT_VALUE, IS_OPTIONAL) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
attributesToLoad)
return Promise.all([pCommand, pAttribute])
})
}
// Inserts device types into the database.
// data is an array of objects that must contain: code, name, description
export function insertDeviceTypes(db, packageId, data) {
return dbMultiInsert(db, "INSERT INTO DEVICE_TYPE (PACKAGE_REF, CODE, PROFILE_ID, NAME, DESCRIPTION) VALUES (?, ?, ?, ?, ?)", data.map(dt => {
return [packageId, dt.code, dt.profileId, dt.name, dt.description]
})).then(lastIdsArray => {
var i
var itemsToLoad = []
for (i = 0; i < lastIdsArray.length; i++) {
if ('clusters' in data[i]) {
var lastId = lastIdsArray[i]
var clusters = data[i].clusters
itemsToLoad.push(...clusters.map(cluster => [lastId, cluster.clusterName, cluster.client, cluster.server, cluster.clientLocked, cluster.serverLocked]))
}
}
return dbMultiInsert(db,
'INSERT INTO DEVICE_TYPE_CLUSTER (DEVICE_TYPE_REF, CLUSTER_NAME, INCLUDE_CLIENT, INCLUDE_SERVER, LOCK_CLIENT, LOCK_SERVER) VALUES (?,?,?,?,?,?)',
itemsToLoad)
})
}
export function updateClusterReferencesForDeviceTypeClusters(db) {
return dbUpdate(db, 'UPDATE DEVICE_TYPE_CLUSTER SET CLUSTER_REF = (SELECT CLUSTER.CLUSTER_ID FROM CLUSTER WHERE CLUSTER.NAME = DEVICE_TYPE_CLUSTER.CLUSTER_NAME)', [])
}
/**
*
* Inserts domains into the database.
* data is an array of objects that must contain: name
*
* @export
* @param {*} db
* @param {*} packageId
* @param {*} data
* @returns A promise that resolves with an array of rowids of all inserted domains.
*/
export function insertDomains(db, packageId, data) {
return dbMultiInsert(db, "INSERT INTO DOMAIN (PACKAGE_REF, NAME) VALUES (?, ?)", data.map(domain => {
return [packageId, domain.name]
}))
}
/**
*
* Inserts structs into the database.
* data is an array of objects that must contain: name
*
* @export
* @param {*} db
* @param {*} packageId
* @param {*} data
* @returns A promise that resolves with an array of struct item rowids.
*/
export function insertStructs(db, packageId, data) {
return dbMultiInsert(db, "INSERT INTO STRUCT (PACKAGE_REF, NAME) VALUES (?, ?)", data.map(struct => {
return [packageId, struct.name]
})).then(lastIdsArray => {
var i
var itemsToLoad = []
for (i = 0; i < lastIdsArray.length; i++) {
if ('items' in data[i]) {
var lastId = lastIdsArray[i]
var items = data[i].items
itemsToLoad.push(...items.map(item => [lastId, item.name, item.type]))
}
}
return dbMultiInsert(db,
"INSERT INTO STRUCT_ITEM (STRUCT_REF, NAME, TYPE) VALUES (?,?,?)",
itemsToLoad)
})
}
// Inserts enums into the database.
// data is an array of objects that must contain: name, type
export function insertEnums(db, packageId, data) {
return dbMultiInsert(db, "INSERT INTO ENUM (PACKAGE_REF, NAME, TYPE) VALUES (?, ?, ?)", data.map(en => {
return [packageId, en.name, en.type]
})).then(lastIdsArray => {
var i
var itemsToLoad = []
for (i = 0; i < lastIdsArray.length; i++) {
if ('items' in data[i]) {
var lastId = lastIdsArray[i]
var items = data[i].items
itemsToLoad.push(...items.map(item => [lastId, item.name, item.value]))
}
}
return dbMultiInsert(db,
"INSERT INTO ENUM_ITEM (ENUM_REF, NAME, VALUE) VALUES (?, ?, ?)",
itemsToLoad)
})
}
/**
* Inserts bitmaps into the database. Data is an array of objects that must contain: name, type
*
* @export
* @param {*} db
* @param {*} packageId
* @param {*} data Array of object containing 'name' and 'type'.
* @returns A promise of bitmap insertions.
*/
export function insertBitmaps(db, packageId, data) {
return dbMultiInsert(db, "INSERT INTO BITMAP (PACKAGE_REF, NAME, TYPE) VALUES (?, ?, ?)", data.map(bm => [packageId, bm.name, bm.type]))
.then(lastIdsArray => {
var i
var fieldsToLoad = []
for (i = 0; i < lastIdsArray.length; i++) {
if ('fields' in data[i]) {
var lastId = lastIdsArray[i]
var fields = data[i].fields
fieldsToLoad.push(...fields.map(field => [lastId, field.name, field.mask]))
}
}
return dbMultiInsert(db,
"INSERT INTO BITMAP_FIELD (BITMAP_REF, NAME, MASK) VALUES (?, ?, ?)",
fieldsToLoad)
})
}
/************************** SESSION QUERIES *************************************/
/**
* Promises to delete a session from the database, including all the rows that have the session as a foreign key.
*
* @export
* @param {*} db
* @param {*} sessionId
* @returns A promise of a removal of session.
*/
export function deleteSession(db, sessionId) {
return dbRemove(db, "DELETE FROM SESSION WHERE SESSION_ID = ?", [sessionId])
}
/**
* Promises to update or insert a key/value pair in SESSION_KEY_VALUE table.
*
* @export
* @param {*} db
* @param {*} sessionId
* @param {*} key
* @param {*} value
* @returns A promise of creating or updating a row, resolves with the rowid of a new row.
*/
export function updateKeyValue(db, sessionId, key, value) {
return dbInsert(db, "INSERT OR REPLACE INTO SESSION_KEY_VALUE (SESSION_REF, KEY, VALUE) VALUES (?,?,?)", [sessionId, key, value])
}
/**
* Promises to update the cluster include/exclude state.
*
* @export
* @param {*} db
* @param {*} endpointTypeId
* @param {*} clusterId
* @param {*} side
* @param {*} enabled
* @returns Promise to update the cluster exclude/include state.
*/
export function insertOrReplaceClusterState(db, endpointTypeId, clusterId, side, enabled) {
return dbInsert(db, "INSERT OR REPLACE INTO ENDPOINT_TYPE_CLUSTER ( ENDPOINT_TYPE_REF, CLUSTER_REF, SIDE, ENABLED ) VALUES ( ?, ?, ?, ?)", [endpointTypeId, clusterId, side, enabled])
}
/*
Resolves into all the cluster states.
*/
export function getAllEndpointTypeClusterState(db, endpointTypeId) {
return dbAll(db, "SELECT CLUSTER.NAME, CLUSTER.CODE, CLUSTER.MANUFACTURER_CODE, ENDPOINT_TYPE_CLUSTER.SIDE, ENDPOINT_TYPE_CLUSTER.ENABLED FROM ENDPOINT_TYPE_CLUSTER INNER JOIN CLUSTER WHERE ENDPOINT_TYPE_CLUSTER.CLUSTER_REF = CLUSTER.CLUSTER_ID AND ENDPOINT_TYPE_CLUSTER.ENDPOINT_TYPE_REF = ?", [endpointTypeId])
.then((rows) => new Promise((resolve, reject) => {
if (rows == null) {
resolve([])
} else {
var result = rows.map(row => {
var obj = {
clusterName: row.NAME,
clusterCode: row.CODE,
side: row.SIDE,
enabled: (row.STATE == '1')
}
if (row.MANUFACTURER_CODE != null)
obj.manufacturerCode = row.MANUFACTURER_CODE;
return obj
})
resolve(result)
}
}))
}
/**
* Promises to add an endpoint.
*
* @export
* @param {*} db
* @param {*} sessionId
* @param {*} endpointId
* @param {*} endpointTypeRef
* @param {*} networkId
* @returns Promise to update endpoints.
*/
export function insertEndpoint(db, sessionId, endpointId, endpointTypeRef, networkId) {
return dbInsert(db, "INSERT OR REPLACE INTO ENDPOINT ( SESSION_REF, ENDPOINT_ID, ENDPOINT_TYPE_REF, NETWORK_ID ) VALUES ( ?, ?, ?, ?)", [sessionId, endpointId, endpointTypeRef, networkId])
}
/**
* Deletes an endpoint.
*
* @export
* @param {*} db
* @param {*} id
* @returns Promise to delete an endpoint that resolves with the number of rows that were deleted.
*/
export function deleteEndpoint(db, id) {
return dbRemove(db, "DELETE FROM ENDPOINT WHERE ENDPOINT_REF = ?", [id])
}
/**
* Promises to add an endpoint type.
*
* @export
* @param {*} db
* @param {*} sessionId
* @param {*} name
* @param {*} deviceTypeRef
* @returns Promise to update endpoints.
*/
export function insertEndpointType(db, sessionId, name, deviceTypeRef) {
return dbInsert(db, "INSERT OR REPLACE INTO ENDPOINT_TYPE ( SESSION_REF, NAME, DEVICE_TYPE_REF ) VALUES ( ?, ?, ?)", [sessionId, name, deviceTypeRef])
}
/**
* Promise to delete an endpoint type.
* @param {*} db
* @param {*} sessionId
* @param {*} id
*/
export function deleteEndpointType(db, id) {
return dbRemove(db, "DELETE FROM ENDPOINT_TYPE WHERE ENDPOINT_TYPE_ID = ?", [id])
}
/**
* Resolves to an array of objects that contain 'key' and 'value'
*
* @export
* @param {*} db
* @param {*} sessionId
* @returns Promise to retrieve all session key values.
*/
export function getAllSesionKeyValues(db, sessionId) {
return dbAll(db, "SELECT KEY, VALUE FROM SESSION_KEY_VALUE WHERE SESSION_REF = ? ORDER BY KEY", [sessionId])
.then((rows) => new Promise((resolve, reject) => {
if (rows == null) {
resolve([])
} else {
var result = rows.map(row => {
return {
key: row.KEY,
value: row.VALUE
}
})
resolve(result)
}
}))
}
/**
* Resolves to an array of endpoint types.
*
* @export
* @param {*} db
* @param {*} sessionId
* @returns Promise to retrieve all endpoint types.
*/
export function getAllEndpointTypes(db, sessionId) {
return dbAll(db, "SELECT NAME, DEVICE_TYPE_REF FROM ENDPOINT_TYPE WHERE SESSION_REF = ? ORDER BY NAME", [sessionId])
.then((rows) => new Promise((resolve, reject) => {
if (rows == null) {
resolve([])
} else {
var result = rows.map(rows => {
return {
name: row.NAME
}
})
resolve(result)
}
}))
}
/**
* Returns a promise that resolves into an array of objects containing 'sessionId', 'sessionKey' and 'creationTime'.
*
* @export
* @param {*} db
* @returns A promise of executing a query.
*/
export function getAllSessions(db) {
return dbAll(db, "SELECT SESSION_ID, SESSION_KEY, CREATION_TIME FROM SESSION", [])
.then(rows => {
if (rows == null) {
reject()
} else {
var map = rows.map(row => {
return {
sessionId: row.SESSION_ID,
sessionKey: row.SESSION_KEY,
creationTime: row.CREATION_TIME
}
})
return Promise.resolve(map)
}
})
}
export function setSessionClean(db, sessionId) {
return dbUpdate(db, "UPDATE SESSION SET DIRTY = ? WHERE SESSION_ID = ?", [0, sessionId])
}
/**
* Resolves with true or false, depending whether this session is dirty.
*
* @export
* @param {*} db
* @param {*} sessionId
* @returns A promise that resolves into true or false, reflecting session dirty state.
*/
export function getSessionDirtyFlag(db, sessionId) {
return dbGet(db, "SELECT DIRTY FROM SESSION WHERE SESSION_ID = ?", [sessionId])
.then(row => {
if ( row == null ) {
reject()
} else {
return Promise.resolve(row.DIRTY)
}
})
}
export function getSessionIdFromWindowdId(db, windowId) {
return dbGet(db, "SELECT SESSION_ID, SESSION_KEY, CREATION_TIME FROM SESSION WHERE SESSION_WINID = ?", [windowId])
.then(row => {
if (row == null) {
reject()
} else {
return Promise.resolve({
sessionId: row.SESSION_ID,
sessionKey: row.SESSION_KEY,
creationTime: row.CREATION_TIME
})
}
})
}
export function ensureZapSessionId(db, sessionKey, windowId) {
return dbGet(db, "SELECT SESSION_ID FROM SESSION WHERE SESSION_KEY = ?", [sessionKey])
.then(row => {
if (row == null) {
return dbInsert(db, "INSERT INTO SESSION (SESSION_KEY, SESSION_WINID, CREATION_TIME) VALUES (?,?,?)", [sessionKey, windowId, Date.now()])
} else {
return Promise.resolve(row.SESSION_ID)
}
})
}
/*
PACKAGE table contains the "packages" that are the sources for the
loading of the other data. They may be individual files, or
collection of files.
Table records the CRC at the time loading.
*/
CREATE TABLE IF NOT EXISTS "PACKAGE" (
"PACKAGE_ID" integer primary key autoincrement,
"PATH" text NOT NULL UNIQUE,
"CRC" integer
);
/*
CLUSTER table contains the clusters loaded from the ZCL XML files.
*/
CREATE TABLE IF NOT EXISTS "CLUSTER" (
"CLUSTER_ID" integer primary key autoincrement,
"PACKAGE_REF" integer,
"CODE" integer,
"MANUFACTURER_CODE" integer,
"NAME" text,
"DESCRIPTION" text,
"DEFINE" text,
foreign key (PACKAGE_REF) references PACKAGE(PACKAGE_ID)
);
/*
COMMAND table contains commands contained inside a cluster.
*/
CREATE TABLE IF NOT EXISTS "COMMAND" (
"COMMAND_ID" integer primary key autoincrement,
"CLUSTER_REF" integer,
"CODE" integer,
"MANUFACTURER_CODE" integer,
"NAME" text,
"DESCRIPTION" text,
"SOURCE" text,
"IS_OPTIONAL" integer,
foreign key (CLUSTER_REF) references CLUSTER(CLUSTER_ID)
);
/*
COMMAND_ARG table contains arguments for a command.
*/
CREATE TABLE IF NOT EXISTS "COMMAND_ARG" (
"COMMAND_REF" integer,
"NAME" text,
"TYPE" text,
"IS_ARRAY" integer,
foreign key (COMMAND_REF) references COMMAND(COMMAND_ID)
);
/*
ATTRIBUTE table contains attributes for the cluster.
*/
CREATE TABLE IF NOT EXISTS "ATTRIBUTE" (
"ATTRIBUTE_ID" integer primary key autoincrement,
"CLUSTER_REF" integer,
"CODE" integer,
"MANUFACTURER_CODE" integer,
"NAME" text,
"TYPE" text,
"SIDE" text,
"DEFINE" text,
"MIN" text,
"MAX" text,
"IS_WRITABLE" integer,
"DEFAULT_VALUE" text,
"IS_OPTIONAL" integer,
foreign key (CLUSTER_REF) references CLUSTER(CLUSTER_ID)
);
/*
BITMAP table contains the bitmaps directly loaded from packages.
*/
CREATE TABLE IF NOT EXISTS "BITMAP" (
"BITMAP_ID" integer primary key autoincrement,
"PACKAGE_REF" integer,
"NAME" text,
"TYPE" text,
foreign key (PACKAGE_REF) references PACKAGE(PACKAGE_ID)
);
/*
BITMAP_FIELD contains items that make up a bitmap.
*/
CREATE TABLE IF NOT EXISTS "BITMAP_FIELD" (
"BITMAP_REF" integer,
"NAME" text,
"MASK" integer,
foreign key(BITMAP_REF) references BITMAP(BITMAP_ID)
);
/*
DOMAIN table contains domains directly loaded from packages.
*/
CREATE TABLE IF NOT EXISTS "DOMAIN" (
"DOMAIN_ID" integer primary key autoincrement,
"PACKAGE_REF" integer,
"NAME" text,
foreign key (PACKAGE_REF) references PACKAGE(PACKAGE_ID)
);
/*
ENUM table contains enums directly loaded from packages.
*/
CREATE TABLE IF NOT EXISTS "ENUM" (
"ENUM_ID" integer primary key autoincrement,
"PACKAGE_REF" integer,
"NAME" text,
"TYPE" text,
foreign key (PACKAGE_REF) references PACKAGE(PACKAGE_ID)
);
/*
ENUM_ITEM table contains individual enum items.
*/
CREATE TABLE IF NOT EXISTS "ENUM_ITEM" (
"ENUM_REF" integer,
"NAME" text,
"VALUE" integer,
foreign key (ENUM_REF) references ENUM(ENUM_ID)
);
/*
STRUCT table contains structs directly loaded from packages.
*/
CREATE TABLE IF NOT EXISTS "STRUCT" (
"STRUCT_ID" integer primary key autoincrement,
"PACKAGE_REF" integer,
"NAME" text,
foreign key (PACKAGE_REF) references PACKAGE(PACKAGE_ID)
);
/*
STRUCT_ITEM table contains individual struct items.
*/
CREATE TABLE IF NOT EXISTS "STRUCT_ITEM" (
"STRUCT_REF" integer,
"NAME" text,
"TYPE" text,
foreign key (STRUCT_REF) references STRUCT(STRUCT_ID)
);
/*
DEVICE_TYPE table contains device types directly loaded from packages.
*/
CREATE TABLE IF NOT EXISTS "DEVICE_TYPE" (
"DEVICE_TYPE_ID" integer primary key autoincrement,
"PACKAGE_REF" integer,
"CODE" integer,
"PROFILE_ID" integer,
"NAME" text,
"DESCRIPTION" text,
foreign key (PACKAGE_REF) references PACKAGE(PACKAGE_ID)
);
/*
DEVICE_TYPE_CLUSTER contains clusters that belong to the device type.
*/
CREATE TABLE IF NOT EXISTS "DEVICE_TYPE_CLUSTER" (
"DEVICE_TYPE_REF" integer,
"CLUSTER_REF" integer,
"CLUSTER_NAME" text,
"INCLUDE_CLIENT" integer,
"INCLUDE_SERVER" integer,
"LOCK_CLIENT" integer,
"LOCK_SERVER" integer,
foreign key (DEVICE_TYPE_REF) references DEVICE_TYPE(DEVICE_TYPE_ID),
foreign key (CLUSTER_REF) references CLUSTER(CLUSTER_ID)
);
/*
SESSION table contains the list of known and remembered sessions.
In case of electron SESSION_WINID is the window ID for a given
session.
*/
CREATE TABLE IF NOT EXISTS "SESSION" (
"SESSION_ID" integer primary key autoincrement,
"SESSION_KEY" text,
"SESSION_WINID" text,
"CREATION_TIME" integer,
"DIRTY" integer default 1,
UNIQUE(SESSION_KEY)
);
/*
SESSION_KEY_VALUE table contains the data points that are simple
key/value pairs.
*/
CREATE TABLE IF NOT EXISTS "SESSION_KEY_VALUE" (
"SESSION_REF" integer,
"KEY" text,
"VALUE" text,
foreign key (SESSION_REF) references SESSION(SESSION_ID) on delete cascade
);
/*
ENDPOINT_TYPE contains the bulk of the configuration: clusters, attributes, etc.
*/
CREATE TABLE IF NOT EXISTS "ENDPOINT_TYPE" (
"ENDPOINT_TYPE_ID" integer primary key autoincrement,
"SESSION_REF" integer,
"NAME" text,
"DEVICE_TYPE_REF" integer,
foreign key (SESSION_REF) references SESSION(SESSION_ID) on delete cascade,
foreign key(DEVICE_TYPE_REF) references DEVICE_TYPE(DEVICE_TYPE_ID)
);
/*
ENDPOINT table contains the toplevel configured endpoints.
*/
CREATE TABLE IF NOT EXISTS "ENDPOINT" (
"ENDPOINT_REF" integer primary key autoincrement,
"SESSION_REF" integer,
"ENDPOINT_ID" integer,
"ENDPOINT_TYPE_REF" integer,
"PROFILE" integer,
"NETWORK_ID" integer,
foreign key (SESSION_REF) references SESSION(SESSION_ID) on delete cascade,
foreign key (ENDPOINT_TYPE_REF) references ENDPOINT_TYPE(ENDPOINT_TYPE_ID)
);
/*
SESSION_CLUSTER contains the on/off values for cluster.
SIDE is client or server
STATE is 1 for ON and 0 for OFF.
*/
CREATE TABLE IF NOT EXISTS "ENDPOINT_TYPE_CLUSTER" (
"ENDPOINT_TYPE_REF" integer,
"CLUSTER_REF" integer,
"SIDE" text,
"ENABLED" integer,
foreign key (ENDPOINT_TYPE_REF) references ENDPOINT_TYPE(ENDPOINT_TYPE_ID) on delete cascade,
foreign key (CLUSTER_REF) references CLUSTER(CLUSTER_ID)
);
/*
SETTING table contains site-specific application settings, regardless of a user configuration session.
Essentially application preferences.
*/
CREATE TABLE IF NOT EXISTS "SETTING" (
"CATEGORY" text,
"KEY" text,
"VALUE" text
);
/*
Triggers to maintain "dirty" flag in a session.
*/
\ No newline at end of file
// THIS FEATURE-FLAG FILE IS AUTOGENERATED,
// REMOVAL OR CHANGES WILL CAUSE RELATED TYPES TO STOP WORKING
import "quasar/dist/types/feature-flag";
declare module "quasar/dist/types/feature-flag" {
interface QuasarFeatureFlags {
electron: true;
}
}
/**
* Copyright (c) 2020 Silicon Labs. All rights reserved.
*
* @module JS API: generator logic
*/
import Handlebars from 'handlebars';
var fs = require('fs-extra');
import { selectAllClusters, selectAllEnums, selectAllEnumItems, selectAllBitmaps, selectAllBitmapFields } from "../db/query.js"
/**
* Find the handlebar template file, compile and return the template file.
* In the case of Generate this will take the template directory mentioned.
* However in the case of the browser the templates come from the
* zcl/generation-templates repository.
*
* @param {string} [templateDirectory=""] Directory where the templates reside
* @param {string} [name=""] Name of the template file
* @returns A compiled Template
*/
Handlebars.getTemplate = function(templateDirectory = "", name = "") {
var source = "";
if (templateDirectory) {
source = fs.readFileSync(templateDirectory + '/' + name, 'utf8');
} else {
templateDirectory = __dirname + '/../../zcl/generation-templates';
source = fs.readFileSync(templateDirectory + '/' + name, 'utf8');
}
return Handlebars.compile(source);
};
/**
* Resolve is listed on the map containing the database.
*
* @export
* @param {Object} db database
* @returns A promise with resolve listed on the map
*/
export function mapDatabase(db) {
return new Promise((resolve, reject) => {
var resultantMap = {};
resultantMap.database = db;
resolve(resultantMap);
})
}
/**
* Resolve the handlebar template directory to be able to use the correct
* handlebar templates for generation/preview.
*
* @export
* @param {Object} map HashMap
* @param {string} handlebarTemplateDirectory Handlebar template directory path
* @returns A promise with resolve listed on a map which has the handlebar
* directory.
*/
export function resolveTemplateDirectory(map, handlebarTemplateDirectory="") {
return new Promise((resolve, reject) => {
map.handlebarTemplateDirectory = handlebarTemplateDirectory;
resolve(map);
})
}
/**
* Resolve the compiled handlebar templates for use.
*
* @export
* @param {Object} map Map for database and template directory
* @param {string[]} templateFiles Array of handlebar template files
* @returns A promise with resolve listed on a map which has the compiled
* templates.
*/
export function compileTemplate(map, templateFiles) {
return new Promise((resolve, reject) => {
for (let i=0; i<templateFiles.length; i++) {
var compiledTemplate = Handlebars.getTemplate(map.handlebarTemplateDirectory, templateFiles[i]);
map[templateFiles[i]] = compiledTemplate;
}
resolve(map);
})
}
/**
* The database information is retrieved by calling database query
* functions. Then a resolve is listed on the map containing database, compiled
* template and database row information so that they can be passed on to more
* promises.
*
* @export
* @param {Object} map Map for database, template directory and compiled templates
* @param {string[]} dbRowType Array of strings with each string representing a
* type of database row
* @returns A promise with resolve listed on a map which has the database rows.
*/
export function infoFromDb(map, dbRowType) {
return new Promise((resolve, reject) => {
var db = map.database;
var dbInfo = [];
for (let i=0; i<dbRowType.length; i++) {
if (dbRowType[i] === "clusters") {
dbInfo[i] = selectAllClusters(db)
.then((dbRows) => map[dbRowType[i]] = dbRows);
}
else if (dbRowType[i] == "enums") {
dbInfo[i] = selectAllEnums(db)
.then((dbRows) => map[dbRowType[i]] = dbRows);
} else if (dbRowType[i] == "bitmaps") {
dbInfo[i] = selectAllBitmaps(db)
.then((dbRows) => map[dbRowType[i]] = dbRows);
}
}
// Going through an array of promises and resolving them.
Promise.all(dbInfo).then(() => {
resolve(map);
}).catch(
(reason) => {
console.log('infoFromDb Handle rejected promise ('+reason+') here.');
}
)
})
}
/**
* Additional information attached to each database row. Essentially a way
* to group by content.
*
* @export
* @param {Object} map Map containing database, compiled templates, database and
* database rows for different datbase types.
* @param {Object} groupByParams Object to group information by
* @param {string} groupByParams.subItemName
* @param {string} groupByParams.foreignKey
* @param {string} groupByParams.primaryKey
* @param {string} groupByParams.dbType
* @param {string} groupByParams.columns
* @returns A promise with resolve listed on a map which has the database,
* compiled templates and database rows along with additional grouped by
* content.
*/
export function groupInfoIntoDbRow(map, groupByParams) {
return new Promise((resolve, reject) => {
var subItemName = groupByParams.tableName;
var foreignKey = groupByParams.foreignKey;
var primaryKey = groupByParams.primaryKey
var dbType = groupByParams.dbType;
var columns = groupByParams.columns;
var db = map.database;
var dbRows = map[dbType];
var subDbRows = [];
var subItems;
if (subItemName == 'ENUM_ITEMS') {
subItems = selectAllEnumItems(db);
} else if (subItemName == 'BITMAP_FIELDS') {
subItems = selectAllBitmapFields(db);
} else {
return;
}
subItems.then(function(rows) {
for (let i=0; i<rows.length;i++) {
// create a map here and print in next prmoise to see if it is populated
if ( subDbRows[rows[i][foreignKey]] == null) {
subDbRows[rows[i][foreignKey]] = [{NAME: rows[i][columns.NAME], VALUE: rows[i][columns.VALUE]}];
} else {
var nameValue = {NAME: rows[i][columns.NAME], VALUE: rows[i][columns.VALUE]};
subDbRows[rows[i][foreignKey]].push(nameValue);
}
}
for (let j=0; j<dbRows.length; j++) {
var pk = dbRows[j][primaryKey];
dbRows[j][subItemName] = subDbRows[pk];
}
resolve(map);
}).catch(
(reason) => {
console.log('groupInfoIntoDbRow Handle rejected promise ('+reason+') here.');
})
})
}
/**
* Resolve the helper functions to be used in later promises.
*
* @export
* @param {Object} map
* @param {Object} helperFunctions Map for handlebar helper name to helper function
* @returns A promise with resolve listed on a map which has the helper
* functions.
*/
export function resolveHelper(map, helperFunctions) {
return new Promise((resolve, reject) => {
map.helperFunctions = helperFunctions;
resolve(map);
})
}
/**
* Resolve the generation directory to be able to generate to the correct
* directory.
*
* @export
* @param {Object} map
* @param {string} generationDirectory generation directory path.
* @returns A promise with resolve listed on a map which has the generation
* directory.
*/
export function resolveGenerationDirectory(map, generationDirectory) {
return new Promise((resolve, reject) => {
map.generationDirectory = generationDirectory;
resolve(map);
})
}
/**
* The database information is used to show the generation output to a preview
* pane using the compiled handlebar templates.
*
* @export
* @param {Object} map
* @param {Object[]} databaseRowToHandlebarTemplateFileMap Map linking the
* database row type with handlebar template file.
* @param {string} databaseRowToHandlebarTemplateFileMap.dbRowType Database
* row type
* @param {string} databaseRowToHandlebarTemplateFileMap.hTemplateFile Handlebar
* template file
* @returns A promise with resolve listed on the data which can be seen in the
* preview pane.
*/
export function generateDataToPreview(map, databaseRowToHandlebarTemplateFileMap) {
return new Promise((resolve, reject) => {
var result='';
for (let i=0; i<databaseRowToHandlebarTemplateFileMap.length; i++) {
var compiledTemplate = map[databaseRowToHandlebarTemplateFileMap[i].hTemplateFile];
var dbRows = map[databaseRowToHandlebarTemplateFileMap[i].dbRowType];
for (var key in map.helperFunctions) {
Handlebars.registerHelper(key, map.helperFunctions[key]);
}
var define = compiledTemplate({
type: dbRows
});
result = result + define;
}
resolve(result);
})
}
/**
* The database information is used to write the generation output to a file
* using the compiled handlebar templates.
*
* @export
* @param {Object} map
* @param {string} outputFileName The generation file name
* @param {Object[]} databaseRowToHandlebarTemplateFileMap Map linking the
* database row type with handlebar template file.
* @param {string} databaseRowToHandlebarTemplateFileMap.dbRowType Database
* row type
* @param {string} databaseRowToHandlebarTemplateFileMap.hTemplateFile Handlebar
* template file
* @returns A new promise resolve listed on the data which is generated.
*/
export function generateDataToFile(map, outputFileName, databaseRowToHandlebarTemplateFileMap) {
return new Promise((resolve, reject) => {
var result='';
var generationDirectory = map.generationDirectory;
for (let i=0; i<databaseRowToHandlebarTemplateFileMap.length; i++) {
var compiledTemplate = map[databaseRowToHandlebarTemplateFileMap[i].hTemplateFile];
var dbRows = map[databaseRowToHandlebarTemplateFileMap[i].dbRowType];
for (var key in map.helperFunctions) {
Handlebars.registerHelper(key, map.helperFunctions[key]);
}
var define = compiledTemplate({
type: dbRows
});
if ( !fs.existsSync(generationDirectory) ) {
fs.mkdirSync(generationDirectory);
}
result = result + define;
}
resolve(result);
fs.writeFileSync(generationDirectory + '/' + outputFileName, result);
})
}
/**
Given: String
Return: String
Description: return the given string in uppercase and convert spaces into
underscores.
*/
export function getUppercase(str) {
str = findAndReplace(str, [" "], "_");
return str.toUpperCase();
};
/**
Given: String
Return: String
Description: return the given string such that camel case is changed into a
string with underscores and is also uppercase.
*/
export function getStrong(str) {
str = str.replace(/\.?([A-Z][a-z])/g, function (x,y){return "_" + y}).replace(/^_/, "");
return str.toUpperCase();
};
/**
Given: String
Return: String
Description: return the given string but convert it into a number and then
into a hex string to keep consistency in the hex strings values.
*/
export function getHexValue(str) {
var hexString = parseInt(str, 16).toString(16).toUpperCase();
var prefix;
if (hexString.length % 2 == 0) {
prefix = "0x";
} else {
prefix = "0x0";
}
var result = prefix + hexString;
return result;
}
/**
Given: String
Return: String
Description: Change the target values using the replacement mentioned and
return the given string.
*/
function findAndReplace(string, target, replacement) {
var i=0, j = 0, length = string.length, targetLength = target.length;
for( j=0; j < targetLength; j++) {
for (i=0; i < length; i++) {
string = string.replace(target[j], replacement);
}
}
return string;
}
\ No newline at end of file
文件已添加
src-electron/icons/icon.ico

154.4 KB

src-electron/icons/linux-512x512.png

97.2 KB

src-electron/icons/zap_128x128.png

19.7 KB

src-electron/icons/zap_16x16.png

2.3 KB

src-electron/icons/zap_32x32.png

4.0 KB

src-electron/icons/zap_64x64.png

8.3 KB

0% 加载中 .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册