id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
20,600
blackbaud/skyux-builder
cli/build-public-library.js
transpile
function transpile() { return new Promise((resolve, reject) => { const result = spawn.sync( skyPagesConfigUtil.spaPath('node_modules', '.bin', 'ngc'), [ '--project', skyPagesConfigUtil.spaPathTemp('tsconfig.json') ], { stdio: 'inherit' } ); // Catch ngc errors. if (result.err) { reject(result.err); return; } // Catch non-zero status codes. if (result.status !== 0) { reject(new Error(`Angular compiler (ngc) exited with status code ${result.status}.`)); return; } resolve(); }); }
javascript
function transpile() { return new Promise((resolve, reject) => { const result = spawn.sync( skyPagesConfigUtil.spaPath('node_modules', '.bin', 'ngc'), [ '--project', skyPagesConfigUtil.spaPathTemp('tsconfig.json') ], { stdio: 'inherit' } ); // Catch ngc errors. if (result.err) { reject(result.err); return; } // Catch non-zero status codes. if (result.status !== 0) { reject(new Error(`Angular compiler (ngc) exited with status code ${result.status}.`)); return; } resolve(); }); }
[ "function", "transpile", "(", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "result", "=", "spawn", ".", "sync", "(", "skyPagesConfigUtil", ".", "spaPath", "(", "'node_modules'", ",", "'.bin'", ",", "'ngc'", ")", ",", "[", "'--project'", ",", "skyPagesConfigUtil", ".", "spaPathTemp", "(", "'tsconfig.json'", ")", "]", ",", "{", "stdio", ":", "'inherit'", "}", ")", ";", "// Catch ngc errors.", "if", "(", "result", ".", "err", ")", "{", "reject", "(", "result", ".", "err", ")", ";", "return", ";", "}", "// Catch non-zero status codes.", "if", "(", "result", ".", "status", "!==", "0", ")", "{", "reject", "(", "new", "Error", "(", "`", "${", "result", ".", "status", "}", "`", ")", ")", ";", "return", ";", "}", "resolve", "(", ")", ";", "}", ")", ";", "}" ]
Transpiles TypeScript files into JavaScript files to be included with the NPM package.
[ "Transpiles", "TypeScript", "files", "into", "JavaScript", "files", "to", "be", "included", "with", "the", "NPM", "package", "." ]
fe8c622f12817552f85940abe194ddcb262e7b44
https://github.com/blackbaud/skyux-builder/blob/fe8c622f12817552f85940abe194ddcb262e7b44/cli/build-public-library.js#L138-L163
20,601
blackbaud/skyux-builder
lib/assets-processor.js
getAssetsUrl
function getAssetsUrl(skyPagesConfig, baseUrl, rel) { return baseUrl + skyPagesConfig.runtime.app.base + (rel || ''); }
javascript
function getAssetsUrl(skyPagesConfig, baseUrl, rel) { return baseUrl + skyPagesConfig.runtime.app.base + (rel || ''); }
[ "function", "getAssetsUrl", "(", "skyPagesConfig", ",", "baseUrl", ",", "rel", ")", "{", "return", "baseUrl", "+", "skyPagesConfig", ".", "runtime", ".", "app", ".", "base", "+", "(", "rel", "||", "''", ")", ";", "}" ]
Gets the assets URL with the application's root directory appended to it. @param {*} skyPagesConfig The SKY UX app config. @param {*} baseUrl The base URL where the assets will be served. @param {*} rel An additional relative path to append to the assets base URL once the application's root directory has been appended.
[ "Gets", "the", "assets", "URL", "with", "the", "application", "s", "root", "directory", "appended", "to", "it", "." ]
fe8c622f12817552f85940abe194ddcb262e7b44
https://github.com/blackbaud/skyux-builder/blob/fe8c622f12817552f85940abe194ddcb262e7b44/lib/assets-processor.js#L22-L24
20,602
blackbaud/skyux-builder
lib/assets-processor.js
processAssets
function processAssets(content, baseUrl, callback) { let match = ASSETS_REGEX.exec(content); while (match) { const matchString = match[0]; let filePath; let filePathWithHash; if (isLocaleFile(matchString)) { filePath = resolvePhysicalLocaleFilePath(matchString); filePathWithHash = resolveRelativeLocaleFileDestination( assetsUtils.getFilePathWithHash(filePath, true) ); } else { filePath = matchString.substring(2, matchString.length); filePathWithHash = assetsUtils.getFilePathWithHash(filePath, true); } if (callback) { callback(filePathWithHash, skyPagesConfigUtil.spaPath('src', filePath)); } const url = `${baseUrl}${filePathWithHash.replace(/\\/gi, '/')}`; content = content.replace( new RegExp(matchString, 'gi'), url ); match = ASSETS_REGEX.exec(content); } return content; }
javascript
function processAssets(content, baseUrl, callback) { let match = ASSETS_REGEX.exec(content); while (match) { const matchString = match[0]; let filePath; let filePathWithHash; if (isLocaleFile(matchString)) { filePath = resolvePhysicalLocaleFilePath(matchString); filePathWithHash = resolveRelativeLocaleFileDestination( assetsUtils.getFilePathWithHash(filePath, true) ); } else { filePath = matchString.substring(2, matchString.length); filePathWithHash = assetsUtils.getFilePathWithHash(filePath, true); } if (callback) { callback(filePathWithHash, skyPagesConfigUtil.spaPath('src', filePath)); } const url = `${baseUrl}${filePathWithHash.replace(/\\/gi, '/')}`; content = content.replace( new RegExp(matchString, 'gi'), url ); match = ASSETS_REGEX.exec(content); } return content; }
[ "function", "processAssets", "(", "content", ",", "baseUrl", ",", "callback", ")", "{", "let", "match", "=", "ASSETS_REGEX", ".", "exec", "(", "content", ")", ";", "while", "(", "match", ")", "{", "const", "matchString", "=", "match", "[", "0", "]", ";", "let", "filePath", ";", "let", "filePathWithHash", ";", "if", "(", "isLocaleFile", "(", "matchString", ")", ")", "{", "filePath", "=", "resolvePhysicalLocaleFilePath", "(", "matchString", ")", ";", "filePathWithHash", "=", "resolveRelativeLocaleFileDestination", "(", "assetsUtils", ".", "getFilePathWithHash", "(", "filePath", ",", "true", ")", ")", ";", "}", "else", "{", "filePath", "=", "matchString", ".", "substring", "(", "2", ",", "matchString", ".", "length", ")", ";", "filePathWithHash", "=", "assetsUtils", ".", "getFilePathWithHash", "(", "filePath", ",", "true", ")", ";", "}", "if", "(", "callback", ")", "{", "callback", "(", "filePathWithHash", ",", "skyPagesConfigUtil", ".", "spaPath", "(", "'src'", ",", "filePath", ")", ")", ";", "}", "const", "url", "=", "`", "${", "baseUrl", "}", "${", "filePathWithHash", ".", "replace", "(", "/", "\\\\", "/", "gi", ",", "'/'", ")", "}", "`", ";", "content", "=", "content", ".", "replace", "(", "new", "RegExp", "(", "matchString", ",", "'gi'", ")", ",", "url", ")", ";", "match", "=", "ASSETS_REGEX", ".", "exec", "(", "content", ")", ";", "}", "return", "content", ";", "}" ]
Finds referenced assets in a file and replaces occurrences in the file's contents with the absolute URL. @param {*} content The file contents. @param {*} baseUrl The base URL where the assets will be served. @param {*} callback A function to call for each found asset path. The function will be provided the file path with a file hash added to the file name along with the physical path to the file.
[ "Finds", "referenced", "assets", "in", "a", "file", "and", "replaces", "occurrences", "in", "the", "file", "s", "contents", "with", "the", "absolute", "URL", "." ]
fe8c622f12817552f85940abe194ddcb262e7b44
https://github.com/blackbaud/skyux-builder/blob/fe8c622f12817552f85940abe194ddcb262e7b44/lib/assets-processor.js#L35-L69
20,603
blackbaud/skyux-builder
lib/assets-processor.js
setSkyAssetsLoaderUrl
function setSkyAssetsLoaderUrl(webpackConfig, skyPagesConfig, baseUrl, rel) { const rules = webpackConfig && webpackConfig.module && webpackConfig.module.rules; if (rules) { const assetsRule = rules.find(rule => /sky-assets$/.test(rule.loader)); assetsRule.options = assetsRule.options || {}; assetsRule.options.baseUrl = getAssetsUrl(skyPagesConfig, baseUrl, rel); } }
javascript
function setSkyAssetsLoaderUrl(webpackConfig, skyPagesConfig, baseUrl, rel) { const rules = webpackConfig && webpackConfig.module && webpackConfig.module.rules; if (rules) { const assetsRule = rules.find(rule => /sky-assets$/.test(rule.loader)); assetsRule.options = assetsRule.options || {}; assetsRule.options.baseUrl = getAssetsUrl(skyPagesConfig, baseUrl, rel); } }
[ "function", "setSkyAssetsLoaderUrl", "(", "webpackConfig", ",", "skyPagesConfig", ",", "baseUrl", ",", "rel", ")", "{", "const", "rules", "=", "webpackConfig", "&&", "webpackConfig", ".", "module", "&&", "webpackConfig", ".", "module", ".", "rules", ";", "if", "(", "rules", ")", "{", "const", "assetsRule", "=", "rules", ".", "find", "(", "rule", "=>", "/", "sky-assets$", "/", ".", "test", "(", "rule", ".", "loader", ")", ")", ";", "assetsRule", ".", "options", "=", "assetsRule", ".", "options", "||", "{", "}", ";", "assetsRule", ".", "options", ".", "baseUrl", "=", "getAssetsUrl", "(", "skyPagesConfig", ",", "baseUrl", ",", "rel", ")", ";", "}", "}" ]
Sets the assets URL on Webpack loaders that reference it. @param {*} webpackConfig The Webpack config object. @param {*} skyPagesConfig The SKY UX app config. @param {*} baseUrl The base URL where the assets will be served. @param {*} rel An additional relative path to append to the assets base URL once the application's root directory has been appended.
[ "Sets", "the", "assets", "URL", "on", "Webpack", "loaders", "that", "reference", "it", "." ]
fe8c622f12817552f85940abe194ddcb262e7b44
https://github.com/blackbaud/skyux-builder/blob/fe8c622f12817552f85940abe194ddcb262e7b44/lib/assets-processor.js#L79-L89
20,604
blackbaud/skyux-builder
utils/assets-utils.js
getFilePathWithHash
function getFilePathWithHash(filePath, rel) { const indexOfLastDot = filePath.lastIndexOf('.'); let filePathWithHash = filePath.substr(0, indexOfLastDot) + '.' + hashFile.sync(skyPagesConfigUtil.spaPath('src', filePath)) + '.' + filePath.substr(indexOfLastDot + 1); if (!rel) { const srcPath = skyPagesConfigUtil.spaPath('src'); filePathWithHash = filePathWithHash.substr(srcPath.length + 1); } return filePathWithHash; }
javascript
function getFilePathWithHash(filePath, rel) { const indexOfLastDot = filePath.lastIndexOf('.'); let filePathWithHash = filePath.substr(0, indexOfLastDot) + '.' + hashFile.sync(skyPagesConfigUtil.spaPath('src', filePath)) + '.' + filePath.substr(indexOfLastDot + 1); if (!rel) { const srcPath = skyPagesConfigUtil.spaPath('src'); filePathWithHash = filePathWithHash.substr(srcPath.length + 1); } return filePathWithHash; }
[ "function", "getFilePathWithHash", "(", "filePath", ",", "rel", ")", "{", "const", "indexOfLastDot", "=", "filePath", ".", "lastIndexOf", "(", "'.'", ")", ";", "let", "filePathWithHash", "=", "filePath", ".", "substr", "(", "0", ",", "indexOfLastDot", ")", "+", "'.'", "+", "hashFile", ".", "sync", "(", "skyPagesConfigUtil", ".", "spaPath", "(", "'src'", ",", "filePath", ")", ")", "+", "'.'", "+", "filePath", ".", "substr", "(", "indexOfLastDot", "+", "1", ")", ";", "if", "(", "!", "rel", ")", "{", "const", "srcPath", "=", "skyPagesConfigUtil", ".", "spaPath", "(", "'src'", ")", ";", "filePathWithHash", "=", "filePathWithHash", ".", "substr", "(", "srcPath", ".", "length", "+", "1", ")", ";", "}", "return", "filePathWithHash", ";", "}" ]
Appends the hash of the specified file to the end of the file path. @param {*} filePath The path to the file. @param {*} rel Optional Boolean flag indicating whether the returned path should be relative to the app's src path.
[ "Appends", "the", "hash", "of", "the", "specified", "file", "to", "the", "end", "of", "the", "file", "path", "." ]
fe8c622f12817552f85940abe194ddcb262e7b44
https://github.com/blackbaud/skyux-builder/blob/fe8c622f12817552f85940abe194ddcb262e7b44/utils/assets-utils.js#L13-L28
20,605
blackbaud/skyux-builder
utils/assets-utils.js
getUrl
function getUrl(baseUrl, filePath) { const filePathWithHash = getFilePathWithHash(filePath); const url = `${baseUrl}${filePathWithHash.replace(/\\/gi, '/')}`; return url; }
javascript
function getUrl(baseUrl, filePath) { const filePathWithHash = getFilePathWithHash(filePath); const url = `${baseUrl}${filePathWithHash.replace(/\\/gi, '/')}`; return url; }
[ "function", "getUrl", "(", "baseUrl", ",", "filePath", ")", "{", "const", "filePathWithHash", "=", "getFilePathWithHash", "(", "filePath", ")", ";", "const", "url", "=", "`", "${", "baseUrl", "}", "${", "filePathWithHash", ".", "replace", "(", "/", "\\\\", "/", "gi", ",", "'/'", ")", "}", "`", ";", "return", "url", ";", "}" ]
Gets the URL to a hashed file name. @param {*} baseUrl The base of the URL where the page is being served. @param {*} filePath The path to the file.
[ "Gets", "the", "URL", "to", "a", "hashed", "file", "name", "." ]
fe8c622f12817552f85940abe194ddcb262e7b44
https://github.com/blackbaud/skyux-builder/blob/fe8c622f12817552f85940abe194ddcb262e7b44/utils/assets-utils.js#L35-L41
20,606
blackbaud/skyux-builder
cli/serve.js
getPort
function getPort(config, skyPagesConfig) { return new Promise((resolve, reject) => { const configPort = skyPagesConfig && skyPagesConfig.skyux && skyPagesConfig.skyux.app && skyPagesConfig.skyux.app.port; if (configPort) { resolve(configPort); } else if (config.devServer && config.devServer.port) { resolve(config.devServer.port); } else { portfinder.getPortPromise() .then(port => resolve(port)) .catch(err => reject(err)); } }); }
javascript
function getPort(config, skyPagesConfig) { return new Promise((resolve, reject) => { const configPort = skyPagesConfig && skyPagesConfig.skyux && skyPagesConfig.skyux.app && skyPagesConfig.skyux.app.port; if (configPort) { resolve(configPort); } else if (config.devServer && config.devServer.port) { resolve(config.devServer.port); } else { portfinder.getPortPromise() .then(port => resolve(port)) .catch(err => reject(err)); } }); }
[ "function", "getPort", "(", "config", ",", "skyPagesConfig", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "configPort", "=", "skyPagesConfig", "&&", "skyPagesConfig", ".", "skyux", "&&", "skyPagesConfig", ".", "skyux", ".", "app", "&&", "skyPagesConfig", ".", "skyux", ".", "app", ".", "port", ";", "if", "(", "configPort", ")", "{", "resolve", "(", "configPort", ")", ";", "}", "else", "if", "(", "config", ".", "devServer", "&&", "config", ".", "devServer", ".", "port", ")", "{", "resolve", "(", "config", ".", "devServer", ".", "port", ")", ";", "}", "else", "{", "portfinder", ".", "getPortPromise", "(", ")", ".", "then", "(", "port", "=>", "resolve", "(", "port", ")", ")", ".", "catch", "(", "err", "=>", "reject", "(", "err", ")", ")", ";", "}", "}", ")", ";", "}" ]
Let users configure port via skyuxconfig.json first. Else another plugin has specified devServer.port, use it. Else, find us an available port. @name getPort @returns {Number} port
[ "Let", "users", "configure", "port", "via", "skyuxconfig", ".", "json", "first", ".", "Else", "another", "plugin", "has", "specified", "devServer", ".", "port", "use", "it", ".", "Else", "find", "us", "an", "available", "port", "." ]
fe8c622f12817552f85940abe194ddcb262e7b44
https://github.com/blackbaud/skyux-builder/blob/fe8c622f12817552f85940abe194ddcb262e7b44/cli/serve.js#L16-L33
20,607
blackbaud/skyux-builder
cli/serve.js
serve
function serve(argv, skyPagesConfig, webpack, WebpackDevServer) { const webpackConfig = require('../config/webpack/serve.webpack.config'); let config = webpackConfig.getWebpackConfig(argv, skyPagesConfig); getPort(config, skyPagesConfig).then(port => { const localUrl = `https://localhost:${port}`; assetsProcessor.setSkyAssetsLoaderUrl(config, skyPagesConfig, localUrl); localeAssetsProcessor.prepareLocaleFiles(); // Save our found or defined port config.devServer.port = port; /* istanbul ignore else */ if (config.devServer.inline) { const inline = `webpack-dev-server/client?${localUrl}`; Object.keys(config.entry).forEach((entry) => { config.entry[entry].unshift(inline); }); } if (config.devServer.hot) { const hot = `webpack/hot/only-dev-server`; Object.keys(config.entry).forEach((entry) => { config.entry[entry].unshift(hot); }); // This is required in order to not have HMR requests routed to host. config.output.publicPath = `${localUrl}${config.devServer.publicPath}`; logger.info('Using hot module replacement.'); } const compiler = webpack(config); const server = new WebpackDevServer(compiler, config.devServer); server.listen(config.devServer.port, 'localhost', (err) => { if (err) { logger.error(err); } }); }).catch(err => logger.error(err)); }
javascript
function serve(argv, skyPagesConfig, webpack, WebpackDevServer) { const webpackConfig = require('../config/webpack/serve.webpack.config'); let config = webpackConfig.getWebpackConfig(argv, skyPagesConfig); getPort(config, skyPagesConfig).then(port => { const localUrl = `https://localhost:${port}`; assetsProcessor.setSkyAssetsLoaderUrl(config, skyPagesConfig, localUrl); localeAssetsProcessor.prepareLocaleFiles(); // Save our found or defined port config.devServer.port = port; /* istanbul ignore else */ if (config.devServer.inline) { const inline = `webpack-dev-server/client?${localUrl}`; Object.keys(config.entry).forEach((entry) => { config.entry[entry].unshift(inline); }); } if (config.devServer.hot) { const hot = `webpack/hot/only-dev-server`; Object.keys(config.entry).forEach((entry) => { config.entry[entry].unshift(hot); }); // This is required in order to not have HMR requests routed to host. config.output.publicPath = `${localUrl}${config.devServer.publicPath}`; logger.info('Using hot module replacement.'); } const compiler = webpack(config); const server = new WebpackDevServer(compiler, config.devServer); server.listen(config.devServer.port, 'localhost', (err) => { if (err) { logger.error(err); } }); }).catch(err => logger.error(err)); }
[ "function", "serve", "(", "argv", ",", "skyPagesConfig", ",", "webpack", ",", "WebpackDevServer", ")", "{", "const", "webpackConfig", "=", "require", "(", "'../config/webpack/serve.webpack.config'", ")", ";", "let", "config", "=", "webpackConfig", ".", "getWebpackConfig", "(", "argv", ",", "skyPagesConfig", ")", ";", "getPort", "(", "config", ",", "skyPagesConfig", ")", ".", "then", "(", "port", "=>", "{", "const", "localUrl", "=", "`", "${", "port", "}", "`", ";", "assetsProcessor", ".", "setSkyAssetsLoaderUrl", "(", "config", ",", "skyPagesConfig", ",", "localUrl", ")", ";", "localeAssetsProcessor", ".", "prepareLocaleFiles", "(", ")", ";", "// Save our found or defined port", "config", ".", "devServer", ".", "port", "=", "port", ";", "/* istanbul ignore else */", "if", "(", "config", ".", "devServer", ".", "inline", ")", "{", "const", "inline", "=", "`", "${", "localUrl", "}", "`", ";", "Object", ".", "keys", "(", "config", ".", "entry", ")", ".", "forEach", "(", "(", "entry", ")", "=>", "{", "config", ".", "entry", "[", "entry", "]", ".", "unshift", "(", "inline", ")", ";", "}", ")", ";", "}", "if", "(", "config", ".", "devServer", ".", "hot", ")", "{", "const", "hot", "=", "`", "`", ";", "Object", ".", "keys", "(", "config", ".", "entry", ")", ".", "forEach", "(", "(", "entry", ")", "=>", "{", "config", ".", "entry", "[", "entry", "]", ".", "unshift", "(", "hot", ")", ";", "}", ")", ";", "// This is required in order to not have HMR requests routed to host.", "config", ".", "output", ".", "publicPath", "=", "`", "${", "localUrl", "}", "${", "config", ".", "devServer", ".", "publicPath", "}", "`", ";", "logger", ".", "info", "(", "'Using hot module replacement.'", ")", ";", "}", "const", "compiler", "=", "webpack", "(", "config", ")", ";", "const", "server", "=", "new", "WebpackDevServer", "(", "compiler", ",", "config", ".", "devServer", ")", ";", "server", ".", "listen", "(", "config", ".", "devServer", ".", "port", ",", "'localhost'", ",", "(", "err", ")", "=>", "{", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "err", ")", ";", "}", "}", ")", ";", "}", ")", ".", "catch", "(", "err", "=>", "logger", ".", "error", "(", "err", ")", ")", ";", "}" ]
Executes the serve command. @name serve @name {Object} argv @name {SkyPagesConfig} skyPagesConfig @name {Webpack} webpack @name {WebpackDevServer} WebpackDevServer @returns null
[ "Executes", "the", "serve", "command", "." ]
fe8c622f12817552f85940abe194ddcb262e7b44
https://github.com/blackbaud/skyux-builder/blob/fe8c622f12817552f85940abe194ddcb262e7b44/cli/serve.js#L44-L86
20,608
blackbaud/skyux-builder
config/karma/shared.karma.conf.js
function (item) { const resolvedPath = path.resolve(item); const ignore = (resolvedPath.indexOf(srcPath) === -1); return ignore; }
javascript
function (item) { const resolvedPath = path.resolve(item); const ignore = (resolvedPath.indexOf(srcPath) === -1); return ignore; }
[ "function", "(", "item", ")", "{", "const", "resolvedPath", "=", "path", ".", "resolve", "(", "item", ")", ";", "const", "ignore", "=", "(", "resolvedPath", ".", "indexOf", "(", "srcPath", ")", "===", "-", "1", ")", ";", "return", "ignore", ";", "}" ]
Returning `true` means the file should be ignored. Fat-Arrow functions do not work as chokidar will inspect this method.
[ "Returning", "true", "means", "the", "file", "should", "be", "ignored", ".", "Fat", "-", "Arrow", "functions", "do", "not", "work", "as", "chokidar", "will", "inspect", "this", "method", "." ]
fe8c622f12817552f85940abe194ddcb262e7b44
https://github.com/blackbaud/skyux-builder/blob/fe8c622f12817552f85940abe194ddcb262e7b44/config/karma/shared.karma.conf.js#L177-L181
20,609
blackbaud/skyux-builder
config/sky-pages/sky-pages.config.js
resolve
function resolve(root, args) { args = root.concat(Array.prototype.slice.call(args)); return path.resolve.apply(path, args); }
javascript
function resolve(root, args) { args = root.concat(Array.prototype.slice.call(args)); return path.resolve.apply(path, args); }
[ "function", "resolve", "(", "root", ",", "args", ")", "{", "args", "=", "root", ".", "concat", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "args", ")", ")", ";", "return", "path", ".", "resolve", ".", "apply", "(", "path", ",", "args", ")", ";", "}" ]
Resolves a path given a root path and an array-like arguments object. @name resolve @param {String} root The root path. @param {Array} args An array or array-like object of additional path parts to add to the root. @returns {String} The resolved path.
[ "Resolves", "a", "path", "given", "a", "root", "path", "and", "an", "array", "-", "like", "arguments", "object", "." ]
fe8c622f12817552f85940abe194ddcb262e7b44
https://github.com/blackbaud/skyux-builder/blob/fe8c622f12817552f85940abe194ddcb262e7b44/config/sky-pages/sky-pages.config.js#L16-L19
20,610
feross/vlc-command
index.js
getInstallDir
function getInstallDir (cb) { var key = new Registry({ hive: Registry.HKLM, key: '\\Software\\VideoLAN\\VLC' }) key.get('InstallDir', cb) }
javascript
function getInstallDir (cb) { var key = new Registry({ hive: Registry.HKLM, key: '\\Software\\VideoLAN\\VLC' }) key.get('InstallDir', cb) }
[ "function", "getInstallDir", "(", "cb", ")", "{", "var", "key", "=", "new", "Registry", "(", "{", "hive", ":", "Registry", ".", "HKLM", ",", "key", ":", "'\\\\Software\\\\VideoLAN\\\\VLC'", "}", ")", "key", ".", "get", "(", "'InstallDir'", ",", "cb", ")", "}" ]
32-bit Windows with 32-bit VLC, and 64-bit Windows with 64-bit VLC
[ "32", "-", "bit", "Windows", "with", "32", "-", "bit", "VLC", "and", "64", "-", "bit", "Windows", "with", "64", "-", "bit", "VLC" ]
ac71ecf65b67b5142ef0081776946ed029dbf0f1
https://github.com/feross/vlc-command/blob/ac71ecf65b67b5142ef0081776946ed029dbf0f1/index.js#L30-L36
20,611
traveloka/javascript
packages/eslint-plugin-marlint/lib/rules/limited-danger.js
isAllowedTagName
function isAllowedTagName(name) { const config = context.options[0] || {}; const allowedTagNames = config.allowedTagNames || DEFAULTS; return allowedTagNames.indexOf(name) !== -1; }
javascript
function isAllowedTagName(name) { const config = context.options[0] || {}; const allowedTagNames = config.allowedTagNames || DEFAULTS; return allowedTagNames.indexOf(name) !== -1; }
[ "function", "isAllowedTagName", "(", "name", ")", "{", "const", "config", "=", "context", ".", "options", "[", "0", "]", "||", "{", "}", ";", "const", "allowedTagNames", "=", "config", ".", "allowedTagNames", "||", "DEFAULTS", ";", "return", "allowedTagNames", ".", "indexOf", "(", "name", ")", "!==", "-", "1", ";", "}" ]
Checks if a node name is allowed to have dangerous attribute. @param {String} tagName - JSX tag name @returns {boolean} Whether or not tag name is allowed to have dangerous attribute
[ "Checks", "if", "a", "node", "name", "is", "allowed", "to", "have", "dangerous", "attribute", "." ]
ff72daaee5994b8a137b072e2595730583eaebbe
https://github.com/traveloka/javascript/blob/ff72daaee5994b8a137b072e2595730583eaebbe/packages/eslint-plugin-marlint/lib/rules/limited-danger.js#L62-L66
20,612
jscs-dev/grunt-jscs
tasks/lib/jscs.js
JSCS
function JSCS( options ) { this.checker = new Checker(); this.options = options; this._reporter = null; this.checker.registerDefaultRules(); this.checker.configure( this.getConfig() ); this.registerReporter( options.reporter ); }
javascript
function JSCS( options ) { this.checker = new Checker(); this.options = options; this._reporter = null; this.checker.registerDefaultRules(); this.checker.configure( this.getConfig() ); this.registerReporter( options.reporter ); }
[ "function", "JSCS", "(", "options", ")", "{", "this", ".", "checker", "=", "new", "Checker", "(", ")", ";", "this", ".", "options", "=", "options", ";", "this", ".", "_reporter", "=", "null", ";", "this", ".", "checker", ".", "registerDefaultRules", "(", ")", ";", "this", ".", "checker", ".", "configure", "(", "this", ".", "getConfig", "(", ")", ")", ";", "this", ".", "registerReporter", "(", "options", ".", "reporter", ")", ";", "}" ]
Create new instance of jscs Checker module @constructor @param {Object} options @return {JSCS}
[ "Create", "new", "instance", "of", "jscs", "Checker", "module" ]
efff3087a86296b4a6e8810a0f5e4c215be6210d
https://github.com/jscs-dev/grunt-jscs/blob/efff3087a86296b4a6e8810a0f5e4c215be6210d/tasks/lib/jscs.js#L35-L44
20,613
osk/node-webvtt
lib/parser.js
parseCue
function parseCue (cue, i) { let identifier = ''; let start = 0; let end = 0.01; let text = ''; let styles = ''; // split and remove empty lines const lines = cue.split('\n').filter(Boolean); if (lines.length > 0 && lines[0].trim().startsWith('NOTE')) { return null; } if (lines.length === 1 && !lines[0].includes('-->')) { throw new ParserError(`Cue identifier cannot be standalone (cue #${i})`); } if (lines.length > 1 && !(lines[0].includes('-->') || lines[1].includes('-->'))) { const msg = `Cue identifier needs to be followed by timestamp (cue #${i})`; throw new ParserError(msg); } if (lines.length > 1 && lines[1].includes('-->')) { identifier = lines.shift(); } const times = lines[0].split(' --> '); if (times.length !== 2 || !validTimestamp(times[0]) || !validTimestamp(times[1])) { throw new ParserError(`Invalid cue timestamp (cue #${i})`); } start = parseTimestamp(times[0]); end = parseTimestamp(times[1]); if (start > end) { throw new ParserError(`Start timestamp greater than end (cue #${i})`); } if (end <= start) { throw new ParserError(`End must be greater than start (cue #${i})`); } // TODO better style validation styles = times[1].replace(TIMESTAMP_REGEXP, '').trim(); lines.shift(); text = lines.join('\n'); if (!text) { return false; } return { identifier, start, end, text, styles }; }
javascript
function parseCue (cue, i) { let identifier = ''; let start = 0; let end = 0.01; let text = ''; let styles = ''; // split and remove empty lines const lines = cue.split('\n').filter(Boolean); if (lines.length > 0 && lines[0].trim().startsWith('NOTE')) { return null; } if (lines.length === 1 && !lines[0].includes('-->')) { throw new ParserError(`Cue identifier cannot be standalone (cue #${i})`); } if (lines.length > 1 && !(lines[0].includes('-->') || lines[1].includes('-->'))) { const msg = `Cue identifier needs to be followed by timestamp (cue #${i})`; throw new ParserError(msg); } if (lines.length > 1 && lines[1].includes('-->')) { identifier = lines.shift(); } const times = lines[0].split(' --> '); if (times.length !== 2 || !validTimestamp(times[0]) || !validTimestamp(times[1])) { throw new ParserError(`Invalid cue timestamp (cue #${i})`); } start = parseTimestamp(times[0]); end = parseTimestamp(times[1]); if (start > end) { throw new ParserError(`Start timestamp greater than end (cue #${i})`); } if (end <= start) { throw new ParserError(`End must be greater than start (cue #${i})`); } // TODO better style validation styles = times[1].replace(TIMESTAMP_REGEXP, '').trim(); lines.shift(); text = lines.join('\n'); if (!text) { return false; } return { identifier, start, end, text, styles }; }
[ "function", "parseCue", "(", "cue", ",", "i", ")", "{", "let", "identifier", "=", "''", ";", "let", "start", "=", "0", ";", "let", "end", "=", "0.01", ";", "let", "text", "=", "''", ";", "let", "styles", "=", "''", ";", "// split and remove empty lines", "const", "lines", "=", "cue", ".", "split", "(", "'\\n'", ")", ".", "filter", "(", "Boolean", ")", ";", "if", "(", "lines", ".", "length", ">", "0", "&&", "lines", "[", "0", "]", ".", "trim", "(", ")", ".", "startsWith", "(", "'NOTE'", ")", ")", "{", "return", "null", ";", "}", "if", "(", "lines", ".", "length", "===", "1", "&&", "!", "lines", "[", "0", "]", ".", "includes", "(", "'-->'", ")", ")", "{", "throw", "new", "ParserError", "(", "`", "${", "i", "}", "`", ")", ";", "}", "if", "(", "lines", ".", "length", ">", "1", "&&", "!", "(", "lines", "[", "0", "]", ".", "includes", "(", "'-->'", ")", "||", "lines", "[", "1", "]", ".", "includes", "(", "'-->'", ")", ")", ")", "{", "const", "msg", "=", "`", "${", "i", "}", "`", ";", "throw", "new", "ParserError", "(", "msg", ")", ";", "}", "if", "(", "lines", ".", "length", ">", "1", "&&", "lines", "[", "1", "]", ".", "includes", "(", "'-->'", ")", ")", "{", "identifier", "=", "lines", ".", "shift", "(", ")", ";", "}", "const", "times", "=", "lines", "[", "0", "]", ".", "split", "(", "' --> '", ")", ";", "if", "(", "times", ".", "length", "!==", "2", "||", "!", "validTimestamp", "(", "times", "[", "0", "]", ")", "||", "!", "validTimestamp", "(", "times", "[", "1", "]", ")", ")", "{", "throw", "new", "ParserError", "(", "`", "${", "i", "}", "`", ")", ";", "}", "start", "=", "parseTimestamp", "(", "times", "[", "0", "]", ")", ";", "end", "=", "parseTimestamp", "(", "times", "[", "1", "]", ")", ";", "if", "(", "start", ">", "end", ")", "{", "throw", "new", "ParserError", "(", "`", "${", "i", "}", "`", ")", ";", "}", "if", "(", "end", "<=", "start", ")", "{", "throw", "new", "ParserError", "(", "`", "${", "i", "}", "`", ")", ";", "}", "// TODO better style validation", "styles", "=", "times", "[", "1", "]", ".", "replace", "(", "TIMESTAMP_REGEXP", ",", "''", ")", ".", "trim", "(", ")", ";", "lines", ".", "shift", "(", ")", ";", "text", "=", "lines", ".", "join", "(", "'\\n'", ")", ";", "if", "(", "!", "text", ")", "{", "return", "false", ";", "}", "return", "{", "identifier", ",", "start", ",", "end", ",", "text", ",", "styles", "}", ";", "}" ]
Parse a single cue block. @param {array} cue Array of content for the cue @param {number} i Index of cue in array @returns {object} cue Cue object with start, end, text and styles. Null if it's a note
[ "Parse", "a", "single", "cue", "block", "." ]
b75a4b9f9025030dde4f238ad043a1e33e9e703a
https://github.com/osk/node-webvtt/blob/b75a4b9f9025030dde4f238ad043a1e33e9e703a/lib/parser.js#L92-L151
20,614
osk/node-webvtt
lib/compiler.js
compileCue
function compileCue (cue) { // TODO: check for malformed JSON if (typeof cue !== 'object') { throw new CompilerError('Cue malformed: not of type object'); } if (typeof cue.identifier !== 'string' && typeof cue.identifier !== 'number' && cue.identifier !== null) { throw new CompilerError(`Cue malformed: identifier value is not a string. ${JSON.stringify(cue)}`); } if (isNaN(cue.start)) { throw new CompilerError(`Cue malformed: null start value. ${JSON.stringify(cue)}`); } if (isNaN(cue.end)) { throw new CompilerError(`Cue malformed: null end value. ${JSON.stringify(cue)}`); } if (cue.start >= cue.end) { throw new CompilerError(`Cue malformed: start timestamp greater than end ${JSON.stringify(cue)}`); } if (typeof cue.text !== 'string') { throw new CompilerError(`Cue malformed: null text value. ${JSON.stringify(cue)}`); } if (typeof cue.styles !== 'string') { throw new CompilerError(`Cue malformed: null styles value. ${JSON.stringify(cue)}`); } let output = ''; if (cue.identifier.length > 0) { output += `${cue.identifier}\n`; } const startTimestamp = convertTimestamp(cue.start); const endTimestamp = convertTimestamp(cue.end); output += `${startTimestamp} --> ${endTimestamp}`; output += cue.styles ? ` ${cue.styles}` : ''; output += `\n${cue.text}`; return output; }
javascript
function compileCue (cue) { // TODO: check for malformed JSON if (typeof cue !== 'object') { throw new CompilerError('Cue malformed: not of type object'); } if (typeof cue.identifier !== 'string' && typeof cue.identifier !== 'number' && cue.identifier !== null) { throw new CompilerError(`Cue malformed: identifier value is not a string. ${JSON.stringify(cue)}`); } if (isNaN(cue.start)) { throw new CompilerError(`Cue malformed: null start value. ${JSON.stringify(cue)}`); } if (isNaN(cue.end)) { throw new CompilerError(`Cue malformed: null end value. ${JSON.stringify(cue)}`); } if (cue.start >= cue.end) { throw new CompilerError(`Cue malformed: start timestamp greater than end ${JSON.stringify(cue)}`); } if (typeof cue.text !== 'string') { throw new CompilerError(`Cue malformed: null text value. ${JSON.stringify(cue)}`); } if (typeof cue.styles !== 'string') { throw new CompilerError(`Cue malformed: null styles value. ${JSON.stringify(cue)}`); } let output = ''; if (cue.identifier.length > 0) { output += `${cue.identifier}\n`; } const startTimestamp = convertTimestamp(cue.start); const endTimestamp = convertTimestamp(cue.end); output += `${startTimestamp} --> ${endTimestamp}`; output += cue.styles ? ` ${cue.styles}` : ''; output += `\n${cue.text}`; return output; }
[ "function", "compileCue", "(", "cue", ")", "{", "// TODO: check for malformed JSON", "if", "(", "typeof", "cue", "!==", "'object'", ")", "{", "throw", "new", "CompilerError", "(", "'Cue malformed: not of type object'", ")", ";", "}", "if", "(", "typeof", "cue", ".", "identifier", "!==", "'string'", "&&", "typeof", "cue", ".", "identifier", "!==", "'number'", "&&", "cue", ".", "identifier", "!==", "null", ")", "{", "throw", "new", "CompilerError", "(", "`", "${", "JSON", ".", "stringify", "(", "cue", ")", "}", "`", ")", ";", "}", "if", "(", "isNaN", "(", "cue", ".", "start", ")", ")", "{", "throw", "new", "CompilerError", "(", "`", "${", "JSON", ".", "stringify", "(", "cue", ")", "}", "`", ")", ";", "}", "if", "(", "isNaN", "(", "cue", ".", "end", ")", ")", "{", "throw", "new", "CompilerError", "(", "`", "${", "JSON", ".", "stringify", "(", "cue", ")", "}", "`", ")", ";", "}", "if", "(", "cue", ".", "start", ">=", "cue", ".", "end", ")", "{", "throw", "new", "CompilerError", "(", "`", "${", "JSON", ".", "stringify", "(", "cue", ")", "}", "`", ")", ";", "}", "if", "(", "typeof", "cue", ".", "text", "!==", "'string'", ")", "{", "throw", "new", "CompilerError", "(", "`", "${", "JSON", ".", "stringify", "(", "cue", ")", "}", "`", ")", ";", "}", "if", "(", "typeof", "cue", ".", "styles", "!==", "'string'", ")", "{", "throw", "new", "CompilerError", "(", "`", "${", "JSON", ".", "stringify", "(", "cue", ")", "}", "`", ")", ";", "}", "let", "output", "=", "''", ";", "if", "(", "cue", ".", "identifier", ".", "length", ">", "0", ")", "{", "output", "+=", "`", "${", "cue", ".", "identifier", "}", "\\n", "`", ";", "}", "const", "startTimestamp", "=", "convertTimestamp", "(", "cue", ".", "start", ")", ";", "const", "endTimestamp", "=", "convertTimestamp", "(", "cue", ".", "end", ")", ";", "output", "+=", "`", "${", "startTimestamp", "}", "${", "endTimestamp", "}", "`", ";", "output", "+=", "cue", ".", "styles", "?", "`", "${", "cue", ".", "styles", "}", "`", ":", "''", ";", "output", "+=", "`", "\\n", "${", "cue", ".", "text", "}", "`", ";", "return", "output", ";", "}" ]
Compile a single cue block. @param {array} cue Array of content for the cue @returns {object} cue Cue object with start, end, text and styles. Null if it's a note
[ "Compile", "a", "single", "cue", "block", "." ]
b75a4b9f9025030dde4f238ad043a1e33e9e703a
https://github.com/osk/node-webvtt/blob/b75a4b9f9025030dde4f238ad043a1e33e9e703a/lib/compiler.js#L51-L103
20,615
sociomantic-tsunami/nessie-ui
docs/assets/app.js
drawSelectionRange
function drawSelectionRange(cm,range$$1,output){var display=cm.display,doc=cm.doc;var fragment=document.createDocumentFragment();var padding=paddingH(cm.display),leftSide=padding.left;var rightSide=Math.max(display.sizerWidth,displayWidth(cm)-display.sizer.offsetLeft)-padding.right;var docLTR=doc.direction=="ltr";function add(left,top,width,bottom){if(top<0){top=0;}top=Math.round(top);bottom=Math.round(bottom);fragment.appendChild(elt("div",null,"CodeMirror-selected","position: absolute; left: "+left+"px;\n top: "+top+"px; width: "+(width==null?rightSide-left:width)+"px;\n height: "+(bottom-top)+"px"));}function drawForLine(line,fromArg,toArg){var lineObj=getLine(doc,line);var lineLen=lineObj.text.length;var start,end;function coords(ch,bias){return _charCoords(cm,Pos(line,ch),"div",lineObj,bias);}function wrapX(pos,dir,side){var extent=wrappedLineExtentChar(cm,lineObj,null,pos);var prop=dir=="ltr"==(side=="after")?"left":"right";var ch=side=="after"?extent.begin:extent.end-(/\s/.test(lineObj.text.charAt(extent.end-1))?2:1);return coords(ch,prop)[prop];}var order=getOrder(lineObj,doc.direction);iterateBidiSections(order,fromArg||0,toArg==null?lineLen:toArg,function(from,to,dir,i){var ltr=dir=="ltr";var fromPos=coords(from,ltr?"left":"right");var toPos=coords(to-1,ltr?"right":"left");var openStart=fromArg==null&&from==0,openEnd=toArg==null&&to==lineLen;var first=i==0,last=!order||i==order.length-1;if(toPos.top-fromPos.top<=3){// Single line var openLeft=(docLTR?openStart:openEnd)&&first;var openRight=(docLTR?openEnd:openStart)&&last;var left=openLeft?leftSide:(ltr?fromPos:toPos).left;var right=openRight?rightSide:(ltr?toPos:fromPos).right;add(left,fromPos.top,right-left,fromPos.bottom);}else{// Multiple lines var topLeft,topRight,botLeft,botRight;if(ltr){topLeft=docLTR&&openStart&&first?leftSide:fromPos.left;topRight=docLTR?rightSide:wrapX(from,dir,"before");botLeft=docLTR?leftSide:wrapX(to,dir,"after");botRight=docLTR&&openEnd&&last?rightSide:toPos.right;}else{topLeft=!docLTR?leftSide:wrapX(from,dir,"before");topRight=!docLTR&&openStart&&first?rightSide:fromPos.right;botLeft=!docLTR&&openEnd&&last?leftSide:toPos.left;botRight=!docLTR?rightSide:wrapX(to,dir,"after");}add(topLeft,fromPos.top,topRight-topLeft,fromPos.bottom);if(fromPos.bottom<toPos.top){add(leftSide,fromPos.bottom,null,toPos.top);}add(botLeft,toPos.top,botRight-botLeft,toPos.bottom);}if(!start||cmpCoords(fromPos,start)<0){start=fromPos;}if(cmpCoords(toPos,start)<0){start=toPos;}if(!end||cmpCoords(fromPos,end)<0){end=fromPos;}if(cmpCoords(toPos,end)<0){end=toPos;}});return{start:start,end:end};}var sFrom=range$$1.from(),sTo=range$$1.to();if(sFrom.line==sTo.line){drawForLine(sFrom.line,sFrom.ch,sTo.ch);}else{var fromLine=getLine(doc,sFrom.line),toLine=getLine(doc,sTo.line);var singleVLine=visualLine(fromLine)==visualLine(toLine);var leftEnd=drawForLine(sFrom.line,sFrom.ch,singleVLine?fromLine.text.length+1:null).end;var rightStart=drawForLine(sTo.line,singleVLine?0:null,sTo.ch).start;if(singleVLine){if(leftEnd.top<rightStart.top-2){add(leftEnd.right,leftEnd.top,null,leftEnd.bottom);add(leftSide,rightStart.top,rightStart.left,rightStart.bottom);}else{add(leftEnd.right,leftEnd.top,rightStart.left-leftEnd.right,leftEnd.bottom);}}if(leftEnd.bottom<rightStart.top){add(leftSide,leftEnd.bottom,null,rightStart.top);}}output.appendChild(fragment);}
javascript
function drawSelectionRange(cm,range$$1,output){var display=cm.display,doc=cm.doc;var fragment=document.createDocumentFragment();var padding=paddingH(cm.display),leftSide=padding.left;var rightSide=Math.max(display.sizerWidth,displayWidth(cm)-display.sizer.offsetLeft)-padding.right;var docLTR=doc.direction=="ltr";function add(left,top,width,bottom){if(top<0){top=0;}top=Math.round(top);bottom=Math.round(bottom);fragment.appendChild(elt("div",null,"CodeMirror-selected","position: absolute; left: "+left+"px;\n top: "+top+"px; width: "+(width==null?rightSide-left:width)+"px;\n height: "+(bottom-top)+"px"));}function drawForLine(line,fromArg,toArg){var lineObj=getLine(doc,line);var lineLen=lineObj.text.length;var start,end;function coords(ch,bias){return _charCoords(cm,Pos(line,ch),"div",lineObj,bias);}function wrapX(pos,dir,side){var extent=wrappedLineExtentChar(cm,lineObj,null,pos);var prop=dir=="ltr"==(side=="after")?"left":"right";var ch=side=="after"?extent.begin:extent.end-(/\s/.test(lineObj.text.charAt(extent.end-1))?2:1);return coords(ch,prop)[prop];}var order=getOrder(lineObj,doc.direction);iterateBidiSections(order,fromArg||0,toArg==null?lineLen:toArg,function(from,to,dir,i){var ltr=dir=="ltr";var fromPos=coords(from,ltr?"left":"right");var toPos=coords(to-1,ltr?"right":"left");var openStart=fromArg==null&&from==0,openEnd=toArg==null&&to==lineLen;var first=i==0,last=!order||i==order.length-1;if(toPos.top-fromPos.top<=3){// Single line var openLeft=(docLTR?openStart:openEnd)&&first;var openRight=(docLTR?openEnd:openStart)&&last;var left=openLeft?leftSide:(ltr?fromPos:toPos).left;var right=openRight?rightSide:(ltr?toPos:fromPos).right;add(left,fromPos.top,right-left,fromPos.bottom);}else{// Multiple lines var topLeft,topRight,botLeft,botRight;if(ltr){topLeft=docLTR&&openStart&&first?leftSide:fromPos.left;topRight=docLTR?rightSide:wrapX(from,dir,"before");botLeft=docLTR?leftSide:wrapX(to,dir,"after");botRight=docLTR&&openEnd&&last?rightSide:toPos.right;}else{topLeft=!docLTR?leftSide:wrapX(from,dir,"before");topRight=!docLTR&&openStart&&first?rightSide:fromPos.right;botLeft=!docLTR&&openEnd&&last?leftSide:toPos.left;botRight=!docLTR?rightSide:wrapX(to,dir,"after");}add(topLeft,fromPos.top,topRight-topLeft,fromPos.bottom);if(fromPos.bottom<toPos.top){add(leftSide,fromPos.bottom,null,toPos.top);}add(botLeft,toPos.top,botRight-botLeft,toPos.bottom);}if(!start||cmpCoords(fromPos,start)<0){start=fromPos;}if(cmpCoords(toPos,start)<0){start=toPos;}if(!end||cmpCoords(fromPos,end)<0){end=fromPos;}if(cmpCoords(toPos,end)<0){end=toPos;}});return{start:start,end:end};}var sFrom=range$$1.from(),sTo=range$$1.to();if(sFrom.line==sTo.line){drawForLine(sFrom.line,sFrom.ch,sTo.ch);}else{var fromLine=getLine(doc,sFrom.line),toLine=getLine(doc,sTo.line);var singleVLine=visualLine(fromLine)==visualLine(toLine);var leftEnd=drawForLine(sFrom.line,sFrom.ch,singleVLine?fromLine.text.length+1:null).end;var rightStart=drawForLine(sTo.line,singleVLine?0:null,sTo.ch).start;if(singleVLine){if(leftEnd.top<rightStart.top-2){add(leftEnd.right,leftEnd.top,null,leftEnd.bottom);add(leftSide,rightStart.top,rightStart.left,rightStart.bottom);}else{add(leftEnd.right,leftEnd.top,rightStart.left-leftEnd.right,leftEnd.bottom);}}if(leftEnd.bottom<rightStart.top){add(leftSide,leftEnd.bottom,null,rightStart.top);}}output.appendChild(fragment);}
[ "function", "drawSelectionRange", "(", "cm", ",", "range$$1", ",", "output", ")", "{", "var", "display", "=", "cm", ".", "display", ",", "doc", "=", "cm", ".", "doc", ";", "var", "fragment", "=", "document", ".", "createDocumentFragment", "(", ")", ";", "var", "padding", "=", "paddingH", "(", "cm", ".", "display", ")", ",", "leftSide", "=", "padding", ".", "left", ";", "var", "rightSide", "=", "Math", ".", "max", "(", "display", ".", "sizerWidth", ",", "displayWidth", "(", "cm", ")", "-", "display", ".", "sizer", ".", "offsetLeft", ")", "-", "padding", ".", "right", ";", "var", "docLTR", "=", "doc", ".", "direction", "==", "\"ltr\"", ";", "function", "add", "(", "left", ",", "top", ",", "width", ",", "bottom", ")", "{", "if", "(", "top", "<", "0", ")", "{", "top", "=", "0", ";", "}", "top", "=", "Math", ".", "round", "(", "top", ")", ";", "bottom", "=", "Math", ".", "round", "(", "bottom", ")", ";", "fragment", ".", "appendChild", "(", "elt", "(", "\"div\"", ",", "null", ",", "\"CodeMirror-selected\"", ",", "\"position: absolute; left: \"", "+", "left", "+", "\"px;\\n top: \"", "+", "top", "+", "\"px; width: \"", "+", "(", "width", "==", "null", "?", "rightSide", "-", "left", ":", "width", ")", "+", "\"px;\\n height: \"", "+", "(", "bottom", "-", "top", ")", "+", "\"px\"", ")", ")", ";", "}", "function", "drawForLine", "(", "line", ",", "fromArg", ",", "toArg", ")", "{", "var", "lineObj", "=", "getLine", "(", "doc", ",", "line", ")", ";", "var", "lineLen", "=", "lineObj", ".", "text", ".", "length", ";", "var", "start", ",", "end", ";", "function", "coords", "(", "ch", ",", "bias", ")", "{", "return", "_charCoords", "(", "cm", ",", "Pos", "(", "line", ",", "ch", ")", ",", "\"div\"", ",", "lineObj", ",", "bias", ")", ";", "}", "function", "wrapX", "(", "pos", ",", "dir", ",", "side", ")", "{", "var", "extent", "=", "wrappedLineExtentChar", "(", "cm", ",", "lineObj", ",", "null", ",", "pos", ")", ";", "var", "prop", "=", "dir", "==", "\"ltr\"", "==", "(", "side", "==", "\"after\"", ")", "?", "\"left\"", ":", "\"right\"", ";", "var", "ch", "=", "side", "==", "\"after\"", "?", "extent", ".", "begin", ":", "extent", ".", "end", "-", "(", "/", "\\s", "/", ".", "test", "(", "lineObj", ".", "text", ".", "charAt", "(", "extent", ".", "end", "-", "1", ")", ")", "?", "2", ":", "1", ")", ";", "return", "coords", "(", "ch", ",", "prop", ")", "[", "prop", "]", ";", "}", "var", "order", "=", "getOrder", "(", "lineObj", ",", "doc", ".", "direction", ")", ";", "iterateBidiSections", "(", "order", ",", "fromArg", "||", "0", ",", "toArg", "==", "null", "?", "lineLen", ":", "toArg", ",", "function", "(", "from", ",", "to", ",", "dir", ",", "i", ")", "{", "var", "ltr", "=", "dir", "==", "\"ltr\"", ";", "var", "fromPos", "=", "coords", "(", "from", ",", "ltr", "?", "\"left\"", ":", "\"right\"", ")", ";", "var", "toPos", "=", "coords", "(", "to", "-", "1", ",", "ltr", "?", "\"right\"", ":", "\"left\"", ")", ";", "var", "openStart", "=", "fromArg", "==", "null", "&&", "from", "==", "0", ",", "openEnd", "=", "toArg", "==", "null", "&&", "to", "==", "lineLen", ";", "var", "first", "=", "i", "==", "0", ",", "last", "=", "!", "order", "||", "i", "==", "order", ".", "length", "-", "1", ";", "if", "(", "toPos", ".", "top", "-", "fromPos", ".", "top", "<=", "3", ")", "{", "// Single line", "var", "openLeft", "=", "(", "docLTR", "?", "openStart", ":", "openEnd", ")", "&&", "first", ";", "var", "openRight", "=", "(", "docLTR", "?", "openEnd", ":", "openStart", ")", "&&", "last", ";", "var", "left", "=", "openLeft", "?", "leftSide", ":", "(", "ltr", "?", "fromPos", ":", "toPos", ")", ".", "left", ";", "var", "right", "=", "openRight", "?", "rightSide", ":", "(", "ltr", "?", "toPos", ":", "fromPos", ")", ".", "right", ";", "add", "(", "left", ",", "fromPos", ".", "top", ",", "right", "-", "left", ",", "fromPos", ".", "bottom", ")", ";", "}", "else", "{", "// Multiple lines", "var", "topLeft", ",", "topRight", ",", "botLeft", ",", "botRight", ";", "if", "(", "ltr", ")", "{", "topLeft", "=", "docLTR", "&&", "openStart", "&&", "first", "?", "leftSide", ":", "fromPos", ".", "left", ";", "topRight", "=", "docLTR", "?", "rightSide", ":", "wrapX", "(", "from", ",", "dir", ",", "\"before\"", ")", ";", "botLeft", "=", "docLTR", "?", "leftSide", ":", "wrapX", "(", "to", ",", "dir", ",", "\"after\"", ")", ";", "botRight", "=", "docLTR", "&&", "openEnd", "&&", "last", "?", "rightSide", ":", "toPos", ".", "right", ";", "}", "else", "{", "topLeft", "=", "!", "docLTR", "?", "leftSide", ":", "wrapX", "(", "from", ",", "dir", ",", "\"before\"", ")", ";", "topRight", "=", "!", "docLTR", "&&", "openStart", "&&", "first", "?", "rightSide", ":", "fromPos", ".", "right", ";", "botLeft", "=", "!", "docLTR", "&&", "openEnd", "&&", "last", "?", "leftSide", ":", "toPos", ".", "left", ";", "botRight", "=", "!", "docLTR", "?", "rightSide", ":", "wrapX", "(", "to", ",", "dir", ",", "\"after\"", ")", ";", "}", "add", "(", "topLeft", ",", "fromPos", ".", "top", ",", "topRight", "-", "topLeft", ",", "fromPos", ".", "bottom", ")", ";", "if", "(", "fromPos", ".", "bottom", "<", "toPos", ".", "top", ")", "{", "add", "(", "leftSide", ",", "fromPos", ".", "bottom", ",", "null", ",", "toPos", ".", "top", ")", ";", "}", "add", "(", "botLeft", ",", "toPos", ".", "top", ",", "botRight", "-", "botLeft", ",", "toPos", ".", "bottom", ")", ";", "}", "if", "(", "!", "start", "||", "cmpCoords", "(", "fromPos", ",", "start", ")", "<", "0", ")", "{", "start", "=", "fromPos", ";", "}", "if", "(", "cmpCoords", "(", "toPos", ",", "start", ")", "<", "0", ")", "{", "start", "=", "toPos", ";", "}", "if", "(", "!", "end", "||", "cmpCoords", "(", "fromPos", ",", "end", ")", "<", "0", ")", "{", "end", "=", "fromPos", ";", "}", "if", "(", "cmpCoords", "(", "toPos", ",", "end", ")", "<", "0", ")", "{", "end", "=", "toPos", ";", "}", "}", ")", ";", "return", "{", "start", ":", "start", ",", "end", ":", "end", "}", ";", "}", "var", "sFrom", "=", "range$$1", ".", "from", "(", ")", ",", "sTo", "=", "range$$1", ".", "to", "(", ")", ";", "if", "(", "sFrom", ".", "line", "==", "sTo", ".", "line", ")", "{", "drawForLine", "(", "sFrom", ".", "line", ",", "sFrom", ".", "ch", ",", "sTo", ".", "ch", ")", ";", "}", "else", "{", "var", "fromLine", "=", "getLine", "(", "doc", ",", "sFrom", ".", "line", ")", ",", "toLine", "=", "getLine", "(", "doc", ",", "sTo", ".", "line", ")", ";", "var", "singleVLine", "=", "visualLine", "(", "fromLine", ")", "==", "visualLine", "(", "toLine", ")", ";", "var", "leftEnd", "=", "drawForLine", "(", "sFrom", ".", "line", ",", "sFrom", ".", "ch", ",", "singleVLine", "?", "fromLine", ".", "text", ".", "length", "+", "1", ":", "null", ")", ".", "end", ";", "var", "rightStart", "=", "drawForLine", "(", "sTo", ".", "line", ",", "singleVLine", "?", "0", ":", "null", ",", "sTo", ".", "ch", ")", ".", "start", ";", "if", "(", "singleVLine", ")", "{", "if", "(", "leftEnd", ".", "top", "<", "rightStart", ".", "top", "-", "2", ")", "{", "add", "(", "leftEnd", ".", "right", ",", "leftEnd", ".", "top", ",", "null", ",", "leftEnd", ".", "bottom", ")", ";", "add", "(", "leftSide", ",", "rightStart", ".", "top", ",", "rightStart", ".", "left", ",", "rightStart", ".", "bottom", ")", ";", "}", "else", "{", "add", "(", "leftEnd", ".", "right", ",", "leftEnd", ".", "top", ",", "rightStart", ".", "left", "-", "leftEnd", ".", "right", ",", "leftEnd", ".", "bottom", ")", ";", "}", "}", "if", "(", "leftEnd", ".", "bottom", "<", "rightStart", ".", "top", ")", "{", "add", "(", "leftSide", ",", "leftEnd", ".", "bottom", ",", "null", ",", "rightStart", ".", "top", ")", ";", "}", "}", "output", ".", "appendChild", "(", "fragment", ")", ";", "}" ]
Draws the given range as a highlighted selection
[ "Draws", "the", "given", "range", "as", "a", "highlighted", "selection" ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L866-L868
20,616
sociomantic-tsunami/nessie-ui
docs/assets/app.js
doHandleBinding
function doHandleBinding(cm,bound,dropShift){if(typeof bound=="string"){bound=commands[bound];if(!bound){return false;}}// Ensure previous input has been read, so that the handler sees a // consistent view of the document cm.display.input.ensurePolled();var prevShift=cm.display.shift,done=false;try{if(cm.isReadOnly()){cm.state.suppressEdits=true;}if(dropShift){cm.display.shift=false;}done=bound(cm)!=Pass;}finally{cm.display.shift=prevShift;cm.state.suppressEdits=false;}return done;}
javascript
function doHandleBinding(cm,bound,dropShift){if(typeof bound=="string"){bound=commands[bound];if(!bound){return false;}}// Ensure previous input has been read, so that the handler sees a // consistent view of the document cm.display.input.ensurePolled();var prevShift=cm.display.shift,done=false;try{if(cm.isReadOnly()){cm.state.suppressEdits=true;}if(dropShift){cm.display.shift=false;}done=bound(cm)!=Pass;}finally{cm.display.shift=prevShift;cm.state.suppressEdits=false;}return done;}
[ "function", "doHandleBinding", "(", "cm", ",", "bound", ",", "dropShift", ")", "{", "if", "(", "typeof", "bound", "==", "\"string\"", ")", "{", "bound", "=", "commands", "[", "bound", "]", ";", "if", "(", "!", "bound", ")", "{", "return", "false", ";", "}", "}", "// Ensure previous input has been read, so that the handler sees a", "// consistent view of the document", "cm", ".", "display", ".", "input", ".", "ensurePolled", "(", ")", ";", "var", "prevShift", "=", "cm", ".", "display", ".", "shift", ",", "done", "=", "false", ";", "try", "{", "if", "(", "cm", ".", "isReadOnly", "(", ")", ")", "{", "cm", ".", "state", ".", "suppressEdits", "=", "true", ";", "}", "if", "(", "dropShift", ")", "{", "cm", ".", "display", ".", "shift", "=", "false", ";", "}", "done", "=", "bound", "(", "cm", ")", "!=", "Pass", ";", "}", "finally", "{", "cm", ".", "display", ".", "shift", "=", "prevShift", ";", "cm", ".", "state", ".", "suppressEdits", "=", "false", ";", "}", "return", "done", ";", "}" ]
Run a handler that was bound to a key.
[ "Run", "a", "handler", "that", "was", "bound", "to", "a", "key", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L1296-L1298
20,617
sociomantic-tsunami/nessie-ui
docs/assets/app.js
bidiSimplify
function bidiSimplify(cm,range$$1){var anchor=range$$1.anchor;var head=range$$1.head;var anchorLine=getLine(cm.doc,anchor.line);if(cmp(anchor,head)==0&&anchor.sticky==head.sticky){return range$$1;}var order=getOrder(anchorLine);if(!order){return range$$1;}var index=getBidiPartAt(order,anchor.ch,anchor.sticky),part=order[index];if(part.from!=anchor.ch&&part.to!=anchor.ch){return range$$1;}var boundary=index+(part.from==anchor.ch==(part.level!=1)?0:1);if(boundary==0||boundary==order.length){return range$$1;}// Compute the relative visual position of the head compared to the // anchor (<0 is to the left, >0 to the right) var leftSide;if(head.line!=anchor.line){leftSide=(head.line-anchor.line)*(cm.doc.direction=="ltr"?1:-1)>0;}else{var headIndex=getBidiPartAt(order,head.ch,head.sticky);var dir=headIndex-index||(head.ch-anchor.ch)*(part.level==1?-1:1);if(headIndex==boundary-1||headIndex==boundary){leftSide=dir<0;}else{leftSide=dir>0;}}var usePart=order[boundary+(leftSide?-1:0)];var from=leftSide==(usePart.level==1);var ch=from?usePart.from:usePart.to,sticky=from?"after":"before";return anchor.ch==ch&&anchor.sticky==sticky?range$$1:new Range(new Pos(anchor.line,ch,sticky),head);}
javascript
function bidiSimplify(cm,range$$1){var anchor=range$$1.anchor;var head=range$$1.head;var anchorLine=getLine(cm.doc,anchor.line);if(cmp(anchor,head)==0&&anchor.sticky==head.sticky){return range$$1;}var order=getOrder(anchorLine);if(!order){return range$$1;}var index=getBidiPartAt(order,anchor.ch,anchor.sticky),part=order[index];if(part.from!=anchor.ch&&part.to!=anchor.ch){return range$$1;}var boundary=index+(part.from==anchor.ch==(part.level!=1)?0:1);if(boundary==0||boundary==order.length){return range$$1;}// Compute the relative visual position of the head compared to the // anchor (<0 is to the left, >0 to the right) var leftSide;if(head.line!=anchor.line){leftSide=(head.line-anchor.line)*(cm.doc.direction=="ltr"?1:-1)>0;}else{var headIndex=getBidiPartAt(order,head.ch,head.sticky);var dir=headIndex-index||(head.ch-anchor.ch)*(part.level==1?-1:1);if(headIndex==boundary-1||headIndex==boundary){leftSide=dir<0;}else{leftSide=dir>0;}}var usePart=order[boundary+(leftSide?-1:0)];var from=leftSide==(usePart.level==1);var ch=from?usePart.from:usePart.to,sticky=from?"after":"before";return anchor.ch==ch&&anchor.sticky==sticky?range$$1:new Range(new Pos(anchor.line,ch,sticky),head);}
[ "function", "bidiSimplify", "(", "cm", ",", "range$$1", ")", "{", "var", "anchor", "=", "range$$1", ".", "anchor", ";", "var", "head", "=", "range$$1", ".", "head", ";", "var", "anchorLine", "=", "getLine", "(", "cm", ".", "doc", ",", "anchor", ".", "line", ")", ";", "if", "(", "cmp", "(", "anchor", ",", "head", ")", "==", "0", "&&", "anchor", ".", "sticky", "==", "head", ".", "sticky", ")", "{", "return", "range$$1", ";", "}", "var", "order", "=", "getOrder", "(", "anchorLine", ")", ";", "if", "(", "!", "order", ")", "{", "return", "range$$1", ";", "}", "var", "index", "=", "getBidiPartAt", "(", "order", ",", "anchor", ".", "ch", ",", "anchor", ".", "sticky", ")", ",", "part", "=", "order", "[", "index", "]", ";", "if", "(", "part", ".", "from", "!=", "anchor", ".", "ch", "&&", "part", ".", "to", "!=", "anchor", ".", "ch", ")", "{", "return", "range$$1", ";", "}", "var", "boundary", "=", "index", "+", "(", "part", ".", "from", "==", "anchor", ".", "ch", "==", "(", "part", ".", "level", "!=", "1", ")", "?", "0", ":", "1", ")", ";", "if", "(", "boundary", "==", "0", "||", "boundary", "==", "order", ".", "length", ")", "{", "return", "range$$1", ";", "}", "// Compute the relative visual position of the head compared to the", "// anchor (<0 is to the left, >0 to the right)", "var", "leftSide", ";", "if", "(", "head", ".", "line", "!=", "anchor", ".", "line", ")", "{", "leftSide", "=", "(", "head", ".", "line", "-", "anchor", ".", "line", ")", "*", "(", "cm", ".", "doc", ".", "direction", "==", "\"ltr\"", "?", "1", ":", "-", "1", ")", ">", "0", ";", "}", "else", "{", "var", "headIndex", "=", "getBidiPartAt", "(", "order", ",", "head", ".", "ch", ",", "head", ".", "sticky", ")", ";", "var", "dir", "=", "headIndex", "-", "index", "||", "(", "head", ".", "ch", "-", "anchor", ".", "ch", ")", "*", "(", "part", ".", "level", "==", "1", "?", "-", "1", ":", "1", ")", ";", "if", "(", "headIndex", "==", "boundary", "-", "1", "||", "headIndex", "==", "boundary", ")", "{", "leftSide", "=", "dir", "<", "0", ";", "}", "else", "{", "leftSide", "=", "dir", ">", "0", ";", "}", "}", "var", "usePart", "=", "order", "[", "boundary", "+", "(", "leftSide", "?", "-", "1", ":", "0", ")", "]", ";", "var", "from", "=", "leftSide", "==", "(", "usePart", ".", "level", "==", "1", ")", ";", "var", "ch", "=", "from", "?", "usePart", ".", "from", ":", "usePart", ".", "to", ",", "sticky", "=", "from", "?", "\"after\"", ":", "\"before\"", ";", "return", "anchor", ".", "ch", "==", "ch", "&&", "anchor", ".", "sticky", "==", "sticky", "?", "range$$1", ":", "new", "Range", "(", "new", "Pos", "(", "anchor", ".", "line", ",", "ch", ",", "sticky", ")", ",", "head", ")", ";", "}" ]
Used when mouse-selecting to adjust the anchor to the proper side of a bidi jump depending on the visual position of the head.
[ "Used", "when", "mouse", "-", "selecting", "to", "adjust", "the", "anchor", "to", "the", "proper", "side", "of", "a", "bidi", "jump", "depending", "on", "the", "visual", "position", "of", "the", "head", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L1329-L1331
20,618
sociomantic-tsunami/nessie-ui
docs/assets/app.js
prepareSelectAllHack
function prepareSelectAllHack(){if(te.selectionStart!=null){var selected=cm.somethingSelected();var extval='\u200B'+(selected?te.value:"");te.value='\u21DA';// Used to catch context-menu undo te.value=extval;input.prevInput=selected?"":'\u200B';te.selectionStart=1;te.selectionEnd=extval.length;// Re-set this, in case some other handler touched the // selection in the meantime. display.selForContextMenu=cm.doc.sel;}}
javascript
function prepareSelectAllHack(){if(te.selectionStart!=null){var selected=cm.somethingSelected();var extval='\u200B'+(selected?te.value:"");te.value='\u21DA';// Used to catch context-menu undo te.value=extval;input.prevInput=selected?"":'\u200B';te.selectionStart=1;te.selectionEnd=extval.length;// Re-set this, in case some other handler touched the // selection in the meantime. display.selForContextMenu=cm.doc.sel;}}
[ "function", "prepareSelectAllHack", "(", ")", "{", "if", "(", "te", ".", "selectionStart", "!=", "null", ")", "{", "var", "selected", "=", "cm", ".", "somethingSelected", "(", ")", ";", "var", "extval", "=", "'\\u200B'", "+", "(", "selected", "?", "te", ".", "value", ":", "\"\"", ")", ";", "te", ".", "value", "=", "'\\u21DA'", ";", "// Used to catch context-menu undo", "te", ".", "value", "=", "extval", ";", "input", ".", "prevInput", "=", "selected", "?", "\"\"", ":", "'\\u200B'", ";", "te", ".", "selectionStart", "=", "1", ";", "te", ".", "selectionEnd", "=", "extval", ".", "length", ";", "// Re-set this, in case some other handler touched the", "// selection in the meantime.", "display", ".", "selForContextMenu", "=", "cm", ".", "doc", ".", "sel", ";", "}", "}" ]
Select-all will be greyed out if there's nothing to select, so this adds a zero-width space so that we can later check whether it got selected.
[ "Select", "-", "all", "will", "be", "greyed", "out", "if", "there", "s", "nothing", "to", "select", "so", "this", "adds", "a", "zero", "-", "width", "space", "so", "that", "we", "can", "later", "check", "whether", "it", "got", "selected", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L1473-L1476
20,619
sociomantic-tsunami/nessie-ui
docs/assets/app.js
getClosestInstanceFromNode
function getClosestInstanceFromNode(node) { if (node[internalInstanceKey]) { return node[internalInstanceKey]; } // Walk up the tree until we find an ancestor whose instance we have cached. var parents = []; while (!node[internalInstanceKey]) { parents.push(node); if (node.parentNode) { node = node.parentNode; } else { // Top of the tree. This node must not be part of a React tree (or is // unmounted, potentially). return null; } } var closest; var inst; for (; node && (inst = node[internalInstanceKey]); node = parents.pop()) { closest = inst; if (parents.length) { precacheChildNodes(inst, node); } } return closest; }
javascript
function getClosestInstanceFromNode(node) { if (node[internalInstanceKey]) { return node[internalInstanceKey]; } // Walk up the tree until we find an ancestor whose instance we have cached. var parents = []; while (!node[internalInstanceKey]) { parents.push(node); if (node.parentNode) { node = node.parentNode; } else { // Top of the tree. This node must not be part of a React tree (or is // unmounted, potentially). return null; } } var closest; var inst; for (; node && (inst = node[internalInstanceKey]); node = parents.pop()) { closest = inst; if (parents.length) { precacheChildNodes(inst, node); } } return closest; }
[ "function", "getClosestInstanceFromNode", "(", "node", ")", "{", "if", "(", "node", "[", "internalInstanceKey", "]", ")", "{", "return", "node", "[", "internalInstanceKey", "]", ";", "}", "// Walk up the tree until we find an ancestor whose instance we have cached.", "var", "parents", "=", "[", "]", ";", "while", "(", "!", "node", "[", "internalInstanceKey", "]", ")", "{", "parents", ".", "push", "(", "node", ")", ";", "if", "(", "node", ".", "parentNode", ")", "{", "node", "=", "node", ".", "parentNode", ";", "}", "else", "{", "// Top of the tree. This node must not be part of a React tree (or is", "// unmounted, potentially).", "return", "null", ";", "}", "}", "var", "closest", ";", "var", "inst", ";", "for", "(", ";", "node", "&&", "(", "inst", "=", "node", "[", "internalInstanceKey", "]", ")", ";", "node", "=", "parents", ".", "pop", "(", ")", ")", "{", "closest", "=", "inst", ";", "if", "(", "parents", ".", "length", ")", "{", "precacheChildNodes", "(", "inst", ",", "node", ")", ";", "}", "}", "return", "closest", ";", "}" ]
Given a DOM node, return the closest ReactDOMComponent or ReactDOMTextComponent instance ancestor.
[ "Given", "a", "DOM", "node", "return", "the", "closest", "ReactDOMComponent", "or", "ReactDOMTextComponent", "instance", "ancestor", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L5857-L5885
20,620
sociomantic-tsunami/nessie-ui
docs/assets/app.js
createRoutesFromReactChildren
function createRoutesFromReactChildren(children, parentRoute) { var routes = []; _react2.default.Children.forEach(children, function (element) { if (_react2.default.isValidElement(element)) { // Component classes may have a static create* method. if (element.type.createRouteFromReactElement) { var route = element.type.createRouteFromReactElement(element, parentRoute); if (route) routes.push(route); } else { routes.push(createRouteFromReactElement(element)); } } }); return routes; }
javascript
function createRoutesFromReactChildren(children, parentRoute) { var routes = []; _react2.default.Children.forEach(children, function (element) { if (_react2.default.isValidElement(element)) { // Component classes may have a static create* method. if (element.type.createRouteFromReactElement) { var route = element.type.createRouteFromReactElement(element, parentRoute); if (route) routes.push(route); } else { routes.push(createRouteFromReactElement(element)); } } }); return routes; }
[ "function", "createRoutesFromReactChildren", "(", "children", ",", "parentRoute", ")", "{", "var", "routes", "=", "[", "]", ";", "_react2", ".", "default", ".", "Children", ".", "forEach", "(", "children", ",", "function", "(", "element", ")", "{", "if", "(", "_react2", ".", "default", ".", "isValidElement", "(", "element", ")", ")", "{", "// Component classes may have a static create* method.", "if", "(", "element", ".", "type", ".", "createRouteFromReactElement", ")", "{", "var", "route", "=", "element", ".", "type", ".", "createRouteFromReactElement", "(", "element", ",", "parentRoute", ")", ";", "if", "(", "route", ")", "routes", ".", "push", "(", "route", ")", ";", "}", "else", "{", "routes", ".", "push", "(", "createRouteFromReactElement", "(", "element", ")", ")", ";", "}", "}", "}", ")", ";", "return", "routes", ";", "}" ]
Creates and returns a routes object from the given ReactChildren. JSX provides a convenient way to visualize how routes in the hierarchy are nested. import { Route, createRoutesFromReactChildren } from 'react-router' const routes = createRoutesFromReactChildren( <Route component={App}> <Route path="home" component={Dashboard}/> <Route path="news" component={NewsFeed}/> </Route> ) Note: This method is automatically used when you provide <Route> children to a <Router> component.
[ "Creates", "and", "returns", "a", "routes", "object", "from", "the", "given", "ReactChildren", ".", "JSX", "provides", "a", "convenient", "way", "to", "visualize", "how", "routes", "in", "the", "hierarchy", "are", "nested", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L6833-L6850
20,621
sociomantic-tsunami/nessie-ui
docs/assets/app.js
createRoutes
function createRoutes(routes) { if (isReactChildren(routes)) { routes = createRoutesFromReactChildren(routes); } else if (routes && !Array.isArray(routes)) { routes = [routes]; } return routes; }
javascript
function createRoutes(routes) { if (isReactChildren(routes)) { routes = createRoutesFromReactChildren(routes); } else if (routes && !Array.isArray(routes)) { routes = [routes]; } return routes; }
[ "function", "createRoutes", "(", "routes", ")", "{", "if", "(", "isReactChildren", "(", "routes", ")", ")", "{", "routes", "=", "createRoutesFromReactChildren", "(", "routes", ")", ";", "}", "else", "if", "(", "routes", "&&", "!", "Array", ".", "isArray", "(", "routes", ")", ")", "{", "routes", "=", "[", "routes", "]", ";", "}", "return", "routes", ";", "}" ]
Creates and returns an array of routes from the given object which may be a JSX route, a plain object route, or an array of either.
[ "Creates", "and", "returns", "an", "array", "of", "routes", "from", "the", "given", "object", "which", "may", "be", "a", "JSX", "route", "a", "plain", "object", "route", "or", "an", "array", "of", "either", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L6856-L6864
20,622
sociomantic-tsunami/nessie-ui
docs/assets/app.js
oneArgumentPooler
function oneArgumentPooler(copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }
javascript
function oneArgumentPooler(copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }
[ "function", "oneArgumentPooler", "(", "copyFieldsFrom", ")", "{", "var", "Klass", "=", "this", ";", "if", "(", "Klass", ".", "instancePool", ".", "length", ")", "{", "var", "instance", "=", "Klass", ".", "instancePool", ".", "pop", "(", ")", ";", "Klass", ".", "call", "(", "instance", ",", "copyFieldsFrom", ")", ";", "return", "instance", ";", "}", "else", "{", "return", "new", "Klass", "(", "copyFieldsFrom", ")", ";", "}", "}" ]
Static poolers. Several custom versions for each potential number of arguments. A completely generic pooler is easy to implement, but would require accessing the `arguments` object. In each of these, `this` refers to the Class itself, not an instance. If any others are needed, simply add them here, or in their own files.
[ "Static", "poolers", ".", "Several", "custom", "versions", "for", "each", "potential", "number", "of", "arguments", ".", "A", "completely", "generic", "pooler", "is", "easy", "to", "implement", "but", "would", "require", "accessing", "the", "arguments", "object", ".", "In", "each", "of", "these", "this", "refers", "to", "the", "Class", "itself", "not", "an", "instance", ".", "If", "any", "others", "are", "needed", "simply", "add", "them", "here", "or", "in", "their", "own", "files", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L7015-L7024
20,623
sociomantic-tsunami/nessie-ui
docs/assets/app.js
accumulateDispatches
function accumulateDispatches(inst, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(inst, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } }
javascript
function accumulateDispatches(inst, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(inst, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } }
[ "function", "accumulateDispatches", "(", "inst", ",", "ignoredDirection", ",", "event", ")", "{", "if", "(", "event", "&&", "event", ".", "dispatchConfig", ".", "registrationName", ")", "{", "var", "registrationName", "=", "event", ".", "dispatchConfig", ".", "registrationName", ";", "var", "listener", "=", "getListener", "(", "inst", ",", "registrationName", ")", ";", "if", "(", "listener", ")", "{", "event", ".", "_dispatchListeners", "=", "accumulateInto", "(", "event", ".", "_dispatchListeners", ",", "listener", ")", ";", "event", ".", "_dispatchInstances", "=", "accumulateInto", "(", "event", ".", "_dispatchInstances", ",", "inst", ")", ";", "}", "}", "}" ]
Accumulates without regard to direction, does not look for phased registration names. Same as `accumulateDirectDispatchesSingle` but without requiring that the `dispatchMarker` be the same as the dispatched ID.
[ "Accumulates", "without", "regard", "to", "direction", "does", "not", "look", "for", "phased", "registration", "names", ".", "Same", "as", "accumulateDirectDispatchesSingle", "but", "without", "requiring", "that", "the", "dispatchMarker", "be", "the", "same", "as", "the", "dispatched", "ID", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L7940-L7949
20,624
sociomantic-tsunami/nessie-ui
docs/assets/app.js
listenBefore
function listenBefore(hook) { return history.listenBefore(function (location, callback) { _runTransitionHook2['default'](hook, addQuery(location), callback); }); }
javascript
function listenBefore(hook) { return history.listenBefore(function (location, callback) { _runTransitionHook2['default'](hook, addQuery(location), callback); }); }
[ "function", "listenBefore", "(", "hook", ")", "{", "return", "history", ".", "listenBefore", "(", "function", "(", "location", ",", "callback", ")", "{", "_runTransitionHook2", "[", "'default'", "]", "(", "hook", ",", "addQuery", "(", "location", ")", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Override all read methods with query-aware versions.
[ "Override", "all", "read", "methods", "with", "query", "-", "aware", "versions", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L9229-L9233
20,625
sociomantic-tsunami/nessie-ui
docs/assets/app.js
beautifyCode
function beautifyCode(str) { var beautifulStr = str; try { beautifulStr = (0, _jsBeautify.html)(str, beautifySettings); } catch (err) { console.error('Beautify error:', err.message); } return beautifulStr; }
javascript
function beautifyCode(str) { var beautifulStr = str; try { beautifulStr = (0, _jsBeautify.html)(str, beautifySettings); } catch (err) { console.error('Beautify error:', err.message); } return beautifulStr; }
[ "function", "beautifyCode", "(", "str", ")", "{", "var", "beautifulStr", "=", "str", ";", "try", "{", "beautifulStr", "=", "(", "0", ",", "_jsBeautify", ".", "html", ")", "(", "str", ",", "beautifySettings", ")", ";", "}", "catch", "(", "err", ")", "{", "console", ".", "error", "(", "'Beautify error:'", ",", "err", ".", "message", ")", ";", "}", "return", "beautifulStr", ";", "}" ]
Try to beautify a HTML or JSX string using js-beautify; return original string if unsuccessful @param {String} str - a string containing HTML or JSX @return {String}
[ "Try", "to", "beautify", "a", "HTML", "or", "JSX", "string", "using", "js", "-", "beautify", ";", "return", "original", "string", "if", "unsuccessful" ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L9519-L9529
20,626
sociomantic-tsunami/nessie-ui
docs/assets/app.js
propsToString
function propsToString() { var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var defaultProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var propStr = ''; Object.keys(props).map(function (prop) { var propVal = props[prop]; if (prop !== 'children' && propVal !== defaultProps[prop]) { propStr += ' ' + prop + '='; if (typeof propVal === 'string') { propStr += '"' + propVal + '"'; } else { propStr += '{' + JSON.stringify(propVal) + '}'; } } }); return propStr; }
javascript
function propsToString() { var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var defaultProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var propStr = ''; Object.keys(props).map(function (prop) { var propVal = props[prop]; if (prop !== 'children' && propVal !== defaultProps[prop]) { propStr += ' ' + prop + '='; if (typeof propVal === 'string') { propStr += '"' + propVal + '"'; } else { propStr += '{' + JSON.stringify(propVal) + '}'; } } }); return propStr; }
[ "function", "propsToString", "(", ")", "{", "var", "props", "=", "arguments", ".", "length", ">", "0", "&&", "arguments", "[", "0", "]", "!==", "undefined", "?", "arguments", "[", "0", "]", ":", "{", "}", ";", "var", "defaultProps", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "{", "}", ";", "var", "propStr", "=", "''", ";", "Object", ".", "keys", "(", "props", ")", ".", "map", "(", "function", "(", "prop", ")", "{", "var", "propVal", "=", "props", "[", "prop", "]", ";", "if", "(", "prop", "!==", "'children'", "&&", "propVal", "!==", "defaultProps", "[", "prop", "]", ")", "{", "propStr", "+=", "' '", "+", "prop", "+", "'='", ";", "if", "(", "typeof", "propVal", "===", "'string'", ")", "{", "propStr", "+=", "'\"'", "+", "propVal", "+", "'\"'", ";", "}", "else", "{", "propStr", "+=", "'{'", "+", "JSON", ".", "stringify", "(", "propVal", ")", "+", "'}'", ";", "}", "}", "}", ")", ";", "return", "propStr", ";", "}" ]
Converts an object of props to a string, excluding defaultProps @param {Object} props - an object of React props @param {Object} defaultProps - an object of defaults @return {String}
[ "Converts", "an", "object", "of", "props", "to", "a", "string", "excluding", "defaultProps" ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L9680-L9701
20,627
sociomantic-tsunami/nessie-ui
docs/assets/app.js
invokeGuardedCallback
function invokeGuardedCallback(name, func, a) { try { func(a); } catch (x) { if (caughtError === null) { caughtError = x; } } }
javascript
function invokeGuardedCallback(name, func, a) { try { func(a); } catch (x) { if (caughtError === null) { caughtError = x; } } }
[ "function", "invokeGuardedCallback", "(", "name", ",", "func", ",", "a", ")", "{", "try", "{", "func", "(", "a", ")", ";", "}", "catch", "(", "x", ")", "{", "if", "(", "caughtError", "===", "null", ")", "{", "caughtError", "=", "x", ";", "}", "}", "}" ]
Call a function while guarding against errors that happens within it. @param {String} name of the guard to use for logging or debugging @param {Function} func The function to invoke @param {*} a First argument @param {*} b Second argument
[ "Call", "a", "function", "while", "guarding", "against", "errors", "that", "happens", "within", "it", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L15982-L15990
20,628
sociomantic-tsunami/nessie-ui
docs/assets/app.js
unescape
function unescape(key) { var unescapeRegex = /(=0|=2)/g; var unescaperLookup = { '=0': '=', '=2': ':' }; var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1); return ('' + keySubstring).replace(unescapeRegex, function (match) { return unescaperLookup[match]; }); }
javascript
function unescape(key) { var unescapeRegex = /(=0|=2)/g; var unescaperLookup = { '=0': '=', '=2': ':' }; var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1); return ('' + keySubstring).replace(unescapeRegex, function (match) { return unescaperLookup[match]; }); }
[ "function", "unescape", "(", "key", ")", "{", "var", "unescapeRegex", "=", "/", "(=0|=2)", "/", "g", ";", "var", "unescaperLookup", "=", "{", "'=0'", ":", "'='", ",", "'=2'", ":", "':'", "}", ";", "var", "keySubstring", "=", "key", "[", "0", "]", "===", "'.'", "&&", "key", "[", "1", "]", "===", "'$'", "?", "key", ".", "substring", "(", "2", ")", ":", "key", ".", "substring", "(", "1", ")", ";", "return", "(", "''", "+", "keySubstring", ")", ".", "replace", "(", "unescapeRegex", ",", "function", "(", "match", ")", "{", "return", "unescaperLookup", "[", "match", "]", ";", "}", ")", ";", "}" ]
Unescape and unwrap key for human-readable display @param {string} key to unescape. @return {string} the unescaped key.
[ "Unescape", "and", "unwrap", "key", "for", "human", "-", "readable", "display" ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L17251-L17262
20,629
sociomantic-tsunami/nessie-ui
docs/assets/app.js
findOwnerStack
function findOwnerStack(instance) { if (!instance) { return []; } var stack = []; do { stack.push(instance); } while (instance = instance._currentElement._owner); stack.reverse(); return stack; }
javascript
function findOwnerStack(instance) { if (!instance) { return []; } var stack = []; do { stack.push(instance); } while (instance = instance._currentElement._owner); stack.reverse(); return stack; }
[ "function", "findOwnerStack", "(", "instance", ")", "{", "if", "(", "!", "instance", ")", "{", "return", "[", "]", ";", "}", "var", "stack", "=", "[", "]", ";", "do", "{", "stack", ".", "push", "(", "instance", ")", ";", "}", "while", "(", "instance", "=", "instance", ".", "_currentElement", ".", "_owner", ")", ";", "stack", ".", "reverse", "(", ")", ";", "return", "stack", ";", "}" ]
Given a ReactCompositeComponent instance, return a list of its recursive owners, starting at the root and ending with the instance itself.
[ "Given", "a", "ReactCompositeComponent", "instance", "return", "a", "list", "of", "its", "recursive", "owners", "starting", "at", "the", "root", "and", "ending", "with", "the", "instance", "itself", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L17536-L17547
20,630
sociomantic-tsunami/nessie-ui
docs/assets/app.js
warning
function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); /* eslint-disable no-empty */ } catch (e) {} /* eslint-enable no-empty */ }
javascript
function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); /* eslint-disable no-empty */ } catch (e) {} /* eslint-enable no-empty */ }
[ "function", "warning", "(", "message", ")", "{", "/* eslint-disable no-console */", "if", "(", "typeof", "console", "!==", "'undefined'", "&&", "typeof", "console", ".", "error", "===", "'function'", ")", "{", "console", ".", "error", "(", "message", ")", ";", "}", "/* eslint-enable no-console */", "try", "{", "// This error was thrown as a convenience so that if you enable", "// \"break on all exceptions\" in your console,", "// it would pause the execution at this line.", "throw", "new", "Error", "(", "message", ")", ";", "/* eslint-disable no-empty */", "}", "catch", "(", "e", ")", "{", "}", "/* eslint-enable no-empty */", "}" ]
Prints a warning in the console if it exists. @param {String} message The warning message. @returns {void}
[ "Prints", "a", "warning", "in", "the", "console", "if", "it", "exists", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L17792-L17806
20,631
sociomantic-tsunami/nessie-ui
docs/assets/app.js
replaceReducer
function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } currentReducer = nextReducer; dispatch({ type: ActionTypes.INIT }); }
javascript
function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } currentReducer = nextReducer; dispatch({ type: ActionTypes.INIT }); }
[ "function", "replaceReducer", "(", "nextReducer", ")", "{", "if", "(", "typeof", "nextReducer", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'Expected the nextReducer to be a function.'", ")", ";", "}", "currentReducer", "=", "nextReducer", ";", "dispatch", "(", "{", "type", ":", "ActionTypes", ".", "INIT", "}", ")", ";", "}" ]
Replaces the reducer currently used by the store to calculate the state. You might need this if your app implements code splitting and you want to load some of the reducers dynamically. You might also need this if you implement a hot reloading mechanism for Redux. @param {Function} nextReducer The reducer for the store to use instead. @returns {void}
[ "Replaces", "the", "reducer", "currently", "used", "by", "the", "store", "to", "calculate", "the", "state", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L18019-L18026
20,632
sociomantic-tsunami/nessie-ui
docs/assets/app.js
subscribe
function subscribe(observer) { if ((typeof observer === 'undefined' ? 'undefined' : _typeof(observer)) !== 'object') { throw new TypeError('Expected the observer to be an object.'); } function observeState() { if (observer.next) { observer.next(getState()); } } observeState(); var unsubscribe = outerSubscribe(observeState); return { unsubscribe: unsubscribe }; }
javascript
function subscribe(observer) { if ((typeof observer === 'undefined' ? 'undefined' : _typeof(observer)) !== 'object') { throw new TypeError('Expected the observer to be an object.'); } function observeState() { if (observer.next) { observer.next(getState()); } } observeState(); var unsubscribe = outerSubscribe(observeState); return { unsubscribe: unsubscribe }; }
[ "function", "subscribe", "(", "observer", ")", "{", "if", "(", "(", "typeof", "observer", "===", "'undefined'", "?", "'undefined'", ":", "_typeof", "(", "observer", ")", ")", "!==", "'object'", ")", "{", "throw", "new", "TypeError", "(", "'Expected the observer to be an object.'", ")", ";", "}", "function", "observeState", "(", ")", "{", "if", "(", "observer", ".", "next", ")", "{", "observer", ".", "next", "(", "getState", "(", ")", ")", ";", "}", "}", "observeState", "(", ")", ";", "var", "unsubscribe", "=", "outerSubscribe", "(", "observeState", ")", ";", "return", "{", "unsubscribe", ":", "unsubscribe", "}", ";", "}" ]
The minimal observable subscription method. @param {Object} observer Any object that can be used as an observer. The observer object should have a `next` method. @returns {subscription} An object with an `unsubscribe` method that can be used to unsubscribe the observable from the store, and prevent further emission of values from the observable.
[ "The", "minimal", "observable", "subscription", "method", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L18047-L18061
20,633
sociomantic-tsunami/nessie-ui
docs/assets/app.js
_loop
function _loop(prop) { if (!Object.prototype.hasOwnProperty.call(location, prop)) { return 'continue'; } Object.defineProperty(stateWithLocation, prop, { get: function get() { process.env.NODE_ENV !== 'production' ? (0, _routerWarning2.default)(false, 'Accessing location properties directly from the first argument to `getComponent`, `getComponents`, `getChildRoutes`, and `getIndexRoute` is deprecated. That argument is now the router state (`nextState` or `partialNextState`) rather than the location. To access the location, use `nextState.location` or `partialNextState.location`.') : void 0; return location[prop]; } }); }
javascript
function _loop(prop) { if (!Object.prototype.hasOwnProperty.call(location, prop)) { return 'continue'; } Object.defineProperty(stateWithLocation, prop, { get: function get() { process.env.NODE_ENV !== 'production' ? (0, _routerWarning2.default)(false, 'Accessing location properties directly from the first argument to `getComponent`, `getComponents`, `getChildRoutes`, and `getIndexRoute` is deprecated. That argument is now the router state (`nextState` or `partialNextState`) rather than the location. To access the location, use `nextState.location` or `partialNextState.location`.') : void 0; return location[prop]; } }); }
[ "function", "_loop", "(", "prop", ")", "{", "if", "(", "!", "Object", ".", "prototype", ".", "hasOwnProperty", ".", "call", "(", "location", ",", "prop", ")", ")", "{", "return", "'continue'", ";", "}", "Object", ".", "defineProperty", "(", "stateWithLocation", ",", "prop", ",", "{", "get", ":", "function", "get", "(", ")", "{", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", "?", "(", "0", ",", "_routerWarning2", ".", "default", ")", "(", "false", ",", "'Accessing location properties directly from the first argument to `getComponent`, `getComponents`, `getChildRoutes`, and `getIndexRoute` is deprecated. That argument is now the router state (`nextState` or `partialNextState`) rather than the location. To access the location, use `nextState.location` or `partialNextState.location`.'", ")", ":", "void", "0", ";", "return", "location", "[", "prop", "]", ";", "}", "}", ")", ";", "}" ]
I don't use deprecateObjectProperties here because I want to keep the same code path between development and production, in that we just assign extra properties to the copy of the state object in both cases.
[ "I", "don", "t", "use", "deprecateObjectProperties", "here", "because", "I", "want", "to", "keep", "the", "same", "code", "path", "between", "development", "and", "production", "in", "that", "we", "just", "assign", "extra", "properties", "to", "the", "copy", "of", "the", "state", "object", "in", "both", "cases", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L19020-L19031
20,634
sociomantic-tsunami/nessie-ui
docs/assets/app.js
listenBefore
function listenBefore(hook) { return history.listenBefore(function (location, callback) { _runTransitionHook2['default'](hook, addBasename(location), callback); }); }
javascript
function listenBefore(hook) { return history.listenBefore(function (location, callback) { _runTransitionHook2['default'](hook, addBasename(location), callback); }); }
[ "function", "listenBefore", "(", "hook", ")", "{", "return", "history", ".", "listenBefore", "(", "function", "(", "location", ",", "callback", ")", "{", "_runTransitionHook2", "[", "'default'", "]", "(", "hook", ",", "addBasename", "(", "location", ")", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Override all read methods with basename-aware versions.
[ "Override", "all", "read", "methods", "with", "basename", "-", "aware", "versions", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L19540-L19544
20,635
sociomantic-tsunami/nessie-ui
docs/assets/app.js
routerReducer
function routerReducer() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, type = _ref.type, payload = _ref.payload; if (type === LOCATION_CHANGE) { return _extends({}, state, { locationBeforeTransitions: payload }); } return state; }
javascript
function routerReducer() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, type = _ref.type, payload = _ref.payload; if (type === LOCATION_CHANGE) { return _extends({}, state, { locationBeforeTransitions: payload }); } return state; }
[ "function", "routerReducer", "(", ")", "{", "var", "state", "=", "arguments", ".", "length", ">", "0", "&&", "arguments", "[", "0", "]", "!==", "undefined", "?", "arguments", "[", "0", "]", ":", "initialState", ";", "var", "_ref", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "{", "}", ",", "type", "=", "_ref", ".", "type", ",", "payload", "=", "_ref", ".", "payload", ";", "if", "(", "type", "===", "LOCATION_CHANGE", ")", "{", "return", "_extends", "(", "{", "}", ",", "state", ",", "{", "locationBeforeTransitions", ":", "payload", "}", ")", ";", "}", "return", "state", ";", "}" ]
This reducer will update the state with the most recent location history has transitioned to. This may not be in sync with the router, particularly if you have asynchronously-loaded routes, so reading from and relying on this state is discouraged.
[ "This", "reducer", "will", "update", "the", "state", "with", "the", "most", "recent", "location", "history", "has", "transitioned", "to", ".", "This", "may", "not", "be", "in", "sync", "with", "the", "router", "particularly", "if", "you", "have", "asynchronously", "-", "loaded", "routes", "so", "reading", "from", "and", "relying", "on", "this", "state", "is", "discouraged", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L19792-L19804
20,636
sociomantic-tsunami/nessie-ui
docs/assets/app.js
createMarkupForCustomAttribute
function createMarkupForCustomAttribute(name, value) { if (!isAttributeNameSafe(name) || value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); }
javascript
function createMarkupForCustomAttribute(name, value) { if (!isAttributeNameSafe(name) || value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); }
[ "function", "createMarkupForCustomAttribute", "(", "name", ",", "value", ")", "{", "if", "(", "!", "isAttributeNameSafe", "(", "name", ")", "||", "value", "==", "null", ")", "{", "return", "''", ";", "}", "return", "name", "+", "'='", "+", "quoteAttributeValueForBrowser", "(", "value", ")", ";", "}" ]
Creates markup for a custom property. @param {string} name @param {*} value @return {string} Markup string, or empty string if the property was invalid.
[ "Creates", "markup", "for", "a", "custom", "property", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L21124-L21129
20,637
sociomantic-tsunami/nessie-ui
docs/assets/app.js
applyMiddleware
function applyMiddleware() { for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } return function (createStore) { return function (reducer, preloadedState, enhancer) { var store = createStore(reducer, preloadedState, enhancer); var _dispatch = store.dispatch; var chain = []; var middlewareAPI = { getState: store.getState, dispatch: function dispatch(action) { return _dispatch(action); } }; chain = middlewares.map(function (middleware) { return middleware(middlewareAPI); }); _dispatch = _compose2.default.apply(undefined, chain)(store.dispatch); return _extends({}, store, { dispatch: _dispatch }); }; }; }
javascript
function applyMiddleware() { for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } return function (createStore) { return function (reducer, preloadedState, enhancer) { var store = createStore(reducer, preloadedState, enhancer); var _dispatch = store.dispatch; var chain = []; var middlewareAPI = { getState: store.getState, dispatch: function dispatch(action) { return _dispatch(action); } }; chain = middlewares.map(function (middleware) { return middleware(middlewareAPI); }); _dispatch = _compose2.default.apply(undefined, chain)(store.dispatch); return _extends({}, store, { dispatch: _dispatch }); }; }; }
[ "function", "applyMiddleware", "(", ")", "{", "for", "(", "var", "_len", "=", "arguments", ".", "length", ",", "middlewares", "=", "Array", "(", "_len", ")", ",", "_key", "=", "0", ";", "_key", "<", "_len", ";", "_key", "++", ")", "{", "middlewares", "[", "_key", "]", "=", "arguments", "[", "_key", "]", ";", "}", "return", "function", "(", "createStore", ")", "{", "return", "function", "(", "reducer", ",", "preloadedState", ",", "enhancer", ")", "{", "var", "store", "=", "createStore", "(", "reducer", ",", "preloadedState", ",", "enhancer", ")", ";", "var", "_dispatch", "=", "store", ".", "dispatch", ";", "var", "chain", "=", "[", "]", ";", "var", "middlewareAPI", "=", "{", "getState", ":", "store", ".", "getState", ",", "dispatch", ":", "function", "dispatch", "(", "action", ")", "{", "return", "_dispatch", "(", "action", ")", ";", "}", "}", ";", "chain", "=", "middlewares", ".", "map", "(", "function", "(", "middleware", ")", "{", "return", "middleware", "(", "middlewareAPI", ")", ";", "}", ")", ";", "_dispatch", "=", "_compose2", ".", "default", ".", "apply", "(", "undefined", ",", "chain", ")", "(", "store", ".", "dispatch", ")", ";", "return", "_extends", "(", "{", "}", ",", "store", ",", "{", "dispatch", ":", "_dispatch", "}", ")", ";", "}", ";", "}", ";", "}" ]
Creates a store enhancer that applies middleware to the dispatch method of the Redux store. This is handy for a variety of tasks, such as expressing asynchronous actions in a concise manner, or logging every action payload. See `redux-thunk` package as an example of the Redux middleware. Because middleware is potentially asynchronous, this should be the first store enhancer in the composition chain. Note that each middleware will be given the `dispatch` and `getState` functions as named arguments. @param {...Function} middlewares The middleware chain to be applied. @returns {Function} A store enhancer applying the middleware.
[ "Creates", "a", "store", "enhancer", "that", "applies", "middleware", "to", "the", "dispatch", "method", "of", "the", "Redux", "store", ".", "This", "is", "handy", "for", "a", "variety", "of", "tasks", "such", "as", "expressing", "asynchronous", "actions", "in", "a", "concise", "manner", "or", "logging", "every", "action", "payload", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L25586-L25613
20,638
sociomantic-tsunami/nessie-ui
docs/assets/app.js
runLeaveHooks
function runLeaveHooks(routes, prevState) { for (var i = 0, len = routes.length; i < len; ++i) { if (routes[i].onLeave) routes[i].onLeave.call(routes[i], prevState); } }
javascript
function runLeaveHooks(routes, prevState) { for (var i = 0, len = routes.length; i < len; ++i) { if (routes[i].onLeave) routes[i].onLeave.call(routes[i], prevState); } }
[ "function", "runLeaveHooks", "(", "routes", ",", "prevState", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "routes", ".", "length", ";", "i", "<", "len", ";", "++", "i", ")", "{", "if", "(", "routes", "[", "i", "]", ".", "onLeave", ")", "routes", "[", "i", "]", ".", "onLeave", ".", "call", "(", "routes", "[", "i", "]", ",", "prevState", ")", ";", "}", "}" ]
Runs all onLeave hooks in the given array of routes in order.
[ "Runs", "all", "onLeave", "hooks", "in", "the", "given", "array", "of", "routes", "in", "order", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L26856-L26860
20,639
sociomantic-tsunami/nessie-ui
docs/assets/app.js
pathIsActive
function pathIsActive(pathname, currentPathname) { // Normalize leading slash for consistency. Leading slash on pathname has // already been normalized in isActive. See caveat there. if (currentPathname.charAt(0) !== '/') { currentPathname = '/' + currentPathname; } // Normalize the end of both path names too. Maybe `/foo/` shouldn't show // `/foo` as active, but in this case, we would already have failed the // match. if (pathname.charAt(pathname.length - 1) !== '/') { pathname += '/'; } if (currentPathname.charAt(currentPathname.length - 1) !== '/') { currentPathname += '/'; } return currentPathname === pathname; }
javascript
function pathIsActive(pathname, currentPathname) { // Normalize leading slash for consistency. Leading slash on pathname has // already been normalized in isActive. See caveat there. if (currentPathname.charAt(0) !== '/') { currentPathname = '/' + currentPathname; } // Normalize the end of both path names too. Maybe `/foo/` shouldn't show // `/foo` as active, but in this case, we would already have failed the // match. if (pathname.charAt(pathname.length - 1) !== '/') { pathname += '/'; } if (currentPathname.charAt(currentPathname.length - 1) !== '/') { currentPathname += '/'; } return currentPathname === pathname; }
[ "function", "pathIsActive", "(", "pathname", ",", "currentPathname", ")", "{", "// Normalize leading slash for consistency. Leading slash on pathname has", "// already been normalized in isActive. See caveat there.", "if", "(", "currentPathname", ".", "charAt", "(", "0", ")", "!==", "'/'", ")", "{", "currentPathname", "=", "'/'", "+", "currentPathname", ";", "}", "// Normalize the end of both path names too. Maybe `/foo/` shouldn't show", "// `/foo` as active, but in this case, we would already have failed the", "// match.", "if", "(", "pathname", ".", "charAt", "(", "pathname", ".", "length", "-", "1", ")", "!==", "'/'", ")", "{", "pathname", "+=", "'/'", ";", "}", "if", "(", "currentPathname", ".", "charAt", "(", "currentPathname", ".", "length", "-", "1", ")", "!==", "'/'", ")", "{", "currentPathname", "+=", "'/'", ";", "}", "return", "currentPathname", "===", "pathname", ";", "}" ]
Returns true if the current pathname matches the supplied one, net of leading and trailing slash normalization. This is sufficient for an indexOnly route match.
[ "Returns", "true", "if", "the", "current", "pathname", "matches", "the", "supplied", "one", "net", "of", "leading", "and", "trailing", "slash", "normalization", ".", "This", "is", "sufficient", "for", "an", "indexOnly", "route", "match", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L26922-L26940
20,640
sociomantic-tsunami/nessie-ui
docs/assets/app.js
onChildRoutes
function onChildRoutes(error, childRoutes) { if (error) { callback(error); } else if (childRoutes) { // Check the child routes to see if any of them match. matchRoutes(childRoutes, location, function (error, match) { if (error) { callback(error); } else if (match) { // A child route matched! Augment the match and pass it up the stack. match.routes.unshift(route); callback(null, match); } else { callback(); } }, remainingPathname, paramNames, paramValues); } else { callback(); } }
javascript
function onChildRoutes(error, childRoutes) { if (error) { callback(error); } else if (childRoutes) { // Check the child routes to see if any of them match. matchRoutes(childRoutes, location, function (error, match) { if (error) { callback(error); } else if (match) { // A child route matched! Augment the match and pass it up the stack. match.routes.unshift(route); callback(null, match); } else { callback(); } }, remainingPathname, paramNames, paramValues); } else { callback(); } }
[ "function", "onChildRoutes", "(", "error", ",", "childRoutes", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ")", ";", "}", "else", "if", "(", "childRoutes", ")", "{", "// Check the child routes to see if any of them match.", "matchRoutes", "(", "childRoutes", ",", "location", ",", "function", "(", "error", ",", "match", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ")", ";", "}", "else", "if", "(", "match", ")", "{", "// A child route matched! Augment the match and pass it up the stack.", "match", ".", "routes", ".", "unshift", "(", "route", ")", ";", "callback", "(", "null", ",", "match", ")", ";", "}", "else", "{", "callback", "(", ")", ";", "}", "}", ",", "remainingPathname", ",", "paramNames", ",", "paramValues", ")", ";", "}", "else", "{", "callback", "(", ")", ";", "}", "}" ]
Either a) this route matched at least some of the path or b) we don't have to load this route's children asynchronously. In either case continue checking for matches in the subtree.
[ "Either", "a", ")", "this", "route", "matched", "at", "least", "some", "of", "the", "path", "or", "b", ")", "we", "don", "t", "have", "to", "load", "this", "route", "s", "children", "asynchronously", ".", "In", "either", "case", "continue", "checking", "for", "matches", "in", "the", "subtree", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L27284-L27303
20,641
sociomantic-tsunami/nessie-ui
docs/assets/app.js
syncHistoryWithStore
function syncHistoryWithStore(history, store) { var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, _ref$selectLocationSt = _ref.selectLocationState, selectLocationState = _ref$selectLocationSt === undefined ? defaultSelectLocationState : _ref$selectLocationSt, _ref$adjustUrlOnRepla = _ref.adjustUrlOnReplay, adjustUrlOnReplay = _ref$adjustUrlOnRepla === undefined ? true : _ref$adjustUrlOnRepla; // Ensure that the reducer is mounted on the store and functioning properly. if (typeof selectLocationState(store.getState()) === 'undefined') { throw new Error('Expected the routing state to be available either as `state.routing` ' + 'or as the custom expression you can specify as `selectLocationState` ' + 'in the `syncHistoryWithStore()` options. ' + 'Ensure you have added the `routerReducer` to your store\'s ' + 'reducers via `combineReducers` or whatever method you use to isolate ' + 'your reducers.'); } var initialLocation = void 0; var isTimeTraveling = void 0; var unsubscribeFromStore = void 0; var unsubscribeFromHistory = void 0; var currentLocation = void 0; // What does the store say about current location? var getLocationInStore = function getLocationInStore(useInitialIfEmpty) { var locationState = selectLocationState(store.getState()); return locationState.locationBeforeTransitions || (useInitialIfEmpty ? initialLocation : undefined); }; // Init initialLocation with potential location in store initialLocation = getLocationInStore(); // If the store is replayed, update the URL in the browser to match. if (adjustUrlOnReplay) { var handleStoreChange = function handleStoreChange() { var locationInStore = getLocationInStore(true); if (currentLocation === locationInStore || initialLocation === locationInStore) { return; } // Update address bar to reflect store state isTimeTraveling = true; currentLocation = locationInStore; history.transitionTo(_extends({}, locationInStore, { action: 'PUSH' })); isTimeTraveling = false; }; unsubscribeFromStore = store.subscribe(handleStoreChange); handleStoreChange(); } // Whenever location changes, dispatch an action to get it in the store var handleLocationChange = function handleLocationChange(location) { // ... unless we just caused that location change if (isTimeTraveling) { return; } // Remember where we are currentLocation = location; // Are we being called for the first time? if (!initialLocation) { // Remember as a fallback in case state is reset initialLocation = location; // Respect persisted location, if any if (getLocationInStore()) { return; } } // Tell the store to update by dispatching an action store.dispatch({ type: _reducer.LOCATION_CHANGE, payload: location }); }; unsubscribeFromHistory = history.listen(handleLocationChange); // History 3.x doesn't call listen synchronously, so fire the initial location change ourselves if (history.getCurrentLocation) { handleLocationChange(history.getCurrentLocation()); } // The enhanced history uses store as source of truth return _extends({}, history, { // The listeners are subscribed to the store instead of history listen: function listen(listener) { // Copy of last location. var lastPublishedLocation = getLocationInStore(true); // Keep track of whether we unsubscribed, as Redux store // only applies changes in subscriptions on next dispatch var unsubscribed = false; var unsubscribeFromStore = store.subscribe(function () { var currentLocation = getLocationInStore(true); if (currentLocation === lastPublishedLocation) { return; } lastPublishedLocation = currentLocation; if (!unsubscribed) { listener(lastPublishedLocation); } }); // History 2.x listeners expect a synchronous call. Make the first call to the // listener after subscribing to the store, in case the listener causes a // location change (e.g. when it redirects) if (!history.getCurrentLocation) { listener(lastPublishedLocation); } // Let user unsubscribe later return function () { unsubscribed = true; unsubscribeFromStore(); }; }, // It also provides a way to destroy internal listeners unsubscribe: function unsubscribe() { if (adjustUrlOnReplay) { unsubscribeFromStore(); } unsubscribeFromHistory(); } }); }
javascript
function syncHistoryWithStore(history, store) { var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, _ref$selectLocationSt = _ref.selectLocationState, selectLocationState = _ref$selectLocationSt === undefined ? defaultSelectLocationState : _ref$selectLocationSt, _ref$adjustUrlOnRepla = _ref.adjustUrlOnReplay, adjustUrlOnReplay = _ref$adjustUrlOnRepla === undefined ? true : _ref$adjustUrlOnRepla; // Ensure that the reducer is mounted on the store and functioning properly. if (typeof selectLocationState(store.getState()) === 'undefined') { throw new Error('Expected the routing state to be available either as `state.routing` ' + 'or as the custom expression you can specify as `selectLocationState` ' + 'in the `syncHistoryWithStore()` options. ' + 'Ensure you have added the `routerReducer` to your store\'s ' + 'reducers via `combineReducers` or whatever method you use to isolate ' + 'your reducers.'); } var initialLocation = void 0; var isTimeTraveling = void 0; var unsubscribeFromStore = void 0; var unsubscribeFromHistory = void 0; var currentLocation = void 0; // What does the store say about current location? var getLocationInStore = function getLocationInStore(useInitialIfEmpty) { var locationState = selectLocationState(store.getState()); return locationState.locationBeforeTransitions || (useInitialIfEmpty ? initialLocation : undefined); }; // Init initialLocation with potential location in store initialLocation = getLocationInStore(); // If the store is replayed, update the URL in the browser to match. if (adjustUrlOnReplay) { var handleStoreChange = function handleStoreChange() { var locationInStore = getLocationInStore(true); if (currentLocation === locationInStore || initialLocation === locationInStore) { return; } // Update address bar to reflect store state isTimeTraveling = true; currentLocation = locationInStore; history.transitionTo(_extends({}, locationInStore, { action: 'PUSH' })); isTimeTraveling = false; }; unsubscribeFromStore = store.subscribe(handleStoreChange); handleStoreChange(); } // Whenever location changes, dispatch an action to get it in the store var handleLocationChange = function handleLocationChange(location) { // ... unless we just caused that location change if (isTimeTraveling) { return; } // Remember where we are currentLocation = location; // Are we being called for the first time? if (!initialLocation) { // Remember as a fallback in case state is reset initialLocation = location; // Respect persisted location, if any if (getLocationInStore()) { return; } } // Tell the store to update by dispatching an action store.dispatch({ type: _reducer.LOCATION_CHANGE, payload: location }); }; unsubscribeFromHistory = history.listen(handleLocationChange); // History 3.x doesn't call listen synchronously, so fire the initial location change ourselves if (history.getCurrentLocation) { handleLocationChange(history.getCurrentLocation()); } // The enhanced history uses store as source of truth return _extends({}, history, { // The listeners are subscribed to the store instead of history listen: function listen(listener) { // Copy of last location. var lastPublishedLocation = getLocationInStore(true); // Keep track of whether we unsubscribed, as Redux store // only applies changes in subscriptions on next dispatch var unsubscribed = false; var unsubscribeFromStore = store.subscribe(function () { var currentLocation = getLocationInStore(true); if (currentLocation === lastPublishedLocation) { return; } lastPublishedLocation = currentLocation; if (!unsubscribed) { listener(lastPublishedLocation); } }); // History 2.x listeners expect a synchronous call. Make the first call to the // listener after subscribing to the store, in case the listener causes a // location change (e.g. when it redirects) if (!history.getCurrentLocation) { listener(lastPublishedLocation); } // Let user unsubscribe later return function () { unsubscribed = true; unsubscribeFromStore(); }; }, // It also provides a way to destroy internal listeners unsubscribe: function unsubscribe() { if (adjustUrlOnReplay) { unsubscribeFromStore(); } unsubscribeFromHistory(); } }); }
[ "function", "syncHistoryWithStore", "(", "history", ",", "store", ")", "{", "var", "_ref", "=", "arguments", ".", "length", ">", "2", "&&", "arguments", "[", "2", "]", "!==", "undefined", "?", "arguments", "[", "2", "]", ":", "{", "}", ",", "_ref$selectLocationSt", "=", "_ref", ".", "selectLocationState", ",", "selectLocationState", "=", "_ref$selectLocationSt", "===", "undefined", "?", "defaultSelectLocationState", ":", "_ref$selectLocationSt", ",", "_ref$adjustUrlOnRepla", "=", "_ref", ".", "adjustUrlOnReplay", ",", "adjustUrlOnReplay", "=", "_ref$adjustUrlOnRepla", "===", "undefined", "?", "true", ":", "_ref$adjustUrlOnRepla", ";", "// Ensure that the reducer is mounted on the store and functioning properly.", "if", "(", "typeof", "selectLocationState", "(", "store", ".", "getState", "(", ")", ")", "===", "'undefined'", ")", "{", "throw", "new", "Error", "(", "'Expected the routing state to be available either as `state.routing` '", "+", "'or as the custom expression you can specify as `selectLocationState` '", "+", "'in the `syncHistoryWithStore()` options. '", "+", "'Ensure you have added the `routerReducer` to your store\\'s '", "+", "'reducers via `combineReducers` or whatever method you use to isolate '", "+", "'your reducers.'", ")", ";", "}", "var", "initialLocation", "=", "void", "0", ";", "var", "isTimeTraveling", "=", "void", "0", ";", "var", "unsubscribeFromStore", "=", "void", "0", ";", "var", "unsubscribeFromHistory", "=", "void", "0", ";", "var", "currentLocation", "=", "void", "0", ";", "// What does the store say about current location?", "var", "getLocationInStore", "=", "function", "getLocationInStore", "(", "useInitialIfEmpty", ")", "{", "var", "locationState", "=", "selectLocationState", "(", "store", ".", "getState", "(", ")", ")", ";", "return", "locationState", ".", "locationBeforeTransitions", "||", "(", "useInitialIfEmpty", "?", "initialLocation", ":", "undefined", ")", ";", "}", ";", "// Init initialLocation with potential location in store", "initialLocation", "=", "getLocationInStore", "(", ")", ";", "// If the store is replayed, update the URL in the browser to match.", "if", "(", "adjustUrlOnReplay", ")", "{", "var", "handleStoreChange", "=", "function", "handleStoreChange", "(", ")", "{", "var", "locationInStore", "=", "getLocationInStore", "(", "true", ")", ";", "if", "(", "currentLocation", "===", "locationInStore", "||", "initialLocation", "===", "locationInStore", ")", "{", "return", ";", "}", "// Update address bar to reflect store state", "isTimeTraveling", "=", "true", ";", "currentLocation", "=", "locationInStore", ";", "history", ".", "transitionTo", "(", "_extends", "(", "{", "}", ",", "locationInStore", ",", "{", "action", ":", "'PUSH'", "}", ")", ")", ";", "isTimeTraveling", "=", "false", ";", "}", ";", "unsubscribeFromStore", "=", "store", ".", "subscribe", "(", "handleStoreChange", ")", ";", "handleStoreChange", "(", ")", ";", "}", "// Whenever location changes, dispatch an action to get it in the store", "var", "handleLocationChange", "=", "function", "handleLocationChange", "(", "location", ")", "{", "// ... unless we just caused that location change", "if", "(", "isTimeTraveling", ")", "{", "return", ";", "}", "// Remember where we are", "currentLocation", "=", "location", ";", "// Are we being called for the first time?", "if", "(", "!", "initialLocation", ")", "{", "// Remember as a fallback in case state is reset", "initialLocation", "=", "location", ";", "// Respect persisted location, if any", "if", "(", "getLocationInStore", "(", ")", ")", "{", "return", ";", "}", "}", "// Tell the store to update by dispatching an action", "store", ".", "dispatch", "(", "{", "type", ":", "_reducer", ".", "LOCATION_CHANGE", ",", "payload", ":", "location", "}", ")", ";", "}", ";", "unsubscribeFromHistory", "=", "history", ".", "listen", "(", "handleLocationChange", ")", ";", "// History 3.x doesn't call listen synchronously, so fire the initial location change ourselves", "if", "(", "history", ".", "getCurrentLocation", ")", "{", "handleLocationChange", "(", "history", ".", "getCurrentLocation", "(", ")", ")", ";", "}", "// The enhanced history uses store as source of truth", "return", "_extends", "(", "{", "}", ",", "history", ",", "{", "// The listeners are subscribed to the store instead of history", "listen", ":", "function", "listen", "(", "listener", ")", "{", "// Copy of last location.", "var", "lastPublishedLocation", "=", "getLocationInStore", "(", "true", ")", ";", "// Keep track of whether we unsubscribed, as Redux store", "// only applies changes in subscriptions on next dispatch", "var", "unsubscribed", "=", "false", ";", "var", "unsubscribeFromStore", "=", "store", ".", "subscribe", "(", "function", "(", ")", "{", "var", "currentLocation", "=", "getLocationInStore", "(", "true", ")", ";", "if", "(", "currentLocation", "===", "lastPublishedLocation", ")", "{", "return", ";", "}", "lastPublishedLocation", "=", "currentLocation", ";", "if", "(", "!", "unsubscribed", ")", "{", "listener", "(", "lastPublishedLocation", ")", ";", "}", "}", ")", ";", "// History 2.x listeners expect a synchronous call. Make the first call to the", "// listener after subscribing to the store, in case the listener causes a", "// location change (e.g. when it redirects)", "if", "(", "!", "history", ".", "getCurrentLocation", ")", "{", "listener", "(", "lastPublishedLocation", ")", ";", "}", "// Let user unsubscribe later", "return", "function", "(", ")", "{", "unsubscribed", "=", "true", ";", "unsubscribeFromStore", "(", ")", ";", "}", ";", "}", ",", "// It also provides a way to destroy internal listeners", "unsubscribe", ":", "function", "unsubscribe", "(", ")", "{", "if", "(", "adjustUrlOnReplay", ")", "{", "unsubscribeFromStore", "(", ")", ";", "}", "unsubscribeFromHistory", "(", ")", ";", "}", "}", ")", ";", "}" ]
This function synchronizes your history state with the Redux store. Location changes flow from history to the store. An enhanced history is returned with a listen method that responds to store updates for location. When this history is provided to the router, this means the location data will flow like this: history.push -> store.dispatch -> enhancedHistory.listen -> router This ensures that when the store state changes due to a replay or other event, the router will be updated appropriately and can transition to the correct router state.
[ "This", "function", "synchronizes", "your", "history", "state", "with", "the", "Redux", "store", ".", "Location", "changes", "flow", "from", "history", "to", "the", "store", ".", "An", "enhanced", "history", "is", "returned", "with", "a", "listen", "method", "that", "responds", "to", "store", "updates", "for", "location", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L28673-L28798
20,642
sociomantic-tsunami/nessie-ui
docs/assets/app.js
getLocationInStore
function getLocationInStore(useInitialIfEmpty) { var locationState = selectLocationState(store.getState()); return locationState.locationBeforeTransitions || (useInitialIfEmpty ? initialLocation : undefined); }
javascript
function getLocationInStore(useInitialIfEmpty) { var locationState = selectLocationState(store.getState()); return locationState.locationBeforeTransitions || (useInitialIfEmpty ? initialLocation : undefined); }
[ "function", "getLocationInStore", "(", "useInitialIfEmpty", ")", "{", "var", "locationState", "=", "selectLocationState", "(", "store", ".", "getState", "(", ")", ")", ";", "return", "locationState", ".", "locationBeforeTransitions", "||", "(", "useInitialIfEmpty", "?", "initialLocation", ":", "undefined", ")", ";", "}" ]
What does the store say about current location?
[ "What", "does", "the", "store", "say", "about", "current", "location?" ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L28692-L28695
20,643
sociomantic-tsunami/nessie-ui
docs/assets/app.js
handleLocationChange
function handleLocationChange(location) { // ... unless we just caused that location change if (isTimeTraveling) { return; } // Remember where we are currentLocation = location; // Are we being called for the first time? if (!initialLocation) { // Remember as a fallback in case state is reset initialLocation = location; // Respect persisted location, if any if (getLocationInStore()) { return; } } // Tell the store to update by dispatching an action store.dispatch({ type: _reducer.LOCATION_CHANGE, payload: location }); }
javascript
function handleLocationChange(location) { // ... unless we just caused that location change if (isTimeTraveling) { return; } // Remember where we are currentLocation = location; // Are we being called for the first time? if (!initialLocation) { // Remember as a fallback in case state is reset initialLocation = location; // Respect persisted location, if any if (getLocationInStore()) { return; } } // Tell the store to update by dispatching an action store.dispatch({ type: _reducer.LOCATION_CHANGE, payload: location }); }
[ "function", "handleLocationChange", "(", "location", ")", "{", "// ... unless we just caused that location change", "if", "(", "isTimeTraveling", ")", "{", "return", ";", "}", "// Remember where we are", "currentLocation", "=", "location", ";", "// Are we being called for the first time?", "if", "(", "!", "initialLocation", ")", "{", "// Remember as a fallback in case state is reset", "initialLocation", "=", "location", ";", "// Respect persisted location, if any", "if", "(", "getLocationInStore", "(", ")", ")", "{", "return", ";", "}", "}", "// Tell the store to update by dispatching an action", "store", ".", "dispatch", "(", "{", "type", ":", "_reducer", ".", "LOCATION_CHANGE", ",", "payload", ":", "location", "}", ")", ";", "}" ]
Whenever location changes, dispatch an action to get it in the store
[ "Whenever", "location", "changes", "dispatch", "an", "action", "to", "get", "it", "in", "the", "store" ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L28722-L28747
20,644
sociomantic-tsunami/nessie-ui
docs/assets/app.js
listen
function listen(listener) { // Copy of last location. var lastPublishedLocation = getLocationInStore(true); // Keep track of whether we unsubscribed, as Redux store // only applies changes in subscriptions on next dispatch var unsubscribed = false; var unsubscribeFromStore = store.subscribe(function () { var currentLocation = getLocationInStore(true); if (currentLocation === lastPublishedLocation) { return; } lastPublishedLocation = currentLocation; if (!unsubscribed) { listener(lastPublishedLocation); } }); // History 2.x listeners expect a synchronous call. Make the first call to the // listener after subscribing to the store, in case the listener causes a // location change (e.g. when it redirects) if (!history.getCurrentLocation) { listener(lastPublishedLocation); } // Let user unsubscribe later return function () { unsubscribed = true; unsubscribeFromStore(); }; }
javascript
function listen(listener) { // Copy of last location. var lastPublishedLocation = getLocationInStore(true); // Keep track of whether we unsubscribed, as Redux store // only applies changes in subscriptions on next dispatch var unsubscribed = false; var unsubscribeFromStore = store.subscribe(function () { var currentLocation = getLocationInStore(true); if (currentLocation === lastPublishedLocation) { return; } lastPublishedLocation = currentLocation; if (!unsubscribed) { listener(lastPublishedLocation); } }); // History 2.x listeners expect a synchronous call. Make the first call to the // listener after subscribing to the store, in case the listener causes a // location change (e.g. when it redirects) if (!history.getCurrentLocation) { listener(lastPublishedLocation); } // Let user unsubscribe later return function () { unsubscribed = true; unsubscribeFromStore(); }; }
[ "function", "listen", "(", "listener", ")", "{", "// Copy of last location.", "var", "lastPublishedLocation", "=", "getLocationInStore", "(", "true", ")", ";", "// Keep track of whether we unsubscribed, as Redux store", "// only applies changes in subscriptions on next dispatch", "var", "unsubscribed", "=", "false", ";", "var", "unsubscribeFromStore", "=", "store", ".", "subscribe", "(", "function", "(", ")", "{", "var", "currentLocation", "=", "getLocationInStore", "(", "true", ")", ";", "if", "(", "currentLocation", "===", "lastPublishedLocation", ")", "{", "return", ";", "}", "lastPublishedLocation", "=", "currentLocation", ";", "if", "(", "!", "unsubscribed", ")", "{", "listener", "(", "lastPublishedLocation", ")", ";", "}", "}", ")", ";", "// History 2.x listeners expect a synchronous call. Make the first call to the", "// listener after subscribing to the store, in case the listener causes a", "// location change (e.g. when it redirects)", "if", "(", "!", "history", ".", "getCurrentLocation", ")", "{", "listener", "(", "lastPublishedLocation", ")", ";", "}", "// Let user unsubscribe later", "return", "function", "(", ")", "{", "unsubscribed", "=", "true", ";", "unsubscribeFromStore", "(", ")", ";", "}", ";", "}" ]
The listeners are subscribed to the store instead of history
[ "The", "listeners", "are", "subscribed", "to", "the", "store", "instead", "of", "history" ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L28758-L28788
20,645
sociomantic-tsunami/nessie-ui
docs/assets/app.js
routerMiddleware
function routerMiddleware(history) { return function () { return function (next) { return function (action) { if (action.type !== _actions.CALL_HISTORY_METHOD) { return next(action); } var _action$payload = action.payload, method = _action$payload.method, args = _action$payload.args; history[method].apply(history, _toConsumableArray(args)); }; }; }; }
javascript
function routerMiddleware(history) { return function () { return function (next) { return function (action) { if (action.type !== _actions.CALL_HISTORY_METHOD) { return next(action); } var _action$payload = action.payload, method = _action$payload.method, args = _action$payload.args; history[method].apply(history, _toConsumableArray(args)); }; }; }; }
[ "function", "routerMiddleware", "(", "history", ")", "{", "return", "function", "(", ")", "{", "return", "function", "(", "next", ")", "{", "return", "function", "(", "action", ")", "{", "if", "(", "action", ".", "type", "!==", "_actions", ".", "CALL_HISTORY_METHOD", ")", "{", "return", "next", "(", "action", ")", ";", "}", "var", "_action$payload", "=", "action", ".", "payload", ",", "method", "=", "_action$payload", ".", "method", ",", "args", "=", "_action$payload", ".", "args", ";", "history", "[", "method", "]", ".", "apply", "(", "history", ",", "_toConsumableArray", "(", "args", ")", ")", ";", "}", ";", "}", ";", "}", ";", "}" ]
This middleware captures CALL_HISTORY_METHOD actions to redirect to the provided history object. This will prevent these actions from reaching your reducer or any middleware that comes after this one.
[ "This", "middleware", "captures", "CALL_HISTORY_METHOD", "actions", "to", "redirect", "to", "the", "provided", "history", "object", ".", "This", "will", "prevent", "these", "actions", "from", "reaching", "your", "reducer", "or", "any", "middleware", "that", "comes", "after", "this", "one", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L28829-L28845
20,646
sociomantic-tsunami/nessie-ui
docs/assets/app.js
getDataFromCustomEvent
function getDataFromCustomEvent(nativeEvent) { var detail = nativeEvent.detail; if ((typeof detail === 'undefined' ? 'undefined' : _typeof(detail)) === 'object' && 'data' in detail) { return detail.data; } return null; }
javascript
function getDataFromCustomEvent(nativeEvent) { var detail = nativeEvent.detail; if ((typeof detail === 'undefined' ? 'undefined' : _typeof(detail)) === 'object' && 'data' in detail) { return detail.data; } return null; }
[ "function", "getDataFromCustomEvent", "(", "nativeEvent", ")", "{", "var", "detail", "=", "nativeEvent", ".", "detail", ";", "if", "(", "(", "typeof", "detail", "===", "'undefined'", "?", "'undefined'", ":", "_typeof", "(", "detail", ")", ")", "===", "'object'", "&&", "'data'", "in", "detail", ")", "{", "return", "detail", ".", "data", ";", "}", "return", "null", ";", "}" ]
Google Input Tools provides composition data via a CustomEvent, with the `data` property populated in the `detail` object. If this is available on the event object, use it. If not, this is a plain composition event and we have nothing special to extract. @param {object} nativeEvent @return {?string}
[ "Google", "Input", "Tools", "provides", "composition", "data", "via", "a", "CustomEvent", "with", "the", "data", "property", "populated", "in", "the", "detail", "object", ".", "If", "this", "is", "available", "on", "the", "event", "object", "use", "it", ".", "If", "not", "this", "is", "a", "plain", "composition", "event", "and", "we", "have", "nothing", "special", "to", "extract", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L31889-L31895
20,647
sociomantic-tsunami/nessie-ui
docs/assets/app.js
receiveComponent
function receiveComponent(nextElement, transaction, context) { var prevElement = this._currentElement; this._currentElement = nextElement; this.updateComponent(transaction, prevElement, nextElement, context); }
javascript
function receiveComponent(nextElement, transaction, context) { var prevElement = this._currentElement; this._currentElement = nextElement; this.updateComponent(transaction, prevElement, nextElement, context); }
[ "function", "receiveComponent", "(", "nextElement", ",", "transaction", ",", "context", ")", "{", "var", "prevElement", "=", "this", ".", "_currentElement", ";", "this", ".", "_currentElement", "=", "nextElement", ";", "this", ".", "updateComponent", "(", "transaction", ",", "prevElement", ",", "nextElement", ",", "context", ")", ";", "}" ]
Receives a next element and updates the component. @internal @param {ReactElement} nextElement @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction @param {object} context
[ "Receives", "a", "next", "element", "and", "updates", "the", "component", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L34346-L34350
20,648
sociomantic-tsunami/nessie-ui
docs/assets/app.js
makeInsertMarkup
function makeInsertMarkup(markup, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: 'INSERT_MARKUP', content: markup, fromIndex: null, fromNode: null, toIndex: toIndex, afterNode: afterNode }; }
javascript
function makeInsertMarkup(markup, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: 'INSERT_MARKUP', content: markup, fromIndex: null, fromNode: null, toIndex: toIndex, afterNode: afterNode }; }
[ "function", "makeInsertMarkup", "(", "markup", ",", "afterNode", ",", "toIndex", ")", "{", "// NOTE: Null values reduce hidden classes.", "return", "{", "type", ":", "'INSERT_MARKUP'", ",", "content", ":", "markup", ",", "fromIndex", ":", "null", ",", "fromNode", ":", "null", ",", "toIndex", ":", "toIndex", ",", "afterNode", ":", "afterNode", "}", ";", "}" ]
Make an update for markup to be rendered and inserted at a supplied index. @param {string} markup Markup that renders into an element. @param {number} toIndex Destination index. @private
[ "Make", "an", "update", "for", "markup", "to", "be", "rendered", "and", "inserted", "at", "a", "supplied", "index", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L37549-L37559
20,649
sociomantic-tsunami/nessie-ui
docs/assets/app.js
makeRemove
function makeRemove(child, node) { // NOTE: Null values reduce hidden classes. return { type: 'REMOVE_NODE', content: null, fromIndex: child._mountIndex, fromNode: node, toIndex: null, afterNode: null }; }
javascript
function makeRemove(child, node) { // NOTE: Null values reduce hidden classes. return { type: 'REMOVE_NODE', content: null, fromIndex: child._mountIndex, fromNode: node, toIndex: null, afterNode: null }; }
[ "function", "makeRemove", "(", "child", ",", "node", ")", "{", "// NOTE: Null values reduce hidden classes.", "return", "{", "type", ":", "'REMOVE_NODE'", ",", "content", ":", "null", ",", "fromIndex", ":", "child", ".", "_mountIndex", ",", "fromNode", ":", "node", ",", "toIndex", ":", "null", ",", "afterNode", ":", "null", "}", ";", "}" ]
Make an update for removing an element at an index. @param {number} fromIndex Index of the element to remove. @private
[ "Make", "an", "update", "for", "removing", "an", "element", "at", "an", "index", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L37586-L37596
20,650
sociomantic-tsunami/nessie-ui
docs/assets/app.js
makeSetMarkup
function makeSetMarkup(markup) { // NOTE: Null values reduce hidden classes. return { type: 'SET_MARKUP', content: markup, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; }
javascript
function makeSetMarkup(markup) { // NOTE: Null values reduce hidden classes. return { type: 'SET_MARKUP', content: markup, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; }
[ "function", "makeSetMarkup", "(", "markup", ")", "{", "// NOTE: Null values reduce hidden classes.", "return", "{", "type", ":", "'SET_MARKUP'", ",", "content", ":", "markup", ",", "fromIndex", ":", "null", ",", "fromNode", ":", "null", ",", "toIndex", ":", "null", ",", "afterNode", ":", "null", "}", ";", "}" ]
Make an update for setting the markup of a node. @param {string} markup Markup that renders into an element. @private
[ "Make", "an", "update", "for", "setting", "the", "markup", "of", "a", "node", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L37604-L37614
20,651
sociomantic-tsunami/nessie-ui
docs/assets/app.js
makeTextContent
function makeTextContent(textContent) { // NOTE: Null values reduce hidden classes. return { type: 'TEXT_CONTENT', content: textContent, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; }
javascript
function makeTextContent(textContent) { // NOTE: Null values reduce hidden classes. return { type: 'TEXT_CONTENT', content: textContent, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; }
[ "function", "makeTextContent", "(", "textContent", ")", "{", "// NOTE: Null values reduce hidden classes.", "return", "{", "type", ":", "'TEXT_CONTENT'", ",", "content", ":", "textContent", ",", "fromIndex", ":", "null", ",", "fromNode", ":", "null", ",", "toIndex", ":", "null", ",", "afterNode", ":", "null", "}", ";", "}" ]
Make an update for setting the text content. @param {string} textContent Text content to set. @private
[ "Make", "an", "update", "for", "setting", "the", "text", "content", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L37622-L37632
20,652
sociomantic-tsunami/nessie-ui
docs/assets/app.js
enqueue
function enqueue(queue, update) { if (update) { queue = queue || []; queue.push(update); } return queue; }
javascript
function enqueue(queue, update) { if (update) { queue = queue || []; queue.push(update); } return queue; }
[ "function", "enqueue", "(", "queue", ",", "update", ")", "{", "if", "(", "update", ")", "{", "queue", "=", "queue", "||", "[", "]", ";", "queue", ".", "push", "(", "update", ")", ";", "}", "return", "queue", ";", "}" ]
Push an update, if any, onto the queue. Creates a new queue if none is passed and always returns the queue. Mutative.
[ "Push", "an", "update", "if", "any", "onto", "the", "queue", ".", "Creates", "a", "new", "queue", "if", "none", "is", "passed", "and", "always", "returns", "the", "queue", ".", "Mutative", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L37638-L37644
20,653
sociomantic-tsunami/nessie-ui
docs/assets/app.js
updateMarkup
function updateMarkup(nextMarkup) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren, false); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { true ? false ? invariant(false, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0; } } var updates = [makeSetMarkup(nextMarkup)]; processQueue(this, updates); }
javascript
function updateMarkup(nextMarkup) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren, false); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { true ? false ? invariant(false, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0; } } var updates = [makeSetMarkup(nextMarkup)]; processQueue(this, updates); }
[ "function", "updateMarkup", "(", "nextMarkup", ")", "{", "var", "prevChildren", "=", "this", ".", "_renderedChildren", ";", "// Remove any rendered children.", "ReactChildReconciler", ".", "unmountChildren", "(", "prevChildren", ",", "false", ")", ";", "for", "(", "var", "name", "in", "prevChildren", ")", "{", "if", "(", "prevChildren", ".", "hasOwnProperty", "(", "name", ")", ")", "{", "true", "?", "false", "?", "invariant", "(", "false", ",", "'updateTextContent called on non-empty component.'", ")", ":", "_prodInvariant", "(", "'118'", ")", ":", "void", "0", ";", "}", "}", "var", "updates", "=", "[", "makeSetMarkup", "(", "nextMarkup", ")", "]", ";", "processQueue", "(", "this", ",", "updates", ")", ";", "}" ]
Replaces any rendered children with a markup string. @param {string} nextMarkup String of markup. @internal
[ "Replaces", "any", "rendered", "children", "with", "a", "markup", "string", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L37790-L37801
20,654
sociomantic-tsunami/nessie-ui
docs/assets/app.js
unmountChildren
function unmountChildren(safely) { var renderedChildren = this._renderedChildren; ReactChildReconciler.unmountChildren(renderedChildren, safely); this._renderedChildren = null; }
javascript
function unmountChildren(safely) { var renderedChildren = this._renderedChildren; ReactChildReconciler.unmountChildren(renderedChildren, safely); this._renderedChildren = null; }
[ "function", "unmountChildren", "(", "safely", ")", "{", "var", "renderedChildren", "=", "this", ".", "_renderedChildren", ";", "ReactChildReconciler", ".", "unmountChildren", "(", "renderedChildren", ",", "safely", ")", ";", "this", ".", "_renderedChildren", "=", "null", ";", "}" ]
Unmounts all rendered children. This should be used to clean up children when this component is unmounted. It does not actually perform any backend operations. @internal
[ "Unmounts", "all", "rendered", "children", ".", "This", "should", "be", "used", "to", "clean", "up", "children", "when", "this", "component", "is", "unmounted", ".", "It", "does", "not", "actually", "perform", "any", "backend", "operations", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L37884-L37888
20,655
sociomantic-tsunami/nessie-ui
docs/assets/app.js
_maskContext
function _maskContext(context) { var Component = this._currentElement.type; var contextTypes = Component.contextTypes; if (!contextTypes) { return emptyObject; } var maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } return maskedContext; }
javascript
function _maskContext(context) { var Component = this._currentElement.type; var contextTypes = Component.contextTypes; if (!contextTypes) { return emptyObject; } var maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } return maskedContext; }
[ "function", "_maskContext", "(", "context", ")", "{", "var", "Component", "=", "this", ".", "_currentElement", ".", "type", ";", "var", "contextTypes", "=", "Component", ".", "contextTypes", ";", "if", "(", "!", "contextTypes", ")", "{", "return", "emptyObject", ";", "}", "var", "maskedContext", "=", "{", "}", ";", "for", "(", "var", "contextName", "in", "contextTypes", ")", "{", "maskedContext", "[", "contextName", "]", "=", "context", "[", "contextName", "]", ";", "}", "return", "maskedContext", ";", "}" ]
Filters the context object to only contain keys specified in `contextTypes` @param {object} context @return {?object} @private
[ "Filters", "the", "context", "object", "to", "only", "contain", "keys", "specified", "in", "contextTypes" ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L38581-L38592
20,656
sociomantic-tsunami/nessie-ui
docs/assets/app.js
constructSelectEvent
function constructSelectEvent(nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if (mouseDown || activeElement == null || activeElement !== getActiveElement()) { return null; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementInst, nativeEvent, nativeEventTarget); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement; EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } return null; }
javascript
function constructSelectEvent(nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if (mouseDown || activeElement == null || activeElement !== getActiveElement()) { return null; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementInst, nativeEvent, nativeEventTarget); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement; EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } return null; }
[ "function", "constructSelectEvent", "(", "nativeEvent", ",", "nativeEventTarget", ")", "{", "// Ensure we have the right element, and that the user is not dragging a", "// selection (this matches native `select` event behavior). In HTML5, select", "// fires only on input and textarea thus if there's no focused element we", "// won't dispatch.", "if", "(", "mouseDown", "||", "activeElement", "==", "null", "||", "activeElement", "!==", "getActiveElement", "(", ")", ")", "{", "return", "null", ";", "}", "// Only fire when selection has actually changed.", "var", "currentSelection", "=", "getSelection", "(", "activeElement", ")", ";", "if", "(", "!", "lastSelection", "||", "!", "shallowEqual", "(", "lastSelection", ",", "currentSelection", ")", ")", "{", "lastSelection", "=", "currentSelection", ";", "var", "syntheticEvent", "=", "SyntheticEvent", ".", "getPooled", "(", "eventTypes", ".", "select", ",", "activeElementInst", ",", "nativeEvent", ",", "nativeEventTarget", ")", ";", "syntheticEvent", ".", "type", "=", "'select'", ";", "syntheticEvent", ".", "target", "=", "activeElement", ";", "EventPropagators", ".", "accumulateTwoPhaseDispatches", "(", "syntheticEvent", ")", ";", "return", "syntheticEvent", ";", "}", "return", "null", ";", "}" ]
Poll selection to see whether it's changed. @param {object} nativeEvent @return {?SyntheticEvent}
[ "Poll", "selection", "to", "see", "whether", "it", "s", "changed", "." ]
e2348045ebc6cd10be49ffe39462abad48956ce3
https://github.com/sociomantic-tsunami/nessie-ui/blob/e2348045ebc6cd10be49ffe39462abad48956ce3/docs/assets/app.js#L40951-L40976
20,657
larsvanbraam/vue-transition-component
build-tools/script/deploy-utils.js
connectToServer
async function connectToServer(client, config) { return new Promise((resolve, reject) => { client .on('ready', error => (error ? reject(error) : resolve(client))) .on('error', error => reject(error)) .connect(config); }); }
javascript
async function connectToServer(client, config) { return new Promise((resolve, reject) => { client .on('ready', error => (error ? reject(error) : resolve(client))) .on('error', error => reject(error)) .connect(config); }); }
[ "async", "function", "connectToServer", "(", "client", ",", "config", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "client", ".", "on", "(", "'ready'", ",", "error", "=>", "(", "error", "?", "reject", "(", "error", ")", ":", "resolve", "(", "client", ")", ")", ")", ".", "on", "(", "'error'", ",", "error", "=>", "reject", "(", "error", ")", ")", ".", "connect", "(", "config", ")", ";", "}", ")", ";", "}" ]
Create a connection to the server @returns {Promise<*>}
[ "Create", "a", "connection", "to", "the", "server" ]
bad27770dff1004973ec6c18fbf59103248742c9
https://github.com/larsvanbraam/vue-transition-component/blob/bad27770dff1004973ec6c18fbf59103248742c9/build-tools/script/deploy-utils.js#L7-L14
20,658
larsvanbraam/vue-transition-component
build-tools/script/deploy-utils.js
createSftpConnection
async function createSftpConnection(client) { return new Promise((resolve, reject) => { client.sftp((error, sftp) => (error ? reject(error) : resolve(sftp))); }); }
javascript
async function createSftpConnection(client) { return new Promise((resolve, reject) => { client.sftp((error, sftp) => (error ? reject(error) : resolve(sftp))); }); }
[ "async", "function", "createSftpConnection", "(", "client", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "client", ".", "sftp", "(", "(", "error", ",", "sftp", ")", "=>", "(", "error", "?", "reject", "(", "error", ")", ":", "resolve", "(", "sftp", ")", ")", ")", ";", "}", ")", ";", "}" ]
Create an SFTP connection @param client @returns {Promise<*>}
[ "Create", "an", "SFTP", "connection" ]
bad27770dff1004973ec6c18fbf59103248742c9
https://github.com/larsvanbraam/vue-transition-component/blob/bad27770dff1004973ec6c18fbf59103248742c9/build-tools/script/deploy-utils.js#L21-L25
20,659
larsvanbraam/vue-transition-component
build-tools/script/deploy-utils.js
readDirectory
async function readDirectory(sftp, path) { return new Promise(resolve => { sftp.readdir(path, (error, list) => { resolve(list || null); }); }); }
javascript
async function readDirectory(sftp, path) { return new Promise(resolve => { sftp.readdir(path, (error, list) => { resolve(list || null); }); }); }
[ "async", "function", "readDirectory", "(", "sftp", ",", "path", ")", "{", "return", "new", "Promise", "(", "resolve", "=>", "{", "sftp", ".", "readdir", "(", "path", ",", "(", "error", ",", "list", ")", "=>", "{", "resolve", "(", "list", "||", "null", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Read a directory @param sftp @param path @returns {Promise<*>}
[ "Read", "a", "directory" ]
bad27770dff1004973ec6c18fbf59103248742c9
https://github.com/larsvanbraam/vue-transition-component/blob/bad27770dff1004973ec6c18fbf59103248742c9/build-tools/script/deploy-utils.js#L33-L39
20,660
larsvanbraam/vue-transition-component
build-tools/script/deploy-utils.js
createDirectory
async function createDirectory(sftp, path) { return new Promise((resolve, reject) => { sftp.mkdir(path, error => (error ? reject(error) : resolve())); }); }
javascript
async function createDirectory(sftp, path) { return new Promise((resolve, reject) => { sftp.mkdir(path, error => (error ? reject(error) : resolve())); }); }
[ "async", "function", "createDirectory", "(", "sftp", ",", "path", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "sftp", ".", "mkdir", "(", "path", ",", "error", "=>", "(", "error", "?", "reject", "(", "error", ")", ":", "resolve", "(", ")", ")", ")", ";", "}", ")", ";", "}" ]
Create a directory on the server @param sftp @param path @returns {Promise<*>}
[ "Create", "a", "directory", "on", "the", "server" ]
bad27770dff1004973ec6c18fbf59103248742c9
https://github.com/larsvanbraam/vue-transition-component/blob/bad27770dff1004973ec6c18fbf59103248742c9/build-tools/script/deploy-utils.js#L48-L52
20,661
larsvanbraam/vue-transition-component
build-tools/script/deploy-utils.js
uploadFile
async function uploadFile(sftp, source, target) { return new Promise((resolve, reject) => { sftp.fastPut(source, target, error => (error ? reject(error) : resolve())); }); }
javascript
async function uploadFile(sftp, source, target) { return new Promise((resolve, reject) => { sftp.fastPut(source, target, error => (error ? reject(error) : resolve())); }); }
[ "async", "function", "uploadFile", "(", "sftp", ",", "source", ",", "target", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "sftp", ".", "fastPut", "(", "source", ",", "target", ",", "error", "=>", "(", "error", "?", "reject", "(", "error", ")", ":", "resolve", "(", ")", ")", ")", ";", "}", ")", ";", "}" ]
Upload a file to the provided ftp server @param sftp @param source @param target @returns {Promise<*>}
[ "Upload", "a", "file", "to", "the", "provided", "ftp", "server" ]
bad27770dff1004973ec6c18fbf59103248742c9
https://github.com/larsvanbraam/vue-transition-component/blob/bad27770dff1004973ec6c18fbf59103248742c9/build-tools/script/deploy-utils.js#L73-L77
20,662
nodeshift/openshift-rest-client
lib/openshift-rest-client.js
getNames
function getNames (resourceType) { const aliases = [resourceType]; if (resourceAliases[resourceType]) { return aliases.concat(resourceAliases[resourceType]); } return alias(resourceType); }
javascript
function getNames (resourceType) { const aliases = [resourceType]; if (resourceAliases[resourceType]) { return aliases.concat(resourceAliases[resourceType]); } return alias(resourceType); }
[ "function", "getNames", "(", "resourceType", ")", "{", "const", "aliases", "=", "[", "resourceType", "]", ";", "if", "(", "resourceAliases", "[", "resourceType", "]", ")", "{", "return", "aliases", ".", "concat", "(", "resourceAliases", "[", "resourceType", "]", ")", ";", "}", "return", "alias", "(", "resourceType", ")", ";", "}" ]
function is passed in and called by the kubernetes-client to add the openshift aliases
[ "function", "is", "passed", "in", "and", "called", "by", "the", "kubernetes", "-", "client", "to", "add", "the", "openshift", "aliases" ]
18cc69f469ab5f22596f8e915238ba4e6df363b5
https://github.com/nodeshift/openshift-rest-client/blob/18cc69f469ab5f22596f8e915238ba4e6df363b5/lib/openshift-rest-client.js#L47-L53
20,663
trustnote/trustnote-pow-common
p2p/network.js
addPeer
function addPeer( sPeer ) { if ( assocKnownPeers[ sPeer ] ) { return; } // // save to memory // assocKnownPeers[ sPeer ] = true; // // save to local storage // let sHost = getHostByPeer( sPeer ); addPeerHost ( sHost, () => { console.log( "will insert peer " + sPeer ); db.query( "INSERT " + db.getIgnore() + " INTO peers (peer_host, peer) VALUES (?,?)", [ sHost, sPeer ] ); } ); }
javascript
function addPeer( sPeer ) { if ( assocKnownPeers[ sPeer ] ) { return; } // // save to memory // assocKnownPeers[ sPeer ] = true; // // save to local storage // let sHost = getHostByPeer( sPeer ); addPeerHost ( sHost, () => { console.log( "will insert peer " + sPeer ); db.query( "INSERT " + db.getIgnore() + " INTO peers (peer_host, peer) VALUES (?,?)", [ sHost, sPeer ] ); } ); }
[ "function", "addPeer", "(", "sPeer", ")", "{", "if", "(", "assocKnownPeers", "[", "sPeer", "]", ")", "{", "return", ";", "}", "//", "//\tsave to memory", "//", "assocKnownPeers", "[", "sPeer", "]", "=", "true", ";", "//", "//\tsave to local storage", "//", "let", "sHost", "=", "getHostByPeer", "(", "sPeer", ")", ";", "addPeerHost", "(", "sHost", ",", "(", ")", "=>", "{", "console", ".", "log", "(", "\"will insert peer \"", "+", "sPeer", ")", ";", "db", ".", "query", "(", "\"INSERT \"", "+", "db", ".", "getIgnore", "(", ")", "+", "\" INTO peers (peer_host, peer) VALUES (?,?)\"", ",", "[", "sHost", ",", "sPeer", "]", ")", ";", "}", ")", ";", "}" ]
save peer to database @param {string} sPeer - 'wss://127.0.0.1:90000'
[ "save", "peer", "to", "database" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/p2p/network.js#L831-L856
20,664
trustnote/trustnote-pow-common
p2p/network.js
pushOutBoundPeersToExplorer
function pushOutBoundPeersToExplorer(){ if(!conf.IF_BYZANTINE) return; if (conf.bLight ) return; findOutboundPeerOrConnect ( explorerUrl, ( err, oWsByExplorerUrl ) => { if ( ! err ) { let arrOutboundPeerUrls = arrOutboundPeers.map(function (ws) { return ws.peer; }); sendJustsaying( oWsByExplorerUrl, 'push_outbound_peers', arrOutboundPeerUrls ); } } ); }
javascript
function pushOutBoundPeersToExplorer(){ if(!conf.IF_BYZANTINE) return; if (conf.bLight ) return; findOutboundPeerOrConnect ( explorerUrl, ( err, oWsByExplorerUrl ) => { if ( ! err ) { let arrOutboundPeerUrls = arrOutboundPeers.map(function (ws) { return ws.peer; }); sendJustsaying( oWsByExplorerUrl, 'push_outbound_peers', arrOutboundPeerUrls ); } } ); }
[ "function", "pushOutBoundPeersToExplorer", "(", ")", "{", "if", "(", "!", "conf", ".", "IF_BYZANTINE", ")", "return", ";", "if", "(", "conf", ".", "bLight", ")", "return", ";", "findOutboundPeerOrConnect", "(", "explorerUrl", ",", "(", "err", ",", "oWsByExplorerUrl", ")", "=>", "{", "if", "(", "!", "err", ")", "{", "let", "arrOutboundPeerUrls", "=", "arrOutboundPeers", ".", "map", "(", "function", "(", "ws", ")", "{", "return", "ws", ".", "peer", ";", "}", ")", ";", "sendJustsaying", "(", "oWsByExplorerUrl", ",", "'push_outbound_peers'", ",", "arrOutboundPeerUrls", ")", ";", "}", "}", ")", ";", "}" ]
push the arrOutboundPeers to explorer
[ "push", "the", "arrOutboundPeers", "to", "explorer" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/p2p/network.js#L1181-L1200
20,665
trustnote/trustnote-pow-common
p2p/network.js
sumOnLinePeers
function sumOnLinePeers() { let nowTime = Date.now(); assocOnlinePeers = {}; Object.keys(assocAllOutBoundPeers).forEach(function(curUrl){ var curPeers = assocAllOutBoundPeers[curUrl]; if(nowTime - parseInt(curPeers.time) < 3 * 60 * 1000){ for (var j=0; j<curPeers.peers.length; j++){ if(assocOnlinePeers[curPeers.peers[j]]) assocOnlinePeers[curPeers.peers[j]]++; else assocOnlinePeers[curPeers.peers[j]] = 1; } } }); }
javascript
function sumOnLinePeers() { let nowTime = Date.now(); assocOnlinePeers = {}; Object.keys(assocAllOutBoundPeers).forEach(function(curUrl){ var curPeers = assocAllOutBoundPeers[curUrl]; if(nowTime - parseInt(curPeers.time) < 3 * 60 * 1000){ for (var j=0; j<curPeers.peers.length; j++){ if(assocOnlinePeers[curPeers.peers[j]]) assocOnlinePeers[curPeers.peers[j]]++; else assocOnlinePeers[curPeers.peers[j]] = 1; } } }); }
[ "function", "sumOnLinePeers", "(", ")", "{", "let", "nowTime", "=", "Date", ".", "now", "(", ")", ";", "assocOnlinePeers", "=", "{", "}", ";", "Object", ".", "keys", "(", "assocAllOutBoundPeers", ")", ".", "forEach", "(", "function", "(", "curUrl", ")", "{", "var", "curPeers", "=", "assocAllOutBoundPeers", "[", "curUrl", "]", ";", "if", "(", "nowTime", "-", "parseInt", "(", "curPeers", ".", "time", ")", "<", "3", "*", "60", "*", "1000", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "curPeers", ".", "peers", ".", "length", ";", "j", "++", ")", "{", "if", "(", "assocOnlinePeers", "[", "curPeers", ".", "peers", "[", "j", "]", "]", ")", "assocOnlinePeers", "[", "curPeers", ".", "peers", "[", "j", "]", "]", "++", ";", "else", "assocOnlinePeers", "[", "curPeers", ".", "peers", "[", "j", "]", "]", "=", "1", ";", "}", "}", "}", ")", ";", "}" ]
Summary online peers
[ "Summary", "online", "peers" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/p2p/network.js#L1203-L1217
20,666
trustnote/trustnote-pow-common
p2p/network.js
getOnLinePeers
function getOnLinePeers() { var arrOnlinePeers = []; function compare(){ return function(a,b){ return b['count'] - a['count']; } } Object.keys(assocOnlinePeers).forEach(function(curUrl){ arrOnlinePeers.push({peer:curUrl, count:assocOnlinePeers[curUrl]}); }) if(arrOnlinePeers.length === 0) return []; else return arrOnlinePeers.sort(compare()); }
javascript
function getOnLinePeers() { var arrOnlinePeers = []; function compare(){ return function(a,b){ return b['count'] - a['count']; } } Object.keys(assocOnlinePeers).forEach(function(curUrl){ arrOnlinePeers.push({peer:curUrl, count:assocOnlinePeers[curUrl]}); }) if(arrOnlinePeers.length === 0) return []; else return arrOnlinePeers.sort(compare()); }
[ "function", "getOnLinePeers", "(", ")", "{", "var", "arrOnlinePeers", "=", "[", "]", ";", "function", "compare", "(", ")", "{", "return", "function", "(", "a", ",", "b", ")", "{", "return", "b", "[", "'count'", "]", "-", "a", "[", "'count'", "]", ";", "}", "}", "Object", ".", "keys", "(", "assocOnlinePeers", ")", ".", "forEach", "(", "function", "(", "curUrl", ")", "{", "arrOnlinePeers", ".", "push", "(", "{", "peer", ":", "curUrl", ",", "count", ":", "assocOnlinePeers", "[", "curUrl", "]", "}", ")", ";", "}", ")", "if", "(", "arrOnlinePeers", ".", "length", "===", "0", ")", "return", "[", "]", ";", "else", "return", "arrOnlinePeers", ".", "sort", "(", "compare", "(", ")", ")", ";", "}" ]
Gets the online node, sorted by count
[ "Gets", "the", "online", "node", "sorted", "by", "count" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/p2p/network.js#L1220-L1236
20,667
trustnote/trustnote-pow-common
p2p/network.js
notifyLightClientsAboutStableJoints
function notifyLightClientsAboutStableJoints(from_mci, to_mci) { db.query( "SELECT peer FROM units JOIN unit_authors USING(unit) JOIN watched_light_addresses USING(address) \n\ WHERE main_chain_index>? AND main_chain_index<=? \n\ UNION \n\ SELECT peer FROM units JOIN outputs USING(unit) JOIN watched_light_addresses USING(address) \n\ WHERE main_chain_index>? AND main_chain_index<=? \n\ UNION \n\ SELECT peer FROM units JOIN watched_light_units USING(unit) \n\ WHERE main_chain_index>? AND main_chain_index<=?", [from_mci, to_mci, from_mci, to_mci, from_mci, to_mci], function (rows) { rows.forEach(function (row) { let ws = getPeerWebSocket(row.peer); if (ws && ws.readyState === ws.OPEN) sendJustsaying(ws, 'light/have_updates'); }); db.query("DELETE FROM watched_light_units \n\ WHERE unit IN (SELECT unit FROM units WHERE main_chain_index>? AND main_chain_index<=?)", [from_mci, to_mci], function () { }); } ); }
javascript
function notifyLightClientsAboutStableJoints(from_mci, to_mci) { db.query( "SELECT peer FROM units JOIN unit_authors USING(unit) JOIN watched_light_addresses USING(address) \n\ WHERE main_chain_index>? AND main_chain_index<=? \n\ UNION \n\ SELECT peer FROM units JOIN outputs USING(unit) JOIN watched_light_addresses USING(address) \n\ WHERE main_chain_index>? AND main_chain_index<=? \n\ UNION \n\ SELECT peer FROM units JOIN watched_light_units USING(unit) \n\ WHERE main_chain_index>? AND main_chain_index<=?", [from_mci, to_mci, from_mci, to_mci, from_mci, to_mci], function (rows) { rows.forEach(function (row) { let ws = getPeerWebSocket(row.peer); if (ws && ws.readyState === ws.OPEN) sendJustsaying(ws, 'light/have_updates'); }); db.query("DELETE FROM watched_light_units \n\ WHERE unit IN (SELECT unit FROM units WHERE main_chain_index>? AND main_chain_index<=?)", [from_mci, to_mci], function () { }); } ); }
[ "function", "notifyLightClientsAboutStableJoints", "(", "from_mci", ",", "to_mci", ")", "{", "db", ".", "query", "(", "\"SELECT peer FROM units JOIN unit_authors USING(unit) JOIN watched_light_addresses USING(address) \\n\\\n\t\tWHERE main_chain_index>? AND main_chain_index<=? \\n\\\n\t\tUNION \\n\\\n\t\tSELECT peer FROM units JOIN outputs USING(unit) JOIN watched_light_addresses USING(address) \\n\\\n\t\tWHERE main_chain_index>? AND main_chain_index<=? \\n\\\n\t\tUNION \\n\\\n\t\tSELECT peer FROM units JOIN watched_light_units USING(unit) \\n\\\n\t\tWHERE main_chain_index>? AND main_chain_index<=?\"", ",", "[", "from_mci", ",", "to_mci", ",", "from_mci", ",", "to_mci", ",", "from_mci", ",", "to_mci", "]", ",", "function", "(", "rows", ")", "{", "rows", ".", "forEach", "(", "function", "(", "row", ")", "{", "let", "ws", "=", "getPeerWebSocket", "(", "row", ".", "peer", ")", ";", "if", "(", "ws", "&&", "ws", ".", "readyState", "===", "ws", ".", "OPEN", ")", "sendJustsaying", "(", "ws", ",", "'light/have_updates'", ")", ";", "}", ")", ";", "db", ".", "query", "(", "\"DELETE FROM watched_light_units \\n\\\n\t\t\t\tWHERE unit IN (SELECT unit FROM units WHERE main_chain_index>? AND main_chain_index<=?)\"", ",", "[", "from_mci", ",", "to_mci", "]", ",", "function", "(", ")", "{", "}", ")", ";", "}", ")", ";", "}" ]
from_mci is non-inclusive, to_mci is inclusive
[ "from_mci", "is", "non", "-", "inclusive", "to_mci", "is", "inclusive" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/p2p/network.js#L1961-L1984
20,668
trustnote/trustnote-pow-common
p2p/network.js
requestCatchup_Dev
function requestCatchup_Dev(oWebSocket, oRequestData) { // // { last_stable_mci: last_stable_mci, last_known_mci: last_known_mci } // if (!_bUnitTestEnv) { return console.log(`this function only works in dev env.`); } return sendRequest ( oWebSocket, 'catchup', oRequestData, true, handleCatchupChain ); }
javascript
function requestCatchup_Dev(oWebSocket, oRequestData) { // // { last_stable_mci: last_stable_mci, last_known_mci: last_known_mci } // if (!_bUnitTestEnv) { return console.log(`this function only works in dev env.`); } return sendRequest ( oWebSocket, 'catchup', oRequestData, true, handleCatchupChain ); }
[ "function", "requestCatchup_Dev", "(", "oWebSocket", ",", "oRequestData", ")", "{", "//", "//\t{ last_stable_mci: last_stable_mci, last_known_mci: last_known_mci }", "//", "if", "(", "!", "_bUnitTestEnv", ")", "{", "return", "console", ".", "log", "(", "`", "`", ")", ";", "}", "return", "sendRequest", "(", "oWebSocket", ",", "'catchup'", ",", "oRequestData", ",", "true", ",", "handleCatchupChain", ")", ";", "}" ]
request catchup in dev @param {object} oWebSocket @param {object} oRequestData @param {number} oRequestData.last_stable_mci @param {number} oRequestData.last_known_mci @return {*}
[ "request", "catchup", "in", "dev" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/p2p/network.js#L2241-L2257
20,669
trustnote/trustnote-pow-common
p2p/network.js
sendPrivatePayment
function sendPrivatePayment(peer, arrChains) { let ws = getPeerWebSocket(peer); if (ws) return sendPrivatePaymentToWs(ws, arrChains); findOutboundPeerOrConnect(peer, function (err, ws) { if (!err) sendPrivatePaymentToWs(ws, arrChains); }); }
javascript
function sendPrivatePayment(peer, arrChains) { let ws = getPeerWebSocket(peer); if (ws) return sendPrivatePaymentToWs(ws, arrChains); findOutboundPeerOrConnect(peer, function (err, ws) { if (!err) sendPrivatePaymentToWs(ws, arrChains); }); }
[ "function", "sendPrivatePayment", "(", "peer", ",", "arrChains", ")", "{", "let", "ws", "=", "getPeerWebSocket", "(", "peer", ")", ";", "if", "(", "ws", ")", "return", "sendPrivatePaymentToWs", "(", "ws", ",", "arrChains", ")", ";", "findOutboundPeerOrConnect", "(", "peer", ",", "function", "(", "err", ",", "ws", ")", "{", "if", "(", "!", "err", ")", "sendPrivatePaymentToWs", "(", "ws", ",", "arrChains", ")", ";", "}", ")", ";", "}" ]
sends multiple private payloads and their corresponding chains
[ "sends", "multiple", "private", "payloads", "and", "their", "corresponding", "chains" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/p2p/network.js#L2384-L2393
20,670
trustnote/trustnote-pow-common
catchup/catchup.js
readHashTree
function readHashTree( hashTreeRequest, callbacks ) { let from_ball = hashTreeRequest.from_ball; let to_ball = hashTreeRequest.to_ball; if ( 'string' !== typeof from_ball ) { return callbacks.ifError( "no from_ball" ); } if ( 'string' !== typeof to_ball ) { return callbacks.ifError( "no to_ball" ); } let from_mci; let to_mci; _db.query ( "SELECT is_stable, is_on_main_chain, main_chain_index, ball FROM balls JOIN units USING(unit) WHERE ball IN(?,?)", [ from_ball, to_ball ], function( rows ) { if ( rows.length !== 2 ) { return callbacks.ifError( "some balls not found" ); } for ( let i = 0; i < rows.length; i++ ) { let props = rows[ i ]; if ( props.is_stable !== 1 ) { return callbacks.ifError( "some balls not stable" ); } if ( props.is_on_main_chain !== 1 ) { return callbacks.ifError( "some balls not on mc" ); } if ( props.ball === from_ball ) { from_mci = props.main_chain_index; } else if ( props.ball === to_ball ) { to_mci = props.main_chain_index; } } if ( from_mci >= to_mci ) { return callbacks.ifError( "from is after to" ); } let arrBalls = []; let op = ( from_mci === 0 ) ? ">=" : ">"; // if starting from 0, add genesis itself _db.query ( "SELECT unit, ball, content_hash FROM units LEFT JOIN balls USING(unit) \n\ WHERE main_chain_index " + op + " ? AND main_chain_index<=? ORDER BY `level`", [ from_mci, to_mci ], function( ball_rows ) { _async.eachSeries ( ball_rows, function( objBall, cb ) { if ( ! objBall.ball ) { throw Error( "no ball for unit " + objBall.unit ); } if ( objBall.content_hash ) { objBall.is_nonserial = true; } // ... delete objBall.content_hash; _db.query ( "SELECT ball FROM parenthoods LEFT JOIN balls ON parent_unit=balls.unit WHERE child_unit=? ORDER BY ball", [ objBall.unit ], function( parent_rows ) { if ( parent_rows.some(function(parent_row){ return ! parent_row.ball; })) { throw Error( "some parents have no balls" ); } if ( parent_rows.length > 0 ) { objBall.parent_balls = parent_rows.map(function(parent_row){ return parent_row.ball; }); } // // just collect skiplist balls // _db.query ( "SELECT ball FROM skiplist_units LEFT JOIN balls ON skiplist_unit=balls.unit WHERE skiplist_units.unit=? ORDER BY ball", [ objBall.unit ], function( srows ) { if ( srows.some(function(srow){ return ! srow.ball; })) { throw Error("some skiplist units have no balls"); } if ( srows.length > 0) { objBall.skiplist_balls = srows.map(function(srow){ return srow.ball; }); } // ... arrBalls.push( objBall ); // ... cb(); } ); } ); }, function() { callbacks.ifOk( arrBalls ); } ); } ); } ); }
javascript
function readHashTree( hashTreeRequest, callbacks ) { let from_ball = hashTreeRequest.from_ball; let to_ball = hashTreeRequest.to_ball; if ( 'string' !== typeof from_ball ) { return callbacks.ifError( "no from_ball" ); } if ( 'string' !== typeof to_ball ) { return callbacks.ifError( "no to_ball" ); } let from_mci; let to_mci; _db.query ( "SELECT is_stable, is_on_main_chain, main_chain_index, ball FROM balls JOIN units USING(unit) WHERE ball IN(?,?)", [ from_ball, to_ball ], function( rows ) { if ( rows.length !== 2 ) { return callbacks.ifError( "some balls not found" ); } for ( let i = 0; i < rows.length; i++ ) { let props = rows[ i ]; if ( props.is_stable !== 1 ) { return callbacks.ifError( "some balls not stable" ); } if ( props.is_on_main_chain !== 1 ) { return callbacks.ifError( "some balls not on mc" ); } if ( props.ball === from_ball ) { from_mci = props.main_chain_index; } else if ( props.ball === to_ball ) { to_mci = props.main_chain_index; } } if ( from_mci >= to_mci ) { return callbacks.ifError( "from is after to" ); } let arrBalls = []; let op = ( from_mci === 0 ) ? ">=" : ">"; // if starting from 0, add genesis itself _db.query ( "SELECT unit, ball, content_hash FROM units LEFT JOIN balls USING(unit) \n\ WHERE main_chain_index " + op + " ? AND main_chain_index<=? ORDER BY `level`", [ from_mci, to_mci ], function( ball_rows ) { _async.eachSeries ( ball_rows, function( objBall, cb ) { if ( ! objBall.ball ) { throw Error( "no ball for unit " + objBall.unit ); } if ( objBall.content_hash ) { objBall.is_nonserial = true; } // ... delete objBall.content_hash; _db.query ( "SELECT ball FROM parenthoods LEFT JOIN balls ON parent_unit=balls.unit WHERE child_unit=? ORDER BY ball", [ objBall.unit ], function( parent_rows ) { if ( parent_rows.some(function(parent_row){ return ! parent_row.ball; })) { throw Error( "some parents have no balls" ); } if ( parent_rows.length > 0 ) { objBall.parent_balls = parent_rows.map(function(parent_row){ return parent_row.ball; }); } // // just collect skiplist balls // _db.query ( "SELECT ball FROM skiplist_units LEFT JOIN balls ON skiplist_unit=balls.unit WHERE skiplist_units.unit=? ORDER BY ball", [ objBall.unit ], function( srows ) { if ( srows.some(function(srow){ return ! srow.ball; })) { throw Error("some skiplist units have no balls"); } if ( srows.length > 0) { objBall.skiplist_balls = srows.map(function(srow){ return srow.ball; }); } // ... arrBalls.push( objBall ); // ... cb(); } ); } ); }, function() { callbacks.ifOk( arrBalls ); } ); } ); } ); }
[ "function", "readHashTree", "(", "hashTreeRequest", ",", "callbacks", ")", "{", "let", "from_ball", "=", "hashTreeRequest", ".", "from_ball", ";", "let", "to_ball", "=", "hashTreeRequest", ".", "to_ball", ";", "if", "(", "'string'", "!==", "typeof", "from_ball", ")", "{", "return", "callbacks", ".", "ifError", "(", "\"no from_ball\"", ")", ";", "}", "if", "(", "'string'", "!==", "typeof", "to_ball", ")", "{", "return", "callbacks", ".", "ifError", "(", "\"no to_ball\"", ")", ";", "}", "let", "from_mci", ";", "let", "to_mci", ";", "_db", ".", "query", "(", "\"SELECT is_stable, is_on_main_chain, main_chain_index, ball FROM balls JOIN units USING(unit) WHERE ball IN(?,?)\"", ",", "[", "from_ball", ",", "to_ball", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "!==", "2", ")", "{", "return", "callbacks", ".", "ifError", "(", "\"some balls not found\"", ")", ";", "}", "for", "(", "let", "i", "=", "0", ";", "i", "<", "rows", ".", "length", ";", "i", "++", ")", "{", "let", "props", "=", "rows", "[", "i", "]", ";", "if", "(", "props", ".", "is_stable", "!==", "1", ")", "{", "return", "callbacks", ".", "ifError", "(", "\"some balls not stable\"", ")", ";", "}", "if", "(", "props", ".", "is_on_main_chain", "!==", "1", ")", "{", "return", "callbacks", ".", "ifError", "(", "\"some balls not on mc\"", ")", ";", "}", "if", "(", "props", ".", "ball", "===", "from_ball", ")", "{", "from_mci", "=", "props", ".", "main_chain_index", ";", "}", "else", "if", "(", "props", ".", "ball", "===", "to_ball", ")", "{", "to_mci", "=", "props", ".", "main_chain_index", ";", "}", "}", "if", "(", "from_mci", ">=", "to_mci", ")", "{", "return", "callbacks", ".", "ifError", "(", "\"from is after to\"", ")", ";", "}", "let", "arrBalls", "=", "[", "]", ";", "let", "op", "=", "(", "from_mci", "===", "0", ")", "?", "\">=\"", ":", "\">\"", ";", "//\tif starting from 0, add genesis itself", "_db", ".", "query", "(", "\"SELECT unit, ball, content_hash FROM units LEFT JOIN balls USING(unit) \\n\\\n\t\t\t\tWHERE main_chain_index \"", "+", "op", "+", "\" ? AND main_chain_index<=? ORDER BY `level`\"", ",", "[", "from_mci", ",", "to_mci", "]", ",", "function", "(", "ball_rows", ")", "{", "_async", ".", "eachSeries", "(", "ball_rows", ",", "function", "(", "objBall", ",", "cb", ")", "{", "if", "(", "!", "objBall", ".", "ball", ")", "{", "throw", "Error", "(", "\"no ball for unit \"", "+", "objBall", ".", "unit", ")", ";", "}", "if", "(", "objBall", ".", "content_hash", ")", "{", "objBall", ".", "is_nonserial", "=", "true", ";", "}", "//\t...", "delete", "objBall", ".", "content_hash", ";", "_db", ".", "query", "(", "\"SELECT ball FROM parenthoods LEFT JOIN balls ON parent_unit=balls.unit WHERE child_unit=? ORDER BY ball\"", ",", "[", "objBall", ".", "unit", "]", ",", "function", "(", "parent_rows", ")", "{", "if", "(", "parent_rows", ".", "some", "(", "function", "(", "parent_row", ")", "{", "return", "!", "parent_row", ".", "ball", ";", "}", ")", ")", "{", "throw", "Error", "(", "\"some parents have no balls\"", ")", ";", "}", "if", "(", "parent_rows", ".", "length", ">", "0", ")", "{", "objBall", ".", "parent_balls", "=", "parent_rows", ".", "map", "(", "function", "(", "parent_row", ")", "{", "return", "parent_row", ".", "ball", ";", "}", ")", ";", "}", "//", "//\tjust collect skiplist balls", "//", "_db", ".", "query", "(", "\"SELECT ball FROM skiplist_units LEFT JOIN balls ON skiplist_unit=balls.unit WHERE skiplist_units.unit=? ORDER BY ball\"", ",", "[", "objBall", ".", "unit", "]", ",", "function", "(", "srows", ")", "{", "if", "(", "srows", ".", "some", "(", "function", "(", "srow", ")", "{", "return", "!", "srow", ".", "ball", ";", "}", ")", ")", "{", "throw", "Error", "(", "\"some skiplist units have no balls\"", ")", ";", "}", "if", "(", "srows", ".", "length", ">", "0", ")", "{", "objBall", ".", "skiplist_balls", "=", "srows", ".", "map", "(", "function", "(", "srow", ")", "{", "return", "srow", ".", "ball", ";", "}", ")", ";", "}", "//\t...", "arrBalls", ".", "push", "(", "objBall", ")", ";", "//\t...", "cb", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ",", "function", "(", ")", "{", "callbacks", ".", "ifOk", "(", "arrBalls", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
read hash tree @param {object} hashTreeRequest @param {object} callbacks @return {*}
[ "read", "hash", "tree" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/catchup/catchup.js#L796-L930
20,671
trustnote/trustnote-pow-common
catchup/catchup.js
updateLastRoundIndexFromPeers
function updateLastRoundIndexFromPeers( nLastRoundIndex, nLastMainChainIndex ) { if ( 'number' === typeof nLastRoundIndex && nLastRoundIndex > 0 && 'number' === typeof nLastMainChainIndex && nLastMainChainIndex > 0 ) { if ( null === _nLastRoundIndexFromPeers || nLastRoundIndex > _nLastRoundIndexFromPeers || null === _nLastMainChainIndexFromPeers || nLastMainChainIndex > _nLastMainChainIndexFromPeers ) { _nLastRoundIndexFromPeers = nLastRoundIndex; _nLastMainChainIndexFromPeers = nLastMainChainIndex; _event_bus.emit( 'updated_last_round_index_from_peers', _nLastRoundIndexFromPeers, _nLastMainChainIndexFromPeers ); } } }
javascript
function updateLastRoundIndexFromPeers( nLastRoundIndex, nLastMainChainIndex ) { if ( 'number' === typeof nLastRoundIndex && nLastRoundIndex > 0 && 'number' === typeof nLastMainChainIndex && nLastMainChainIndex > 0 ) { if ( null === _nLastRoundIndexFromPeers || nLastRoundIndex > _nLastRoundIndexFromPeers || null === _nLastMainChainIndexFromPeers || nLastMainChainIndex > _nLastMainChainIndexFromPeers ) { _nLastRoundIndexFromPeers = nLastRoundIndex; _nLastMainChainIndexFromPeers = nLastMainChainIndex; _event_bus.emit( 'updated_last_round_index_from_peers', _nLastRoundIndexFromPeers, _nLastMainChainIndexFromPeers ); } } }
[ "function", "updateLastRoundIndexFromPeers", "(", "nLastRoundIndex", ",", "nLastMainChainIndex", ")", "{", "if", "(", "'number'", "===", "typeof", "nLastRoundIndex", "&&", "nLastRoundIndex", ">", "0", "&&", "'number'", "===", "typeof", "nLastMainChainIndex", "&&", "nLastMainChainIndex", ">", "0", ")", "{", "if", "(", "null", "===", "_nLastRoundIndexFromPeers", "||", "nLastRoundIndex", ">", "_nLastRoundIndexFromPeers", "||", "null", "===", "_nLastMainChainIndexFromPeers", "||", "nLastMainChainIndex", ">", "_nLastMainChainIndexFromPeers", ")", "{", "_nLastRoundIndexFromPeers", "=", "nLastRoundIndex", ";", "_nLastMainChainIndexFromPeers", "=", "nLastMainChainIndex", ";", "_event_bus", ".", "emit", "(", "'updated_last_round_index_from_peers'", ",", "_nLastRoundIndexFromPeers", ",", "_nLastMainChainIndexFromPeers", ")", ";", "}", "}", "}" ]
update last round index from all outbound peers @return {void}
[ "update", "last", "round", "index", "from", "all", "outbound", "peers" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/catchup/catchup.js#L1149-L1162
20,672
trustnote/trustnote-pow-common
validation/validation.js
function(cb){ deposit.getDepositAddressBySupernodeAddress(conn, objUnit.authors[0].address, function (err,depositAddress){ if(err) return cb(err + " can not send pow unit"); if(payload.deposit != depositAddress) return cb("pow unit deposit address is invalid expeected :" + depositAddress +" Actual :" + payload.deposit); deposit.getBalanceOfDepositContract(conn, depositAddress,objUnit.round_index, function (err,balance){ if(err) return cb(err); depositBalance = balance; cb(); }); }); }
javascript
function(cb){ deposit.getDepositAddressBySupernodeAddress(conn, objUnit.authors[0].address, function (err,depositAddress){ if(err) return cb(err + " can not send pow unit"); if(payload.deposit != depositAddress) return cb("pow unit deposit address is invalid expeected :" + depositAddress +" Actual :" + payload.deposit); deposit.getBalanceOfDepositContract(conn, depositAddress,objUnit.round_index, function (err,balance){ if(err) return cb(err); depositBalance = balance; cb(); }); }); }
[ "function", "(", "cb", ")", "{", "deposit", ".", "getDepositAddressBySupernodeAddress", "(", "conn", ",", "objUnit", ".", "authors", "[", "0", "]", ".", "address", ",", "function", "(", "err", ",", "depositAddress", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", "+", "\" can not send pow unit\"", ")", ";", "if", "(", "payload", ".", "deposit", "!=", "depositAddress", ")", "return", "cb", "(", "\"pow unit deposit address is invalid expeected :\"", "+", "depositAddress", "+", "\" Actual :\"", "+", "payload", ".", "deposit", ")", ";", "deposit", ".", "getBalanceOfDepositContract", "(", "conn", ",", "depositAddress", ",", "objUnit", ".", "round_index", ",", "function", "(", "err", ",", "balance", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "depositBalance", "=", "balance", ";", "cb", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
check deposit address is valid and balance
[ "check", "deposit", "address", "is", "valid", "and", "balance" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/validation/validation.js#L1361-L1374
20,673
trustnote/trustnote-pow-common
p2p/gossiper.js
gossiperOnReceivedMessage
function gossiperOnReceivedMessage( oWs, oMessage ) { try { _oGossiper.onReceivedMessage( oWs, oMessage ); } catch( oException ) { console.error( `GOSSIPER ))) gossiperOnReceivedMessage occurred an exception: ${ JSON.stringify( oException ) }` ); } }
javascript
function gossiperOnReceivedMessage( oWs, oMessage ) { try { _oGossiper.onReceivedMessage( oWs, oMessage ); } catch( oException ) { console.error( `GOSSIPER ))) gossiperOnReceivedMessage occurred an exception: ${ JSON.stringify( oException ) }` ); } }
[ "function", "gossiperOnReceivedMessage", "(", "oWs", ",", "oMessage", ")", "{", "try", "{", "_oGossiper", ".", "onReceivedMessage", "(", "oWs", ",", "oMessage", ")", ";", "}", "catch", "(", "oException", ")", "{", "console", ".", "error", "(", "`", "${", "JSON", ".", "stringify", "(", "oException", ")", "}", "`", ")", ";", "}", "}" ]
on received gossiper message @param {object} oWs @param {object} oMessage @return {void}
[ "on", "received", "gossiper", "message" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/p2p/gossiper.js#L137-L147
20,674
trustnote/trustnote-pow-common
p2p/gossiper.js
_gossiperStartWithOptions
function _gossiperStartWithOptions( oOptions ) { // // create Gossiper instance // _oGossiper = new Gossiper( oOptions ); // // listen ... // _oGossiper.on( 'peer_update', ( sPeerUrl, sKey, vValue ) => { // console.log( `GOSSIPER ))) EVENT [peer_update] (${ GossiperUtils.isReservedKey( sKey ) ? "Reserved" : "Customized" }):: `, sPeerUrl, sKey, vValue ); // // callback while we received a update from remote peers // if ( ! GossiperUtils.isReservedKey( sKey ) ) { _oGossiperOptions.pfnPeerUpdate( sPeerUrl, sKey, vValue ); } }); _oGossiper.on( 'peer_alive', ( sPeerUrl ) => { // console.log( `GOSSIPER ))) EVENT [peer_alive] :: `, sPeerUrl ); }); _oGossiper.on( 'peer_failed', ( sPeerUrl ) => { console.error( `GOSSIPER ))) EVENT [peer_failed] :: `, sPeerUrl ); }); _oGossiper.on( 'new_peer', ( sPeerUrl ) => { // console.log( `GOSSIPER ))) EVENT [new_peer] :: `, sPeerUrl ); if ( sPeerUrl !== _oGossiperOptions.url && ! _oGossiper.m_oRouter.getSocket( sPeerUrl ) ) { // // try to connect to the new peer // _oGossiperOptions.pfnConnectToPeer( sPeerUrl, ( err, oNewWs ) => { if ( err ) { return console.error( `GOSSIPER ))) failed to connectToPeer: ${ sPeerUrl }.` ); } if ( ! oNewWs ) { return console.error( `GOSSIPER ))) connectToPeer returns an invalid oNewWs: ${ JSON.stringify( oNewWs ) }.` ); } // // update the remote socket // if ( ! DeUtilsCore.isPlainObjectWithKeys( oNewWs, 'url' ) || ! GossiperUtils.isValidPeerUrl( oNewWs.url ) ) { oNewWs.url = sPeerUrl; } // // update router // _oGossiper.updatePeerList({ [ sPeerUrl ] : oNewWs }); }); } }); _oGossiper.on( 'log', ( sType, vData ) => { // console.log( `GOSSIPER ))) EVENT [log/${ sType }] :: `, vData ); }); // // start gossiper // _oGossiper.start( {} ); }
javascript
function _gossiperStartWithOptions( oOptions ) { // // create Gossiper instance // _oGossiper = new Gossiper( oOptions ); // // listen ... // _oGossiper.on( 'peer_update', ( sPeerUrl, sKey, vValue ) => { // console.log( `GOSSIPER ))) EVENT [peer_update] (${ GossiperUtils.isReservedKey( sKey ) ? "Reserved" : "Customized" }):: `, sPeerUrl, sKey, vValue ); // // callback while we received a update from remote peers // if ( ! GossiperUtils.isReservedKey( sKey ) ) { _oGossiperOptions.pfnPeerUpdate( sPeerUrl, sKey, vValue ); } }); _oGossiper.on( 'peer_alive', ( sPeerUrl ) => { // console.log( `GOSSIPER ))) EVENT [peer_alive] :: `, sPeerUrl ); }); _oGossiper.on( 'peer_failed', ( sPeerUrl ) => { console.error( `GOSSIPER ))) EVENT [peer_failed] :: `, sPeerUrl ); }); _oGossiper.on( 'new_peer', ( sPeerUrl ) => { // console.log( `GOSSIPER ))) EVENT [new_peer] :: `, sPeerUrl ); if ( sPeerUrl !== _oGossiperOptions.url && ! _oGossiper.m_oRouter.getSocket( sPeerUrl ) ) { // // try to connect to the new peer // _oGossiperOptions.pfnConnectToPeer( sPeerUrl, ( err, oNewWs ) => { if ( err ) { return console.error( `GOSSIPER ))) failed to connectToPeer: ${ sPeerUrl }.` ); } if ( ! oNewWs ) { return console.error( `GOSSIPER ))) connectToPeer returns an invalid oNewWs: ${ JSON.stringify( oNewWs ) }.` ); } // // update the remote socket // if ( ! DeUtilsCore.isPlainObjectWithKeys( oNewWs, 'url' ) || ! GossiperUtils.isValidPeerUrl( oNewWs.url ) ) { oNewWs.url = sPeerUrl; } // // update router // _oGossiper.updatePeerList({ [ sPeerUrl ] : oNewWs }); }); } }); _oGossiper.on( 'log', ( sType, vData ) => { // console.log( `GOSSIPER ))) EVENT [log/${ sType }] :: `, vData ); }); // // start gossiper // _oGossiper.start( {} ); }
[ "function", "_gossiperStartWithOptions", "(", "oOptions", ")", "{", "//", "//\tcreate Gossiper instance", "//", "_oGossiper", "=", "new", "Gossiper", "(", "oOptions", ")", ";", "//", "//\tlisten ...", "//", "_oGossiper", ".", "on", "(", "'peer_update'", ",", "(", "sPeerUrl", ",", "sKey", ",", "vValue", ")", "=>", "{", "// console.log( `GOSSIPER ))) EVENT [peer_update] (${ GossiperUtils.isReservedKey( sKey ) ? \"Reserved\" : \"Customized\" }):: `, sPeerUrl, sKey, vValue );", "//", "//\tcallback while we received a update from remote peers", "//", "if", "(", "!", "GossiperUtils", ".", "isReservedKey", "(", "sKey", ")", ")", "{", "_oGossiperOptions", ".", "pfnPeerUpdate", "(", "sPeerUrl", ",", "sKey", ",", "vValue", ")", ";", "}", "}", ")", ";", "_oGossiper", ".", "on", "(", "'peer_alive'", ",", "(", "sPeerUrl", ")", "=>", "{", "// console.log( `GOSSIPER ))) EVENT [peer_alive] :: `, sPeerUrl );", "}", ")", ";", "_oGossiper", ".", "on", "(", "'peer_failed'", ",", "(", "sPeerUrl", ")", "=>", "{", "console", ".", "error", "(", "`", "`", ",", "sPeerUrl", ")", ";", "}", ")", ";", "_oGossiper", ".", "on", "(", "'new_peer'", ",", "(", "sPeerUrl", ")", "=>", "{", "// console.log( `GOSSIPER ))) EVENT [new_peer] :: `, sPeerUrl );", "if", "(", "sPeerUrl", "!==", "_oGossiperOptions", ".", "url", "&&", "!", "_oGossiper", ".", "m_oRouter", ".", "getSocket", "(", "sPeerUrl", ")", ")", "{", "//", "//\ttry to connect to the new peer", "//", "_oGossiperOptions", ".", "pfnConnectToPeer", "(", "sPeerUrl", ",", "(", "err", ",", "oNewWs", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "console", ".", "error", "(", "`", "${", "sPeerUrl", "}", "`", ")", ";", "}", "if", "(", "!", "oNewWs", ")", "{", "return", "console", ".", "error", "(", "`", "${", "JSON", ".", "stringify", "(", "oNewWs", ")", "}", "`", ")", ";", "}", "//", "//\tupdate the remote socket", "//", "if", "(", "!", "DeUtilsCore", ".", "isPlainObjectWithKeys", "(", "oNewWs", ",", "'url'", ")", "||", "!", "GossiperUtils", ".", "isValidPeerUrl", "(", "oNewWs", ".", "url", ")", ")", "{", "oNewWs", ".", "url", "=", "sPeerUrl", ";", "}", "//", "//\tupdate router", "//", "_oGossiper", ".", "updatePeerList", "(", "{", "[", "sPeerUrl", "]", ":", "oNewWs", "}", ")", ";", "}", ")", ";", "}", "}", ")", ";", "_oGossiper", ".", "on", "(", "'log'", ",", "(", "sType", ",", "vData", ")", "=>", "{", "// console.log( `GOSSIPER ))) EVENT [log/${ sType }] :: `, vData );", "}", ")", ";", "//", "//\tstart gossiper", "//", "_oGossiper", ".", "start", "(", "{", "}", ")", ";", "}" ]
start gossiper with options @param {object} oOptions @private
[ "start", "gossiper", "with", "options" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/p2p/gossiper.js#L247-L325
20,675
trustnote/trustnote-pow-common
mc/byzantine.js
initByzantine
function initByzantine(){ if(!conf.IF_BYZANTINE) return; if(bByzantineUnderWay) return; db.query( "SELECT main_chain_index FROM units \n\ WHERE is_on_main_chain=1 AND is_stable=1 AND +sequence='good' AND pow_type=? \n\ ORDER BY main_chain_index DESC LIMIT 1", [constants.POW_TYPE_TRUSTME], function(rows){ var hp = 1; // just after genesis or catchup from fresh start if (rows.length === 0){ db.query( "SELECT main_chain_index FROM units \n\ WHERE unit=?", [constants.GENESIS_UNIT], function(rowGenesis){ if(rowGenesis.length === 0){ setTimeout(function(){ initByzantine(); }, 3000); } else{ startPhase(hp, 0); } } ); } else if (rows.length === 1){ hp = rows[0].main_chain_index + 1; if(maxGossipHp === hp) { startPhase(hp, maxGossipPp); } else { setTimeout(function(){ initByzantine(); }, 3000); } } } ); }
javascript
function initByzantine(){ if(!conf.IF_BYZANTINE) return; if(bByzantineUnderWay) return; db.query( "SELECT main_chain_index FROM units \n\ WHERE is_on_main_chain=1 AND is_stable=1 AND +sequence='good' AND pow_type=? \n\ ORDER BY main_chain_index DESC LIMIT 1", [constants.POW_TYPE_TRUSTME], function(rows){ var hp = 1; // just after genesis or catchup from fresh start if (rows.length === 0){ db.query( "SELECT main_chain_index FROM units \n\ WHERE unit=?", [constants.GENESIS_UNIT], function(rowGenesis){ if(rowGenesis.length === 0){ setTimeout(function(){ initByzantine(); }, 3000); } else{ startPhase(hp, 0); } } ); } else if (rows.length === 1){ hp = rows[0].main_chain_index + 1; if(maxGossipHp === hp) { startPhase(hp, maxGossipPp); } else { setTimeout(function(){ initByzantine(); }, 3000); } } } ); }
[ "function", "initByzantine", "(", ")", "{", "if", "(", "!", "conf", ".", "IF_BYZANTINE", ")", "return", ";", "if", "(", "bByzantineUnderWay", ")", "return", ";", "db", ".", "query", "(", "\"SELECT main_chain_index FROM units \\n\\\n WHERE is_on_main_chain=1 AND is_stable=1 AND +sequence='good' AND pow_type=? \\n\\\n ORDER BY main_chain_index DESC LIMIT 1\"", ",", "[", "constants", ".", "POW_TYPE_TRUSTME", "]", ",", "function", "(", "rows", ")", "{", "var", "hp", "=", "1", ";", "// just after genesis or catchup from fresh start", "if", "(", "rows", ".", "length", "===", "0", ")", "{", "db", ".", "query", "(", "\"SELECT main_chain_index FROM units \\n\\\n WHERE unit=?\"", ",", "[", "constants", ".", "GENESIS_UNIT", "]", ",", "function", "(", "rowGenesis", ")", "{", "if", "(", "rowGenesis", ".", "length", "===", "0", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "initByzantine", "(", ")", ";", "}", ",", "3000", ")", ";", "}", "else", "{", "startPhase", "(", "hp", ",", "0", ")", ";", "}", "}", ")", ";", "}", "else", "if", "(", "rows", ".", "length", "===", "1", ")", "{", "hp", "=", "rows", "[", "0", "]", ".", "main_chain_index", "+", "1", ";", "if", "(", "maxGossipHp", "===", "hp", ")", "{", "startPhase", "(", "hp", ",", "maxGossipPp", ")", ";", "}", "else", "{", "setTimeout", "(", "function", "(", ")", "{", "initByzantine", "(", ")", ";", "}", ",", "3000", ")", ";", "}", "}", "}", ")", ";", "}" ]
init function begin init byzantine, executes at startup
[ "init", "function", "begin", "init", "byzantine", "executes", "at", "startup" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/mc/byzantine.js#L57-L101
20,676
trustnote/trustnote-pow-common
mc/byzantine.js
getCoordinators
function getCoordinators(conn, hp, phase, cb){ hp = parseInt(hp); phase = parseInt(phase); var pIndex = Math.abs(hp-phase+999)%constants.TOTAL_COORDINATORS; if (assocByzantinePhase[hp] && assocByzantinePhase[hp].roundIndex && assocByzantinePhase[hp].witnesses){ return cb(null, assocByzantinePhase[hp].witnesses[pIndex], assocByzantinePhase[hp].roundIndex, assocByzantinePhase[hp].witnesses); } if(!validationUtils.isPositiveInteger(hp)) return cb("param hp is not a positive integer:" + hp); if(!validationUtils.isNonnegativeInteger(phase)) return cb("param phase is not a positive integer:" + phase); var conn = conn || db; round.getRoundIndexByNewMci(conn, hp, function(roundIndex){ if(roundIndex === -1) return cb("have not get the last mci yet "); round.getWitnessesByRoundIndex(conn, roundIndex, function(witnesses){ if(!assocByzantinePhase[hp] || typeof assocByzantinePhase[hp] === 'undefined' || Object.keys(assocByzantinePhase[hp]).length === 0){ assocByzantinePhase[hp] = {}; assocByzantinePhase[hp].roundIndex = roundIndex; assocByzantinePhase[hp].witnesses = witnesses; assocByzantinePhase[hp].phase = {}; assocByzantinePhase[hp].decision = {}; } cb(null, witnesses[pIndex], roundIndex, witnesses); }); }); }
javascript
function getCoordinators(conn, hp, phase, cb){ hp = parseInt(hp); phase = parseInt(phase); var pIndex = Math.abs(hp-phase+999)%constants.TOTAL_COORDINATORS; if (assocByzantinePhase[hp] && assocByzantinePhase[hp].roundIndex && assocByzantinePhase[hp].witnesses){ return cb(null, assocByzantinePhase[hp].witnesses[pIndex], assocByzantinePhase[hp].roundIndex, assocByzantinePhase[hp].witnesses); } if(!validationUtils.isPositiveInteger(hp)) return cb("param hp is not a positive integer:" + hp); if(!validationUtils.isNonnegativeInteger(phase)) return cb("param phase is not a positive integer:" + phase); var conn = conn || db; round.getRoundIndexByNewMci(conn, hp, function(roundIndex){ if(roundIndex === -1) return cb("have not get the last mci yet "); round.getWitnessesByRoundIndex(conn, roundIndex, function(witnesses){ if(!assocByzantinePhase[hp] || typeof assocByzantinePhase[hp] === 'undefined' || Object.keys(assocByzantinePhase[hp]).length === 0){ assocByzantinePhase[hp] = {}; assocByzantinePhase[hp].roundIndex = roundIndex; assocByzantinePhase[hp].witnesses = witnesses; assocByzantinePhase[hp].phase = {}; assocByzantinePhase[hp].decision = {}; } cb(null, witnesses[pIndex], roundIndex, witnesses); }); }); }
[ "function", "getCoordinators", "(", "conn", ",", "hp", ",", "phase", ",", "cb", ")", "{", "hp", "=", "parseInt", "(", "hp", ")", ";", "phase", "=", "parseInt", "(", "phase", ")", ";", "var", "pIndex", "=", "Math", ".", "abs", "(", "hp", "-", "phase", "+", "999", ")", "%", "constants", ".", "TOTAL_COORDINATORS", ";", "if", "(", "assocByzantinePhase", "[", "hp", "]", "&&", "assocByzantinePhase", "[", "hp", "]", ".", "roundIndex", "&&", "assocByzantinePhase", "[", "hp", "]", ".", "witnesses", ")", "{", "return", "cb", "(", "null", ",", "assocByzantinePhase", "[", "hp", "]", ".", "witnesses", "[", "pIndex", "]", ",", "assocByzantinePhase", "[", "hp", "]", ".", "roundIndex", ",", "assocByzantinePhase", "[", "hp", "]", ".", "witnesses", ")", ";", "}", "if", "(", "!", "validationUtils", ".", "isPositiveInteger", "(", "hp", ")", ")", "return", "cb", "(", "\"param hp is not a positive integer:\"", "+", "hp", ")", ";", "if", "(", "!", "validationUtils", ".", "isNonnegativeInteger", "(", "phase", ")", ")", "return", "cb", "(", "\"param phase is not a positive integer:\"", "+", "phase", ")", ";", "var", "conn", "=", "conn", "||", "db", ";", "round", ".", "getRoundIndexByNewMci", "(", "conn", ",", "hp", ",", "function", "(", "roundIndex", ")", "{", "if", "(", "roundIndex", "===", "-", "1", ")", "return", "cb", "(", "\"have not get the last mci yet \"", ")", ";", "round", ".", "getWitnessesByRoundIndex", "(", "conn", ",", "roundIndex", ",", "function", "(", "witnesses", ")", "{", "if", "(", "!", "assocByzantinePhase", "[", "hp", "]", "||", "typeof", "assocByzantinePhase", "[", "hp", "]", "===", "'undefined'", "||", "Object", ".", "keys", "(", "assocByzantinePhase", "[", "hp", "]", ")", ".", "length", "===", "0", ")", "{", "assocByzantinePhase", "[", "hp", "]", "=", "{", "}", ";", "assocByzantinePhase", "[", "hp", "]", ".", "roundIndex", "=", "roundIndex", ";", "assocByzantinePhase", "[", "hp", "]", ".", "witnesses", "=", "witnesses", ";", "assocByzantinePhase", "[", "hp", "]", ".", "phase", "=", "{", "}", ";", "assocByzantinePhase", "[", "hp", "]", ".", "decision", "=", "{", "}", ";", "}", "cb", "(", "null", ",", "witnesses", "[", "pIndex", "]", ",", "roundIndex", ",", "witnesses", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
public function begin Get proposer witnesses and round index by hp and phase @param {obj} conn if conn is null, use db query, otherwise use conn. @param {Integer} hp @param {Integer} phase @param {function} callback( err, proposer, roundIndex, witnesses ) callback function
[ "public", "function", "begin", "Get", "proposer", "witnesses", "and", "round", "index", "by", "hp", "and", "phase" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/mc/byzantine.js#L133-L159
20,677
trustnote/trustnote-pow-common
mc/byzantine.js
gossipLastMessageAtFixedInterval
function gossipLastMessageAtFixedInterval(){ if(p_phase_timeout >0 && Date.now() - p_phase_timeout > constants.BYZANTINE_PHASE_TIMEOUT){ if(bByzantineUnderWay && last_prevote_gossip && typeof last_prevote_gossip !== 'undefined' && Object.keys(last_prevote_gossip).length > 0){ if(last_prevote_gossip.type === constants.BYZANTINE_PREVOTE && h_p === last_prevote_gossip.h){ // console.log("byllllogg gossipLastMessageAtFixedInterval broadcastPrevote" + JSON.stringify(last_prevote_gossip)); broadcastPrevote(last_prevote_gossip.h, last_prevote_gossip.p, last_prevote_gossip.idv); } } if(bByzantineUnderWay && last_precommit_gossip && typeof last_precommit_gossip !== 'undefined' && Object.keys(last_precommit_gossip).length > 0){ if(last_precommit_gossip.type === constants.BYZANTINE_PRECOMMIT && h_p === last_precommit_gossip.h){ if(last_precommit_gossip.idv !== null && assocByzantinePhase[last_precommit_gossip.h].phase[last_precommit_gossip.p].proposal && typeof assocByzantinePhase[last_precommit_gossip.h].phase[last_precommit_gossip.p].proposal !== 'undefined'){ var lastProposal = assocByzantinePhase[last_precommit_gossip.h].phase[last_precommit_gossip.p].proposal; broadcastProposal(last_precommit_gossip.h, last_precommit_gossip.p, lastProposal, lastProposal.vp); } // console.log("byllllogg gossipLastMessageAtFixedInterval broadcastPrecommit" + JSON.stringify(last_precommit_gossip)); broadcastPrecommit(last_precommit_gossip.h, last_precommit_gossip.p, last_precommit_gossip.sig, last_precommit_gossip.idv); } } } }
javascript
function gossipLastMessageAtFixedInterval(){ if(p_phase_timeout >0 && Date.now() - p_phase_timeout > constants.BYZANTINE_PHASE_TIMEOUT){ if(bByzantineUnderWay && last_prevote_gossip && typeof last_prevote_gossip !== 'undefined' && Object.keys(last_prevote_gossip).length > 0){ if(last_prevote_gossip.type === constants.BYZANTINE_PREVOTE && h_p === last_prevote_gossip.h){ // console.log("byllllogg gossipLastMessageAtFixedInterval broadcastPrevote" + JSON.stringify(last_prevote_gossip)); broadcastPrevote(last_prevote_gossip.h, last_prevote_gossip.p, last_prevote_gossip.idv); } } if(bByzantineUnderWay && last_precommit_gossip && typeof last_precommit_gossip !== 'undefined' && Object.keys(last_precommit_gossip).length > 0){ if(last_precommit_gossip.type === constants.BYZANTINE_PRECOMMIT && h_p === last_precommit_gossip.h){ if(last_precommit_gossip.idv !== null && assocByzantinePhase[last_precommit_gossip.h].phase[last_precommit_gossip.p].proposal && typeof assocByzantinePhase[last_precommit_gossip.h].phase[last_precommit_gossip.p].proposal !== 'undefined'){ var lastProposal = assocByzantinePhase[last_precommit_gossip.h].phase[last_precommit_gossip.p].proposal; broadcastProposal(last_precommit_gossip.h, last_precommit_gossip.p, lastProposal, lastProposal.vp); } // console.log("byllllogg gossipLastMessageAtFixedInterval broadcastPrecommit" + JSON.stringify(last_precommit_gossip)); broadcastPrecommit(last_precommit_gossip.h, last_precommit_gossip.p, last_precommit_gossip.sig, last_precommit_gossip.idv); } } } }
[ "function", "gossipLastMessageAtFixedInterval", "(", ")", "{", "if", "(", "p_phase_timeout", ">", "0", "&&", "Date", ".", "now", "(", ")", "-", "p_phase_timeout", ">", "constants", ".", "BYZANTINE_PHASE_TIMEOUT", ")", "{", "if", "(", "bByzantineUnderWay", "&&", "last_prevote_gossip", "&&", "typeof", "last_prevote_gossip", "!==", "'undefined'", "&&", "Object", ".", "keys", "(", "last_prevote_gossip", ")", ".", "length", ">", "0", ")", "{", "if", "(", "last_prevote_gossip", ".", "type", "===", "constants", ".", "BYZANTINE_PREVOTE", "&&", "h_p", "===", "last_prevote_gossip", ".", "h", ")", "{", "// console.log(\"byllllogg gossipLastMessageAtFixedInterval broadcastPrevote\" + JSON.stringify(last_prevote_gossip));", "broadcastPrevote", "(", "last_prevote_gossip", ".", "h", ",", "last_prevote_gossip", ".", "p", ",", "last_prevote_gossip", ".", "idv", ")", ";", "}", "}", "if", "(", "bByzantineUnderWay", "&&", "last_precommit_gossip", "&&", "typeof", "last_precommit_gossip", "!==", "'undefined'", "&&", "Object", ".", "keys", "(", "last_precommit_gossip", ")", ".", "length", ">", "0", ")", "{", "if", "(", "last_precommit_gossip", ".", "type", "===", "constants", ".", "BYZANTINE_PRECOMMIT", "&&", "h_p", "===", "last_precommit_gossip", ".", "h", ")", "{", "if", "(", "last_precommit_gossip", ".", "idv", "!==", "null", "&&", "assocByzantinePhase", "[", "last_precommit_gossip", ".", "h", "]", ".", "phase", "[", "last_precommit_gossip", ".", "p", "]", ".", "proposal", "&&", "typeof", "assocByzantinePhase", "[", "last_precommit_gossip", ".", "h", "]", ".", "phase", "[", "last_precommit_gossip", ".", "p", "]", ".", "proposal", "!==", "'undefined'", ")", "{", "var", "lastProposal", "=", "assocByzantinePhase", "[", "last_precommit_gossip", ".", "h", "]", ".", "phase", "[", "last_precommit_gossip", ".", "p", "]", ".", "proposal", ";", "broadcastProposal", "(", "last_precommit_gossip", ".", "h", ",", "last_precommit_gossip", ".", "p", ",", "lastProposal", ",", "lastProposal", ".", "vp", ")", ";", "}", "// console.log(\"byllllogg gossipLastMessageAtFixedInterval broadcastPrecommit\" + JSON.stringify(last_precommit_gossip));", "broadcastPrecommit", "(", "last_precommit_gossip", ".", "h", ",", "last_precommit_gossip", ".", "p", ",", "last_precommit_gossip", ".", "sig", ",", "last_precommit_gossip", ".", "idv", ")", ";", "}", "}", "}", "}" ]
private function end Send the last message at fixed intervals
[ "private", "function", "end", "Send", "the", "last", "message", "at", "fixed", "intervals" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/mc/byzantine.js#L1089-L1114
20,678
trustnote/trustnote-pow-common
mc/byzantine.js
shrinkByzantineCache
function shrinkByzantineCache(){ // shrink assocByzantinePhase var arrByzantinePhases = Object.keys(assocByzantinePhase); if (arrByzantinePhases.length < constants.MAX_BYZANTINE_IN_CACHE){ //console.log("ByzantinePhaseCacheLog:shrinkByzantineCache,will not delete, assocByzantinePhase.length:" + arrByzantinePhases.length); return console.log('byllllogg byzantine cache is small, will not shrink'); } var minIndexByzantinePhases = Math.min.apply(Math, arrByzantinePhases); for (var offset1 = minIndexByzantinePhases; offset1 < h_p - constants.MAX_BYZANTINE_IN_CACHE; offset1++){ //console.log("byllllogg ByzantinePhaseCacheLog:shrinkByzantineCache,delete hp:" + offset1); delete assocByzantinePhase[offset1]; } // minIndexByzantinePhases = Math.min.apply(Math, arrByzantinePhases); // for (var offset2 = minIndexByzantinePhases; offset2 <= h_p; offset2++){ // if(assocByzantinePhase[offset2] && // typeof assocByzantinePhase[offset2] !== 'undefined' && // Object.keys(assocByzantinePhase[offset2]).length > 0){ // var phaseCount = Object.keys(assocByzantinePhase[offset2].phase).length; // if(phaseCount > constants.MAX_BYZANTINE_PHASE_IN_CACHE){ // for (var offset3 = 0; offset3 < phaseCount - constants.MAX_BYZANTINE_PHASE_IN_CACHE; offset3++){ // console.log("byllllogg ByzantinePhaseCacheLog:shrinkByzantineCache,delete hp phase:" + offset3); // delete assocByzantinePhase[offset2].phase[offset3]; // } // } // } // } }
javascript
function shrinkByzantineCache(){ // shrink assocByzantinePhase var arrByzantinePhases = Object.keys(assocByzantinePhase); if (arrByzantinePhases.length < constants.MAX_BYZANTINE_IN_CACHE){ //console.log("ByzantinePhaseCacheLog:shrinkByzantineCache,will not delete, assocByzantinePhase.length:" + arrByzantinePhases.length); return console.log('byllllogg byzantine cache is small, will not shrink'); } var minIndexByzantinePhases = Math.min.apply(Math, arrByzantinePhases); for (var offset1 = minIndexByzantinePhases; offset1 < h_p - constants.MAX_BYZANTINE_IN_CACHE; offset1++){ //console.log("byllllogg ByzantinePhaseCacheLog:shrinkByzantineCache,delete hp:" + offset1); delete assocByzantinePhase[offset1]; } // minIndexByzantinePhases = Math.min.apply(Math, arrByzantinePhases); // for (var offset2 = minIndexByzantinePhases; offset2 <= h_p; offset2++){ // if(assocByzantinePhase[offset2] && // typeof assocByzantinePhase[offset2] !== 'undefined' && // Object.keys(assocByzantinePhase[offset2]).length > 0){ // var phaseCount = Object.keys(assocByzantinePhase[offset2].phase).length; // if(phaseCount > constants.MAX_BYZANTINE_PHASE_IN_CACHE){ // for (var offset3 = 0; offset3 < phaseCount - constants.MAX_BYZANTINE_PHASE_IN_CACHE; offset3++){ // console.log("byllllogg ByzantinePhaseCacheLog:shrinkByzantineCache,delete hp phase:" + offset3); // delete assocByzantinePhase[offset2].phase[offset3]; // } // } // } // } }
[ "function", "shrinkByzantineCache", "(", ")", "{", "// shrink assocByzantinePhase", "var", "arrByzantinePhases", "=", "Object", ".", "keys", "(", "assocByzantinePhase", ")", ";", "if", "(", "arrByzantinePhases", ".", "length", "<", "constants", ".", "MAX_BYZANTINE_IN_CACHE", ")", "{", "//console.log(\"ByzantinePhaseCacheLog:shrinkByzantineCache,will not delete, assocByzantinePhase.length:\" + arrByzantinePhases.length);", "return", "console", ".", "log", "(", "'byllllogg byzantine cache is small, will not shrink'", ")", ";", "}", "var", "minIndexByzantinePhases", "=", "Math", ".", "min", ".", "apply", "(", "Math", ",", "arrByzantinePhases", ")", ";", "for", "(", "var", "offset1", "=", "minIndexByzantinePhases", ";", "offset1", "<", "h_p", "-", "constants", ".", "MAX_BYZANTINE_IN_CACHE", ";", "offset1", "++", ")", "{", "//console.log(\"byllllogg ByzantinePhaseCacheLog:shrinkByzantineCache,delete hp:\" + offset1);", "delete", "assocByzantinePhase", "[", "offset1", "]", ";", "}", "// minIndexByzantinePhases = Math.min.apply(Math, arrByzantinePhases);", "// for (var offset2 = minIndexByzantinePhases; offset2 <= h_p; offset2++){", "// if(assocByzantinePhase[offset2] &&", "// typeof assocByzantinePhase[offset2] !== 'undefined' &&", "// Object.keys(assocByzantinePhase[offset2]).length > 0){", "// var phaseCount = Object.keys(assocByzantinePhase[offset2].phase).length;", "// if(phaseCount > constants.MAX_BYZANTINE_PHASE_IN_CACHE){", "// for (var offset3 = 0; offset3 < phaseCount - constants.MAX_BYZANTINE_PHASE_IN_CACHE; offset3++){", "// console.log(\"byllllogg ByzantinePhaseCacheLog:shrinkByzantineCache,delete hp phase:\" + offset3);", "// delete assocByzantinePhase[offset2].phase[offset3];", "// }", "// }", "// }", "// }", "}" ]
Send the last message end cache begin
[ "Send", "the", "last", "message", "end", "cache", "begin" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/mc/byzantine.js#L1130-L1156
20,679
trustnote/trustnote-pow-common
wallet/light.js
addSharedAddressesOfWallet
function addSharedAddressesOfWallet(arrAddressList, handleAddedSharedAddresses){ if (!arrAddressList || arrAddressList.length === 0 ) return handleAddedSharedAddresses([]); var strAddressList = arrAddressList.map(db.escape).join(', '); db.query("SELECT DISTINCT shared_address FROM shared_address_signing_paths WHERE address IN("+strAddressList+")", function(rows){ if (rows.length === 0) return handleAddedSharedAddresses(arrAddressList); var arrSharedAddresses = rows.map(function(row){ return row.shared_address; }); var arrNewMemberAddresses = _.difference(arrSharedAddresses, arrAddressList); if (arrNewMemberAddresses.length === 0) return handleAddedSharedAddresses(arrAddressList); addSharedAddressesOfWallet(arrAddressList.concat(arrNewMemberAddresses), handleAddedSharedAddresses); }); }
javascript
function addSharedAddressesOfWallet(arrAddressList, handleAddedSharedAddresses){ if (!arrAddressList || arrAddressList.length === 0 ) return handleAddedSharedAddresses([]); var strAddressList = arrAddressList.map(db.escape).join(', '); db.query("SELECT DISTINCT shared_address FROM shared_address_signing_paths WHERE address IN("+strAddressList+")", function(rows){ if (rows.length === 0) return handleAddedSharedAddresses(arrAddressList); var arrSharedAddresses = rows.map(function(row){ return row.shared_address; }); var arrNewMemberAddresses = _.difference(arrSharedAddresses, arrAddressList); if (arrNewMemberAddresses.length === 0) return handleAddedSharedAddresses(arrAddressList); addSharedAddressesOfWallet(arrAddressList.concat(arrNewMemberAddresses), handleAddedSharedAddresses); }); }
[ "function", "addSharedAddressesOfWallet", "(", "arrAddressList", ",", "handleAddedSharedAddresses", ")", "{", "if", "(", "!", "arrAddressList", "||", "arrAddressList", ".", "length", "===", "0", ")", "return", "handleAddedSharedAddresses", "(", "[", "]", ")", ";", "var", "strAddressList", "=", "arrAddressList", ".", "map", "(", "db", ".", "escape", ")", ".", "join", "(", "', '", ")", ";", "db", ".", "query", "(", "\"SELECT DISTINCT shared_address FROM shared_address_signing_paths WHERE address IN(\"", "+", "strAddressList", "+", "\")\"", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "return", "handleAddedSharedAddresses", "(", "arrAddressList", ")", ";", "var", "arrSharedAddresses", "=", "rows", ".", "map", "(", "function", "(", "row", ")", "{", "return", "row", ".", "shared_address", ";", "}", ")", ";", "var", "arrNewMemberAddresses", "=", "_", ".", "difference", "(", "arrSharedAddresses", ",", "arrAddressList", ")", ";", "if", "(", "arrNewMemberAddresses", ".", "length", "===", "0", ")", "return", "handleAddedSharedAddresses", "(", "arrAddressList", ")", ";", "addSharedAddressesOfWallet", "(", "arrAddressList", ".", "concat", "(", "arrNewMemberAddresses", ")", ",", "handleAddedSharedAddresses", ")", ";", "}", ")", ";", "}" ]
Victor ShareAddress Add
[ "Victor", "ShareAddress", "Add" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/wallet/light.js#L149-L162
20,680
trustnote/trustnote-pow-common
wallet/light.js
buildPath
function buildPath(objLaterJoint, objEarlierJoint, arrChain, onDone){ function addJoint(unit, onAdded){ storage.readJoint(db, unit, { ifNotFound: function(){ throw Error("unit not found?"); }, ifFound: function(objJoint){ arrChain.push(objJoint); onAdded(objJoint); } }); } function goUp(objChildJoint){ db.query( "SELECT parent.unit, parent.main_chain_index FROM units AS child JOIN units AS parent ON child.best_parent_unit=parent.unit \n\ WHERE child.unit=?", [objChildJoint.unit.unit], function(rows){ if (rows.length !== 1) throw Error("goUp not 1 parent"); if (rows[0].main_chain_index < objEarlierJoint.unit.main_chain_index) // jumped over the target return buildPathToEarlierUnit(objChildJoint); addJoint(rows[0].unit, function(objJoint){ (objJoint.unit.main_chain_index === objEarlierJoint.unit.main_chain_index) ? buildPathToEarlierUnit(objJoint) : goUp(objJoint); }); } ); } function buildPathToEarlierUnit(objJoint){ db.query( "SELECT unit FROM parenthoods JOIN units ON parent_unit=unit \n\ WHERE child_unit=? AND main_chain_index=?", [objJoint.unit.unit, objJoint.unit.main_chain_index], function(rows){ if (rows.length === 0) throw Error("no parents with same mci?"); var arrParentUnits = rows.map(function(row){ return row.unit }); if (arrParentUnits.indexOf(objEarlierJoint.unit.unit) >= 0) return onDone(); if (arrParentUnits.length === 1) return addJoint(arrParentUnits[0], buildPathToEarlierUnit); // find any parent that includes earlier unit async.eachSeries( arrParentUnits, function(unit, cb){ graph.determineIfIncluded(db, objEarlierJoint.unit.unit, [unit], function(bIncluded){ if (!bIncluded) return cb(); // try next cb(unit); // abort the eachSeries }); }, function(unit){ if (!unit) throw Error("none of the parents includes earlier unit"); addJoint(unit, buildPathToEarlierUnit); } ); } ); } if (objLaterJoint.unit.unit === objEarlierJoint.unit.unit) return onDone(); (objLaterJoint.unit.main_chain_index === objEarlierJoint.unit.main_chain_index) ? buildPathToEarlierUnit(objLaterJoint) : goUp(objLaterJoint); }
javascript
function buildPath(objLaterJoint, objEarlierJoint, arrChain, onDone){ function addJoint(unit, onAdded){ storage.readJoint(db, unit, { ifNotFound: function(){ throw Error("unit not found?"); }, ifFound: function(objJoint){ arrChain.push(objJoint); onAdded(objJoint); } }); } function goUp(objChildJoint){ db.query( "SELECT parent.unit, parent.main_chain_index FROM units AS child JOIN units AS parent ON child.best_parent_unit=parent.unit \n\ WHERE child.unit=?", [objChildJoint.unit.unit], function(rows){ if (rows.length !== 1) throw Error("goUp not 1 parent"); if (rows[0].main_chain_index < objEarlierJoint.unit.main_chain_index) // jumped over the target return buildPathToEarlierUnit(objChildJoint); addJoint(rows[0].unit, function(objJoint){ (objJoint.unit.main_chain_index === objEarlierJoint.unit.main_chain_index) ? buildPathToEarlierUnit(objJoint) : goUp(objJoint); }); } ); } function buildPathToEarlierUnit(objJoint){ db.query( "SELECT unit FROM parenthoods JOIN units ON parent_unit=unit \n\ WHERE child_unit=? AND main_chain_index=?", [objJoint.unit.unit, objJoint.unit.main_chain_index], function(rows){ if (rows.length === 0) throw Error("no parents with same mci?"); var arrParentUnits = rows.map(function(row){ return row.unit }); if (arrParentUnits.indexOf(objEarlierJoint.unit.unit) >= 0) return onDone(); if (arrParentUnits.length === 1) return addJoint(arrParentUnits[0], buildPathToEarlierUnit); // find any parent that includes earlier unit async.eachSeries( arrParentUnits, function(unit, cb){ graph.determineIfIncluded(db, objEarlierJoint.unit.unit, [unit], function(bIncluded){ if (!bIncluded) return cb(); // try next cb(unit); // abort the eachSeries }); }, function(unit){ if (!unit) throw Error("none of the parents includes earlier unit"); addJoint(unit, buildPathToEarlierUnit); } ); } ); } if (objLaterJoint.unit.unit === objEarlierJoint.unit.unit) return onDone(); (objLaterJoint.unit.main_chain_index === objEarlierJoint.unit.main_chain_index) ? buildPathToEarlierUnit(objLaterJoint) : goUp(objLaterJoint); }
[ "function", "buildPath", "(", "objLaterJoint", ",", "objEarlierJoint", ",", "arrChain", ",", "onDone", ")", "{", "function", "addJoint", "(", "unit", ",", "onAdded", ")", "{", "storage", ".", "readJoint", "(", "db", ",", "unit", ",", "{", "ifNotFound", ":", "function", "(", ")", "{", "throw", "Error", "(", "\"unit not found?\"", ")", ";", "}", ",", "ifFound", ":", "function", "(", "objJoint", ")", "{", "arrChain", ".", "push", "(", "objJoint", ")", ";", "onAdded", "(", "objJoint", ")", ";", "}", "}", ")", ";", "}", "function", "goUp", "(", "objChildJoint", ")", "{", "db", ".", "query", "(", "\"SELECT parent.unit, parent.main_chain_index FROM units AS child JOIN units AS parent ON child.best_parent_unit=parent.unit \\n\\\n\t\t\tWHERE child.unit=?\"", ",", "[", "objChildJoint", ".", "unit", ".", "unit", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "!==", "1", ")", "throw", "Error", "(", "\"goUp not 1 parent\"", ")", ";", "if", "(", "rows", "[", "0", "]", ".", "main_chain_index", "<", "objEarlierJoint", ".", "unit", ".", "main_chain_index", ")", "// jumped over the target", "return", "buildPathToEarlierUnit", "(", "objChildJoint", ")", ";", "addJoint", "(", "rows", "[", "0", "]", ".", "unit", ",", "function", "(", "objJoint", ")", "{", "(", "objJoint", ".", "unit", ".", "main_chain_index", "===", "objEarlierJoint", ".", "unit", ".", "main_chain_index", ")", "?", "buildPathToEarlierUnit", "(", "objJoint", ")", ":", "goUp", "(", "objJoint", ")", ";", "}", ")", ";", "}", ")", ";", "}", "function", "buildPathToEarlierUnit", "(", "objJoint", ")", "{", "db", ".", "query", "(", "\"SELECT unit FROM parenthoods JOIN units ON parent_unit=unit \\n\\\n\t\t\tWHERE child_unit=? AND main_chain_index=?\"", ",", "[", "objJoint", ".", "unit", ".", "unit", ",", "objJoint", ".", "unit", ".", "main_chain_index", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "throw", "Error", "(", "\"no parents with same mci?\"", ")", ";", "var", "arrParentUnits", "=", "rows", ".", "map", "(", "function", "(", "row", ")", "{", "return", "row", ".", "unit", "}", ")", ";", "if", "(", "arrParentUnits", ".", "indexOf", "(", "objEarlierJoint", ".", "unit", ".", "unit", ")", ">=", "0", ")", "return", "onDone", "(", ")", ";", "if", "(", "arrParentUnits", ".", "length", "===", "1", ")", "return", "addJoint", "(", "arrParentUnits", "[", "0", "]", ",", "buildPathToEarlierUnit", ")", ";", "// find any parent that includes earlier unit", "async", ".", "eachSeries", "(", "arrParentUnits", ",", "function", "(", "unit", ",", "cb", ")", "{", "graph", ".", "determineIfIncluded", "(", "db", ",", "objEarlierJoint", ".", "unit", ".", "unit", ",", "[", "unit", "]", ",", "function", "(", "bIncluded", ")", "{", "if", "(", "!", "bIncluded", ")", "return", "cb", "(", ")", ";", "// try next", "cb", "(", "unit", ")", ";", "// abort the eachSeries", "}", ")", ";", "}", ",", "function", "(", "unit", ")", "{", "if", "(", "!", "unit", ")", "throw", "Error", "(", "\"none of the parents includes earlier unit\"", ")", ";", "addJoint", "(", "unit", ",", "buildPathToEarlierUnit", ")", ";", "}", ")", ";", "}", ")", ";", "}", "if", "(", "objLaterJoint", ".", "unit", ".", "unit", "===", "objEarlierJoint", ".", "unit", ".", "unit", ")", "return", "onDone", "(", ")", ";", "(", "objLaterJoint", ".", "unit", ".", "main_chain_index", "===", "objEarlierJoint", ".", "unit", ".", "main_chain_index", ")", "?", "buildPathToEarlierUnit", "(", "objLaterJoint", ")", ":", "goUp", "(", "objLaterJoint", ")", ";", "}" ]
build parent path from later unit to earlier unit and add all joints along the path into arrChain arrChain will include later unit but not include earlier unit assuming arrChain already includes later unit
[ "build", "parent", "path", "from", "later", "unit", "to", "earlier", "unit", "and", "add", "all", "joints", "along", "the", "path", "into", "arrChain", "arrChain", "will", "include", "later", "unit", "but", "not", "include", "earlier", "unit", "assuming", "arrChain", "already", "includes", "later", "unit" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/wallet/light.js#L610-L677
20,681
trustnote/trustnote-pow-common
wallet/device.js
reliablySendPreparedMessageToHub
function reliablySendPreparedMessageToHub(ws, recipient_device_pubkey, json, callbacks, conn){ var recipient_device_address = objectHash.getDeviceAddress(recipient_device_pubkey); console.log('will encrypt and send to '+recipient_device_address+': '+JSON.stringify(json)); // encrypt to recipient's permanent pubkey before storing the message into outbox var objEncryptedPackage = createEncryptedPackage(json, recipient_device_pubkey); // if the first attempt fails, this will be the inner message var objDeviceMessage = { encrypted_package: objEncryptedPackage }; var message_hash = objectHash.getBase64Hash(objDeviceMessage); conn = conn || db; conn.query( "INSERT INTO outbox (message_hash, `to`, message) VALUES (?,?,?)", [message_hash, recipient_device_address, JSON.stringify(objDeviceMessage)], function(){ if (callbacks && callbacks.onSaved) callbacks.onSaved(); sendPreparedMessageToHub(ws, recipient_device_pubkey, message_hash, json, callbacks); } ); }
javascript
function reliablySendPreparedMessageToHub(ws, recipient_device_pubkey, json, callbacks, conn){ var recipient_device_address = objectHash.getDeviceAddress(recipient_device_pubkey); console.log('will encrypt and send to '+recipient_device_address+': '+JSON.stringify(json)); // encrypt to recipient's permanent pubkey before storing the message into outbox var objEncryptedPackage = createEncryptedPackage(json, recipient_device_pubkey); // if the first attempt fails, this will be the inner message var objDeviceMessage = { encrypted_package: objEncryptedPackage }; var message_hash = objectHash.getBase64Hash(objDeviceMessage); conn = conn || db; conn.query( "INSERT INTO outbox (message_hash, `to`, message) VALUES (?,?,?)", [message_hash, recipient_device_address, JSON.stringify(objDeviceMessage)], function(){ if (callbacks && callbacks.onSaved) callbacks.onSaved(); sendPreparedMessageToHub(ws, recipient_device_pubkey, message_hash, json, callbacks); } ); }
[ "function", "reliablySendPreparedMessageToHub", "(", "ws", ",", "recipient_device_pubkey", ",", "json", ",", "callbacks", ",", "conn", ")", "{", "var", "recipient_device_address", "=", "objectHash", ".", "getDeviceAddress", "(", "recipient_device_pubkey", ")", ";", "console", ".", "log", "(", "'will encrypt and send to '", "+", "recipient_device_address", "+", "': '", "+", "JSON", ".", "stringify", "(", "json", ")", ")", ";", "// encrypt to recipient's permanent pubkey before storing the message into outbox", "var", "objEncryptedPackage", "=", "createEncryptedPackage", "(", "json", ",", "recipient_device_pubkey", ")", ";", "// if the first attempt fails, this will be the inner message", "var", "objDeviceMessage", "=", "{", "encrypted_package", ":", "objEncryptedPackage", "}", ";", "var", "message_hash", "=", "objectHash", ".", "getBase64Hash", "(", "objDeviceMessage", ")", ";", "conn", "=", "conn", "||", "db", ";", "conn", ".", "query", "(", "\"INSERT INTO outbox (message_hash, `to`, message) VALUES (?,?,?)\"", ",", "[", "message_hash", ",", "recipient_device_address", ",", "JSON", ".", "stringify", "(", "objDeviceMessage", ")", "]", ",", "function", "(", ")", "{", "if", "(", "callbacks", "&&", "callbacks", ".", "onSaved", ")", "callbacks", ".", "onSaved", "(", ")", ";", "sendPreparedMessageToHub", "(", "ws", ",", "recipient_device_pubkey", ",", "message_hash", ",", "json", ",", "callbacks", ")", ";", "}", ")", ";", "}" ]
reliable delivery first param is either WebSocket or hostname of the hub
[ "reliable", "delivery", "first", "param", "is", "either", "WebSocket", "or", "hostname", "of", "the", "hub" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/wallet/device.js#L433-L453
20,682
trustnote/trustnote-pow-common
wallet/device.js
sendPreparedMessageToHub
function sendPreparedMessageToHub(ws, recipient_device_pubkey, message_hash, json, callbacks){ if (!callbacks) callbacks = {ifOk: function(){}, ifError: function(){}}; if (typeof ws === "string"){ var hub_host = ws; network.findOutboundPeerOrConnect(conf.WS_PROTOCOL+hub_host, function onLocatedHubForSend(err, ws){ if (err) return callbacks.ifError(err); sendPreparedMessageToConnectedHub(ws, recipient_device_pubkey, message_hash, json, callbacks); }); } else sendPreparedMessageToConnectedHub(ws, recipient_device_pubkey, message_hash, json, callbacks); }
javascript
function sendPreparedMessageToHub(ws, recipient_device_pubkey, message_hash, json, callbacks){ if (!callbacks) callbacks = {ifOk: function(){}, ifError: function(){}}; if (typeof ws === "string"){ var hub_host = ws; network.findOutboundPeerOrConnect(conf.WS_PROTOCOL+hub_host, function onLocatedHubForSend(err, ws){ if (err) return callbacks.ifError(err); sendPreparedMessageToConnectedHub(ws, recipient_device_pubkey, message_hash, json, callbacks); }); } else sendPreparedMessageToConnectedHub(ws, recipient_device_pubkey, message_hash, json, callbacks); }
[ "function", "sendPreparedMessageToHub", "(", "ws", ",", "recipient_device_pubkey", ",", "message_hash", ",", "json", ",", "callbacks", ")", "{", "if", "(", "!", "callbacks", ")", "callbacks", "=", "{", "ifOk", ":", "function", "(", ")", "{", "}", ",", "ifError", ":", "function", "(", ")", "{", "}", "}", ";", "if", "(", "typeof", "ws", "===", "\"string\"", ")", "{", "var", "hub_host", "=", "ws", ";", "network", ".", "findOutboundPeerOrConnect", "(", "conf", ".", "WS_PROTOCOL", "+", "hub_host", ",", "function", "onLocatedHubForSend", "(", "err", ",", "ws", ")", "{", "if", "(", "err", ")", "return", "callbacks", ".", "ifError", "(", "err", ")", ";", "sendPreparedMessageToConnectedHub", "(", "ws", ",", "recipient_device_pubkey", ",", "message_hash", ",", "json", ",", "callbacks", ")", ";", "}", ")", ";", "}", "else", "sendPreparedMessageToConnectedHub", "(", "ws", ",", "recipient_device_pubkey", ",", "message_hash", ",", "json", ",", "callbacks", ")", ";", "}" ]
first param is either WebSocket or hostname of the hub
[ "first", "param", "is", "either", "WebSocket", "or", "hostname", "of", "the", "hub" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/wallet/device.js#L456-L469
20,683
trustnote/trustnote-pow-common
pow/round.js
getMinWlByRoundIndex
function getMinWlByRoundIndex(conn, roundIndex, callback){ conn.query( "SELECT min_wl FROM round where round_index=?", [roundIndex], function(rows){ if (rows.length !== 1) throw Error("Can not find the right round index"); callback(rows[0].min_wl); } ); }
javascript
function getMinWlByRoundIndex(conn, roundIndex, callback){ conn.query( "SELECT min_wl FROM round where round_index=?", [roundIndex], function(rows){ if (rows.length !== 1) throw Error("Can not find the right round index"); callback(rows[0].min_wl); } ); }
[ "function", "getMinWlByRoundIndex", "(", "conn", ",", "roundIndex", ",", "callback", ")", "{", "conn", ".", "query", "(", "\"SELECT min_wl FROM round where round_index=?\"", ",", "[", "roundIndex", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "!==", "1", ")", "throw", "Error", "(", "\"Can not find the right round index\"", ")", ";", "callback", "(", "rows", "[", "0", "]", ".", "min_wl", ")", ";", "}", ")", ";", "}" ]
the MinWl maybe null
[ "the", "MinWl", "maybe", "null" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/pow/round.js#L283-L293
20,684
trustnote/trustnote-pow-common
pow/round.js
getCoinbaseByRoundIndex
function getCoinbaseByRoundIndex(roundIndex){ if(roundIndex < 1 || roundIndex > constants.ROUND_TOTAL_ALL) return 0; return constants.ROUND_COINBASE[Math.ceil(roundIndex/constants.ROUND_TOTAL_YEAR)-1]; }
javascript
function getCoinbaseByRoundIndex(roundIndex){ if(roundIndex < 1 || roundIndex > constants.ROUND_TOTAL_ALL) return 0; return constants.ROUND_COINBASE[Math.ceil(roundIndex/constants.ROUND_TOTAL_YEAR)-1]; }
[ "function", "getCoinbaseByRoundIndex", "(", "roundIndex", ")", "{", "if", "(", "roundIndex", "<", "1", "||", "roundIndex", ">", "constants", ".", "ROUND_TOTAL_ALL", ")", "return", "0", ";", "return", "constants", ".", "ROUND_COINBASE", "[", "Math", ".", "ceil", "(", "roundIndex", "/", "constants", ".", "ROUND_TOTAL_YEAR", ")", "-", "1", "]", ";", "}" ]
coinbase begin old function
[ "coinbase", "begin", "old", "function" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/pow/round.js#L388-L392
20,685
trustnote/trustnote-pow-common
pow/round.js
queryFirstTrustMEBallOnMainChainByRoundIndex
function queryFirstTrustMEBallOnMainChainByRoundIndex( oConn, nRoundIndex, pfnCallback ) { if ( ! oConn ) { return pfnCallback( `call queryFirstTrustMEBallOnMainChainByRoundIndex with invalid oConn` ); } if ( 'number' !== typeof nRoundIndex ) { return pfnCallback( `call queryFirstTrustMEBallOnMainChainByRoundIndex with invalid nRoundIndex, must be a number` ); } if ( nRoundIndex <= 0 ) { return pfnCallback( `call queryFirstTrustMEBallOnMainChainByRoundIndex with invalid nRoundIndex, must be greater than zero.` ); } // ... oConn.query ( "SELECT ball \ FROM balls JOIN units USING(unit) \ WHERE units.round_index = ? AND units.is_stable=1 AND units.is_on_main_chain=1 AND units.sequence='good' AND units.pow_type=? \ ORDER BY units.main_chain_index ASC \ LIMIT 1", [ nRoundIndex, constants.POW_TYPE_TRUSTME ], function( arrRows ) { if ( 1 !== arrRows.length ) { return pfnCallback( `Can not find a suitable ball for calculation pow.` ); } // ... return pfnCallback( null, arrRows[ 0 ][ 'ball' ] ); } ); }
javascript
function queryFirstTrustMEBallOnMainChainByRoundIndex( oConn, nRoundIndex, pfnCallback ) { if ( ! oConn ) { return pfnCallback( `call queryFirstTrustMEBallOnMainChainByRoundIndex with invalid oConn` ); } if ( 'number' !== typeof nRoundIndex ) { return pfnCallback( `call queryFirstTrustMEBallOnMainChainByRoundIndex with invalid nRoundIndex, must be a number` ); } if ( nRoundIndex <= 0 ) { return pfnCallback( `call queryFirstTrustMEBallOnMainChainByRoundIndex with invalid nRoundIndex, must be greater than zero.` ); } // ... oConn.query ( "SELECT ball \ FROM balls JOIN units USING(unit) \ WHERE units.round_index = ? AND units.is_stable=1 AND units.is_on_main_chain=1 AND units.sequence='good' AND units.pow_type=? \ ORDER BY units.main_chain_index ASC \ LIMIT 1", [ nRoundIndex, constants.POW_TYPE_TRUSTME ], function( arrRows ) { if ( 1 !== arrRows.length ) { return pfnCallback( `Can not find a suitable ball for calculation pow.` ); } // ... return pfnCallback( null, arrRows[ 0 ][ 'ball' ] ); } ); }
[ "function", "queryFirstTrustMEBallOnMainChainByRoundIndex", "(", "oConn", ",", "nRoundIndex", ",", "pfnCallback", ")", "{", "if", "(", "!", "oConn", ")", "{", "return", "pfnCallback", "(", "`", "`", ")", ";", "}", "if", "(", "'number'", "!==", "typeof", "nRoundIndex", ")", "{", "return", "pfnCallback", "(", "`", "`", ")", ";", "}", "if", "(", "nRoundIndex", "<=", "0", ")", "{", "return", "pfnCallback", "(", "`", "`", ")", ";", "}", "//\t...", "oConn", ".", "query", "(", "\"SELECT ball \\\n\t\tFROM balls JOIN units USING(unit) \\\n\t\tWHERE units.round_index = ? AND units.is_stable=1 AND units.is_on_main_chain=1 AND units.sequence='good' AND units.pow_type=? \\\n\t\tORDER BY units.main_chain_index ASC \\\n\t\tLIMIT 1\"", ",", "[", "nRoundIndex", ",", "constants", ".", "POW_TYPE_TRUSTME", "]", ",", "function", "(", "arrRows", ")", "{", "if", "(", "1", "!==", "arrRows", ".", "length", ")", "{", "return", "pfnCallback", "(", "`", "`", ")", ";", "}", "//\t...", "return", "pfnCallback", "(", "null", ",", "arrRows", "[", "0", "]", "[", "'ball'", "]", ")", ";", "}", ")", ";", "}" ]
coinbase end obtain ball address of the first TrustME unit @param {handle} oConn @param {function} oConn.query @param {number} nRoundIndex @param {function} pfnCallback( err, arrCoinBaseList )
[ "coinbase", "end", "obtain", "ball", "address", "of", "the", "first", "TrustME", "unit" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/pow/round.js#L721-L759
20,686
trustnote/trustnote-pow-common
pow/round.js
getLastCoinbaseUnitRoundIndex
function getLastCoinbaseUnitRoundIndex(conn, address, cb){ if (!conn) return getLastCoinbaseUnitRoundIndex(db, address, cb); if(!validationUtils.isNonemptyString(address)) return cb("param address is null or empty string"); if(!validationUtils.isValidAddress(address)) return cb("param address is not a valid address"); conn.query( "SELECT round_index FROM units JOIN unit_authors USING(unit) \n\ WHERE is_stable=1 AND sequence='good' AND pow_type=? \n\ AND address=? ORDER BY round_index DESC LIMIT 1", [constants.POW_TYPE_COIN_BASE, address], function(rows){ if(rows.length === 0) return cb(null, 0); cb(null, rows[0].round_index); } ); }
javascript
function getLastCoinbaseUnitRoundIndex(conn, address, cb){ if (!conn) return getLastCoinbaseUnitRoundIndex(db, address, cb); if(!validationUtils.isNonemptyString(address)) return cb("param address is null or empty string"); if(!validationUtils.isValidAddress(address)) return cb("param address is not a valid address"); conn.query( "SELECT round_index FROM units JOIN unit_authors USING(unit) \n\ WHERE is_stable=1 AND sequence='good' AND pow_type=? \n\ AND address=? ORDER BY round_index DESC LIMIT 1", [constants.POW_TYPE_COIN_BASE, address], function(rows){ if(rows.length === 0) return cb(null, 0); cb(null, rows[0].round_index); } ); }
[ "function", "getLastCoinbaseUnitRoundIndex", "(", "conn", ",", "address", ",", "cb", ")", "{", "if", "(", "!", "conn", ")", "return", "getLastCoinbaseUnitRoundIndex", "(", "db", ",", "address", ",", "cb", ")", ";", "if", "(", "!", "validationUtils", ".", "isNonemptyString", "(", "address", ")", ")", "return", "cb", "(", "\"param address is null or empty string\"", ")", ";", "if", "(", "!", "validationUtils", ".", "isValidAddress", "(", "address", ")", ")", "return", "cb", "(", "\"param address is not a valid address\"", ")", ";", "conn", ".", "query", "(", "\"SELECT round_index FROM units JOIN unit_authors USING(unit) \\n\\\n WHERE is_stable=1 AND sequence='good' AND pow_type=? \\n\\\n AND address=? ORDER BY round_index DESC LIMIT 1\"", ",", "[", "constants", ".", "POW_TYPE_COIN_BASE", ",", "address", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "return", "cb", "(", "null", ",", "0", ")", ";", "cb", "(", "null", ",", "rows", "[", "0", "]", ".", "round_index", ")", ";", "}", ")", ";", "}" ]
Get the round index of address's last coinbase unit. @param {obj} conn if conn is null, use db query, otherwise use conn. @param {string} address @param {function} cb( err, roundIndex ) callback function If there's error, err is the error message and roundIndex is null. If the address hasn't launch coinbase unit, roundIndex is 0. If there's no error, roundIndex is the result.
[ "Get", "the", "round", "index", "of", "address", "s", "last", "coinbase", "unit", "." ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/pow/round.js#L774-L792
20,687
trustnote/trustnote-pow-common
wallet/supernode.js
readKeys
function readKeys(onDone){ console.log('-----------------------'); fs.readFile(KEYS_FILENAME, 'utf8', function(err, data){ var rl = readline.createInterface({ input: process.stdin, output: process.stdout, //terminal: true }); if (err){ // first start console.log('failed to read keys, will gen'); var suggestedDeviceName = require('os').hostname() || 'Headless'; // rl.question("Please name this device ["+suggestedDeviceName+"]: ", function(deviceName){ var deviceName = suggestedDeviceName; var userConfFile = appDataDir + '/conf.json'; fs.writeFile(userConfFile, JSON.stringify({deviceName: deviceName, admin_email: "admin@example.com", from_email: "noreply@example.com"}, null, '\t'), 'utf8', function(err){ if (err) throw Error('failed to write conf.json: '+err); // rl.question( console.log('Device name saved to '+userConfFile+', you can edit it later if you like.\n\nPassphrase for your private keys: ') // function(passphrase){ // rl.close(); var passphrase = "" if (process.stdout.moveCursor) process.stdout.moveCursor(0, -1); if (process.stdout.clearLine) process.stdout.clearLine(); var deviceTempPrivKey = crypto.randomBytes(32); var devicePrevTempPrivKey = crypto.randomBytes(32); var mnemonic = new Mnemonic(); // generates new mnemonic while (!Mnemonic.isValid(mnemonic.toString())) mnemonic = new Mnemonic(); writeKeys(mnemonic.phrase, deviceTempPrivKey, devicePrevTempPrivKey, function(){ console.log('keys created'); xPrivKey = mnemonic.toHDPrivateKey(passphrase); createWallet(xPrivKey, function(){ onDone(mnemonic.phrase, passphrase, deviceTempPrivKey, devicePrevTempPrivKey); }); }); // } // ); }); // }); } else{ // 2nd or later start // rl.question("Passphrase: ", function(passphrase){ var passphrase = ""; // rl.close(); if (process.stdout.moveCursor) process.stdout.moveCursor(0, -1); if (process.stdout.clearLine) process.stdout.clearLine(); var keys = JSON.parse(data); var deviceTempPrivKey = Buffer(keys.temp_priv_key, 'base64'); var devicePrevTempPrivKey = Buffer(keys.prev_temp_priv_key, 'base64'); determineIfWalletExists(function(bWalletExists){ if(!Mnemonic.isValid(keys.mnemonic_phrase)) throw Error('Invalid mnemonic_phrase in ' + KEYS_FILENAME) var mnemonic = new Mnemonic(keys.mnemonic_phrase); xPrivKey = mnemonic.toHDPrivateKey(passphrase); if (bWalletExists) onDone(keys.mnemonic_phrase, passphrase, deviceTempPrivKey, devicePrevTempPrivKey); else{ createWallet(xPrivKey, function(){ onDone(keys.mnemonic_phrase, passphrase, deviceTempPrivKey, devicePrevTempPrivKey); }); } }); // }); } }); }
javascript
function readKeys(onDone){ console.log('-----------------------'); fs.readFile(KEYS_FILENAME, 'utf8', function(err, data){ var rl = readline.createInterface({ input: process.stdin, output: process.stdout, //terminal: true }); if (err){ // first start console.log('failed to read keys, will gen'); var suggestedDeviceName = require('os').hostname() || 'Headless'; // rl.question("Please name this device ["+suggestedDeviceName+"]: ", function(deviceName){ var deviceName = suggestedDeviceName; var userConfFile = appDataDir + '/conf.json'; fs.writeFile(userConfFile, JSON.stringify({deviceName: deviceName, admin_email: "admin@example.com", from_email: "noreply@example.com"}, null, '\t'), 'utf8', function(err){ if (err) throw Error('failed to write conf.json: '+err); // rl.question( console.log('Device name saved to '+userConfFile+', you can edit it later if you like.\n\nPassphrase for your private keys: ') // function(passphrase){ // rl.close(); var passphrase = "" if (process.stdout.moveCursor) process.stdout.moveCursor(0, -1); if (process.stdout.clearLine) process.stdout.clearLine(); var deviceTempPrivKey = crypto.randomBytes(32); var devicePrevTempPrivKey = crypto.randomBytes(32); var mnemonic = new Mnemonic(); // generates new mnemonic while (!Mnemonic.isValid(mnemonic.toString())) mnemonic = new Mnemonic(); writeKeys(mnemonic.phrase, deviceTempPrivKey, devicePrevTempPrivKey, function(){ console.log('keys created'); xPrivKey = mnemonic.toHDPrivateKey(passphrase); createWallet(xPrivKey, function(){ onDone(mnemonic.phrase, passphrase, deviceTempPrivKey, devicePrevTempPrivKey); }); }); // } // ); }); // }); } else{ // 2nd or later start // rl.question("Passphrase: ", function(passphrase){ var passphrase = ""; // rl.close(); if (process.stdout.moveCursor) process.stdout.moveCursor(0, -1); if (process.stdout.clearLine) process.stdout.clearLine(); var keys = JSON.parse(data); var deviceTempPrivKey = Buffer(keys.temp_priv_key, 'base64'); var devicePrevTempPrivKey = Buffer(keys.prev_temp_priv_key, 'base64'); determineIfWalletExists(function(bWalletExists){ if(!Mnemonic.isValid(keys.mnemonic_phrase)) throw Error('Invalid mnemonic_phrase in ' + KEYS_FILENAME) var mnemonic = new Mnemonic(keys.mnemonic_phrase); xPrivKey = mnemonic.toHDPrivateKey(passphrase); if (bWalletExists) onDone(keys.mnemonic_phrase, passphrase, deviceTempPrivKey, devicePrevTempPrivKey); else{ createWallet(xPrivKey, function(){ onDone(keys.mnemonic_phrase, passphrase, deviceTempPrivKey, devicePrevTempPrivKey); }); } }); // }); } }); }
[ "function", "readKeys", "(", "onDone", ")", "{", "console", ".", "log", "(", "'-----------------------'", ")", ";", "fs", ".", "readFile", "(", "KEYS_FILENAME", ",", "'utf8'", ",", "function", "(", "err", ",", "data", ")", "{", "var", "rl", "=", "readline", ".", "createInterface", "(", "{", "input", ":", "process", ".", "stdin", ",", "output", ":", "process", ".", "stdout", ",", "//terminal: true", "}", ")", ";", "if", "(", "err", ")", "{", "// first start", "console", ".", "log", "(", "'failed to read keys, will gen'", ")", ";", "var", "suggestedDeviceName", "=", "require", "(", "'os'", ")", ".", "hostname", "(", ")", "||", "'Headless'", ";", "// rl.question(\"Please name this device [\"+suggestedDeviceName+\"]: \", function(deviceName){", "var", "deviceName", "=", "suggestedDeviceName", ";", "var", "userConfFile", "=", "appDataDir", "+", "'/conf.json'", ";", "fs", ".", "writeFile", "(", "userConfFile", ",", "JSON", ".", "stringify", "(", "{", "deviceName", ":", "deviceName", ",", "admin_email", ":", "\"admin@example.com\"", ",", "from_email", ":", "\"noreply@example.com\"", "}", ",", "null", ",", "'\\t'", ")", ",", "'utf8'", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "throw", "Error", "(", "'failed to write conf.json: '", "+", "err", ")", ";", "// rl.question(", "console", ".", "log", "(", "'Device name saved to '", "+", "userConfFile", "+", "', you can edit it later if you like.\\n\\nPassphrase for your private keys: '", ")", "// function(passphrase){", "// rl.close();", "var", "passphrase", "=", "\"\"", "if", "(", "process", ".", "stdout", ".", "moveCursor", ")", "process", ".", "stdout", ".", "moveCursor", "(", "0", ",", "-", "1", ")", ";", "if", "(", "process", ".", "stdout", ".", "clearLine", ")", "process", ".", "stdout", ".", "clearLine", "(", ")", ";", "var", "deviceTempPrivKey", "=", "crypto", ".", "randomBytes", "(", "32", ")", ";", "var", "devicePrevTempPrivKey", "=", "crypto", ".", "randomBytes", "(", "32", ")", ";", "var", "mnemonic", "=", "new", "Mnemonic", "(", ")", ";", "// generates new mnemonic", "while", "(", "!", "Mnemonic", ".", "isValid", "(", "mnemonic", ".", "toString", "(", ")", ")", ")", "mnemonic", "=", "new", "Mnemonic", "(", ")", ";", "writeKeys", "(", "mnemonic", ".", "phrase", ",", "deviceTempPrivKey", ",", "devicePrevTempPrivKey", ",", "function", "(", ")", "{", "console", ".", "log", "(", "'keys created'", ")", ";", "xPrivKey", "=", "mnemonic", ".", "toHDPrivateKey", "(", "passphrase", ")", ";", "createWallet", "(", "xPrivKey", ",", "function", "(", ")", "{", "onDone", "(", "mnemonic", ".", "phrase", ",", "passphrase", ",", "deviceTempPrivKey", ",", "devicePrevTempPrivKey", ")", ";", "}", ")", ";", "}", ")", ";", "// }", "// );", "}", ")", ";", "// });", "}", "else", "{", "// 2nd or later start", "// rl.question(\"Passphrase: \", function(passphrase){", "var", "passphrase", "=", "\"\"", ";", "// rl.close();", "if", "(", "process", ".", "stdout", ".", "moveCursor", ")", "process", ".", "stdout", ".", "moveCursor", "(", "0", ",", "-", "1", ")", ";", "if", "(", "process", ".", "stdout", ".", "clearLine", ")", "process", ".", "stdout", ".", "clearLine", "(", ")", ";", "var", "keys", "=", "JSON", ".", "parse", "(", "data", ")", ";", "var", "deviceTempPrivKey", "=", "Buffer", "(", "keys", ".", "temp_priv_key", ",", "'base64'", ")", ";", "var", "devicePrevTempPrivKey", "=", "Buffer", "(", "keys", ".", "prev_temp_priv_key", ",", "'base64'", ")", ";", "determineIfWalletExists", "(", "function", "(", "bWalletExists", ")", "{", "if", "(", "!", "Mnemonic", ".", "isValid", "(", "keys", ".", "mnemonic_phrase", ")", ")", "throw", "Error", "(", "'Invalid mnemonic_phrase in '", "+", "KEYS_FILENAME", ")", "var", "mnemonic", "=", "new", "Mnemonic", "(", "keys", ".", "mnemonic_phrase", ")", ";", "xPrivKey", "=", "mnemonic", ".", "toHDPrivateKey", "(", "passphrase", ")", ";", "if", "(", "bWalletExists", ")", "onDone", "(", "keys", ".", "mnemonic_phrase", ",", "passphrase", ",", "deviceTempPrivKey", ",", "devicePrevTempPrivKey", ")", ";", "else", "{", "createWallet", "(", "xPrivKey", ",", "function", "(", ")", "{", "onDone", "(", "keys", ".", "mnemonic_phrase", ",", "passphrase", ",", "deviceTempPrivKey", ",", "devicePrevTempPrivKey", ")", ";", "}", ")", ";", "}", "}", ")", ";", "// });", "}", "}", ")", ";", "}" ]
read keys from config file, or create new keys and write into config file @param {function} onDone - callback
[ "read", "keys", "from", "config", "file", "or", "create", "new", "keys", "and", "write", "into", "config", "file" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/wallet/supernode.js#L25-L92
20,688
trustnote/trustnote-pow-common
wallet/supernode.js
writeKeys
function writeKeys(mnemonic_phrase, deviceTempPrivKey, devicePrevTempPrivKey, onDone){ var keys = { mnemonic_phrase: mnemonic_phrase, temp_priv_key: deviceTempPrivKey.toString('base64'), prev_temp_priv_key: devicePrevTempPrivKey.toString('base64') }; fs.writeFile(KEYS_FILENAME, JSON.stringify(keys, null, '\t'), 'utf8', function(err){ if (err) throw Error("failed to write keys file"); if (onDone) onDone(); }); }
javascript
function writeKeys(mnemonic_phrase, deviceTempPrivKey, devicePrevTempPrivKey, onDone){ var keys = { mnemonic_phrase: mnemonic_phrase, temp_priv_key: deviceTempPrivKey.toString('base64'), prev_temp_priv_key: devicePrevTempPrivKey.toString('base64') }; fs.writeFile(KEYS_FILENAME, JSON.stringify(keys, null, '\t'), 'utf8', function(err){ if (err) throw Error("failed to write keys file"); if (onDone) onDone(); }); }
[ "function", "writeKeys", "(", "mnemonic_phrase", ",", "deviceTempPrivKey", ",", "devicePrevTempPrivKey", ",", "onDone", ")", "{", "var", "keys", "=", "{", "mnemonic_phrase", ":", "mnemonic_phrase", ",", "temp_priv_key", ":", "deviceTempPrivKey", ".", "toString", "(", "'base64'", ")", ",", "prev_temp_priv_key", ":", "devicePrevTempPrivKey", ".", "toString", "(", "'base64'", ")", "}", ";", "fs", ".", "writeFile", "(", "KEYS_FILENAME", ",", "JSON", ".", "stringify", "(", "keys", ",", "null", ",", "'\\t'", ")", ",", "'utf8'", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "throw", "Error", "(", "\"failed to write keys file\"", ")", ";", "if", "(", "onDone", ")", "onDone", "(", ")", ";", "}", ")", ";", "}" ]
write some config into config file @param {string} mnemonic_phrase - mnemonic phrase @param {string} deviceTempPrivKey - temp private key @param {string} devicePrevTempPrivKey - temp device private key @param {function} onDone - callback
[ "write", "some", "config", "into", "config", "file" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/wallet/supernode.js#L101-L113
20,689
trustnote/trustnote-pow-common
wallet/supernode.js
createWallet
function createWallet(xPrivKey, onDone){ var devicePrivKey = xPrivKey.derive("m/1'").privateKey.bn.toBuffer({size:32}); var device = require('../wallet/device.js'); device.setDevicePrivateKey(devicePrivKey); // we need device address before creating a wallet var strXPubKey = Bitcore.HDPublicKey(xPrivKey.derive("m/44'/0'/0'")).toString(); var walletDefinedByKeys = require('../wallet/wallet_defined_by_keys.js'); walletDefinedByKeys.createWalletByDevices(strXPubKey, 0, 1, [], 'any walletName', function(wallet_id){ walletDefinedByKeys.issueNextAddress(wallet_id, 0, function(){ onDone(); }); }); }
javascript
function createWallet(xPrivKey, onDone){ var devicePrivKey = xPrivKey.derive("m/1'").privateKey.bn.toBuffer({size:32}); var device = require('../wallet/device.js'); device.setDevicePrivateKey(devicePrivKey); // we need device address before creating a wallet var strXPubKey = Bitcore.HDPublicKey(xPrivKey.derive("m/44'/0'/0'")).toString(); var walletDefinedByKeys = require('../wallet/wallet_defined_by_keys.js'); walletDefinedByKeys.createWalletByDevices(strXPubKey, 0, 1, [], 'any walletName', function(wallet_id){ walletDefinedByKeys.issueNextAddress(wallet_id, 0, function(){ onDone(); }); }); }
[ "function", "createWallet", "(", "xPrivKey", ",", "onDone", ")", "{", "var", "devicePrivKey", "=", "xPrivKey", ".", "derive", "(", "\"m/1'\"", ")", ".", "privateKey", ".", "bn", ".", "toBuffer", "(", "{", "size", ":", "32", "}", ")", ";", "var", "device", "=", "require", "(", "'../wallet/device.js'", ")", ";", "device", ".", "setDevicePrivateKey", "(", "devicePrivKey", ")", ";", "// we need device address before creating a wallet", "var", "strXPubKey", "=", "Bitcore", ".", "HDPublicKey", "(", "xPrivKey", ".", "derive", "(", "\"m/44'/0'/0'\"", ")", ")", ".", "toString", "(", ")", ";", "var", "walletDefinedByKeys", "=", "require", "(", "'../wallet/wallet_defined_by_keys.js'", ")", ";", "walletDefinedByKeys", ".", "createWalletByDevices", "(", "strXPubKey", ",", "0", ",", "1", ",", "[", "]", ",", "'any walletName'", ",", "function", "(", "wallet_id", ")", "{", "walletDefinedByKeys", ".", "issueNextAddress", "(", "wallet_id", ",", "0", ",", "function", "(", ")", "{", "onDone", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
create wallet with private key @param {string} xPrivKey - private key @param {function} onDone - callback
[ "create", "wallet", "with", "private", "key" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/wallet/supernode.js#L120-L131
20,690
trustnote/trustnote-pow-common
wallet/supernode.js
determineIfWalletExists
function determineIfWalletExists(handleResult){ db.query("SELECT wallet FROM wallets", function(rows){ if (rows.length > 1) throw Error("more than 1 wallet"); handleResult(rows.length > 0); }); }
javascript
function determineIfWalletExists(handleResult){ db.query("SELECT wallet FROM wallets", function(rows){ if (rows.length > 1) throw Error("more than 1 wallet"); handleResult(rows.length > 0); }); }
[ "function", "determineIfWalletExists", "(", "handleResult", ")", "{", "db", ".", "query", "(", "\"SELECT wallet FROM wallets\"", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", ">", "1", ")", "throw", "Error", "(", "\"more than 1 wallet\"", ")", ";", "handleResult", "(", "rows", ".", "length", ">", "0", ")", ";", "}", ")", ";", "}" ]
determin if wallet exists @param {function} handleResult - callback
[ "determin", "if", "wallet", "exists" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/wallet/supernode.js#L137-L143
20,691
trustnote/trustnote-pow-common
wallet/supernode.js
signWithLocalPrivateKey
function signWithLocalPrivateKey(wallet_id, account, is_change, address_index, text_to_sign, handleSig){ var path = "m/44'/0'/" + account + "'/"+is_change+"/"+address_index; var privateKey = xPrivKey.derive(path).privateKey; var privKeyBuf = privateKey.bn.toBuffer({size:32}); // https://github.com/bitpay/bitcore-lib/issues/47 handleSig(ecdsaSig.sign(text_to_sign, privKeyBuf)); }
javascript
function signWithLocalPrivateKey(wallet_id, account, is_change, address_index, text_to_sign, handleSig){ var path = "m/44'/0'/" + account + "'/"+is_change+"/"+address_index; var privateKey = xPrivKey.derive(path).privateKey; var privKeyBuf = privateKey.bn.toBuffer({size:32}); // https://github.com/bitpay/bitcore-lib/issues/47 handleSig(ecdsaSig.sign(text_to_sign, privKeyBuf)); }
[ "function", "signWithLocalPrivateKey", "(", "wallet_id", ",", "account", ",", "is_change", ",", "address_index", ",", "text_to_sign", ",", "handleSig", ")", "{", "var", "path", "=", "\"m/44'/0'/\"", "+", "account", "+", "\"'/\"", "+", "is_change", "+", "\"/\"", "+", "address_index", ";", "var", "privateKey", "=", "xPrivKey", ".", "derive", "(", "path", ")", ".", "privateKey", ";", "var", "privKeyBuf", "=", "privateKey", ".", "bn", ".", "toBuffer", "(", "{", "size", ":", "32", "}", ")", ";", "// https://github.com/bitpay/bitcore-lib/issues/47", "handleSig", "(", "ecdsaSig", ".", "sign", "(", "text_to_sign", ",", "privKeyBuf", ")", ")", ";", "}" ]
sign with local privateKey @param {string} wallet_id - wallet id @param {number} account - account index @param {number} is_change - is_change is 0 not is_change is 1 @param {number} address_index - address index @param {string} text_to_sign - text @param {function} handleSig - callback
[ "sign", "with", "local", "privateKey" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/wallet/supernode.js#L154-L159
20,692
trustnote/trustnote-pow-common
wallet/supernode.js
readSingleAddress
function readSingleAddress(conn, handleAddress){ readSingleWallet(conn, function(wallet_id){ conn.query("SELECT address FROM my_addresses WHERE wallet=?", [wallet_id], function(rows){ if (rows.length === 0) throw Error("no addresses"); if (rows.length > 1) throw Error("more than 1 address"); handleAddress(rows[0].address); }); }) }
javascript
function readSingleAddress(conn, handleAddress){ readSingleWallet(conn, function(wallet_id){ conn.query("SELECT address FROM my_addresses WHERE wallet=?", [wallet_id], function(rows){ if (rows.length === 0) throw Error("no addresses"); if (rows.length > 1) throw Error("more than 1 address"); handleAddress(rows[0].address); }); }) }
[ "function", "readSingleAddress", "(", "conn", ",", "handleAddress", ")", "{", "readSingleWallet", "(", "conn", ",", "function", "(", "wallet_id", ")", "{", "conn", ".", "query", "(", "\"SELECT address FROM my_addresses WHERE wallet=?\"", ",", "[", "wallet_id", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "throw", "Error", "(", "\"no addresses\"", ")", ";", "if", "(", "rows", ".", "length", ">", "1", ")", "throw", "Error", "(", "\"more than 1 address\"", ")", ";", "handleAddress", "(", "rows", "[", "0", "]", ".", "address", ")", ";", "}", ")", ";", "}", ")", "}" ]
read single address, If amount of addresses is bigger than one, will throw an error @param {object} conn - database connection @param {function} handleAddress - callback
[ "read", "single", "address", "If", "amount", "of", "addresses", "is", "bigger", "than", "one", "will", "throw", "an", "error" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/wallet/supernode.js#L233-L243
20,693
trustnote/trustnote-pow-common
wallet/supernode.js
readSingleWallet
function readSingleWallet(conn, handleWallet){ conn.query("SELECT wallet FROM wallets", function(rows){ if (rows.length === 0) throw Error("no wallets"); if (rows.length > 1) throw Error("more than 1 wallet"); handleWallet(rows[0].wallet); }); }
javascript
function readSingleWallet(conn, handleWallet){ conn.query("SELECT wallet FROM wallets", function(rows){ if (rows.length === 0) throw Error("no wallets"); if (rows.length > 1) throw Error("more than 1 wallet"); handleWallet(rows[0].wallet); }); }
[ "function", "readSingleWallet", "(", "conn", ",", "handleWallet", ")", "{", "conn", ".", "query", "(", "\"SELECT wallet FROM wallets\"", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "throw", "Error", "(", "\"no wallets\"", ")", ";", "if", "(", "rows", ".", "length", ">", "1", ")", "throw", "Error", "(", "\"more than 1 wallet\"", ")", ";", "handleWallet", "(", "rows", "[", "0", "]", ".", "wallet", ")", ";", "}", ")", ";", "}" ]
read single wallet, If amount of wallets is bigger than one, will throw an error @param {object} conn - database connection @param {function} handleWallet - callback
[ "read", "single", "wallet", "If", "amount", "of", "wallets", "is", "bigger", "than", "one", "will", "throw", "an", "error" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/wallet/supernode.js#L250-L258
20,694
trustnote/trustnote-pow-common
wallet/supernode.js
readMinerDeposit
function readMinerDeposit( sSuperNodeAddress, pfnCallback ) { readMinerAddress( sSuperNodeAddress, function( err, sMinerAddress ) { if ( err ) { return pfnCallback( err ); } // // query deposit // let nDeposit = 0; // ... return pfnCallback( null, nDeposit ); }); }
javascript
function readMinerDeposit( sSuperNodeAddress, pfnCallback ) { readMinerAddress( sSuperNodeAddress, function( err, sMinerAddress ) { if ( err ) { return pfnCallback( err ); } // // query deposit // let nDeposit = 0; // ... return pfnCallback( null, nDeposit ); }); }
[ "function", "readMinerDeposit", "(", "sSuperNodeAddress", ",", "pfnCallback", ")", "{", "readMinerAddress", "(", "sSuperNodeAddress", ",", "function", "(", "err", ",", "sMinerAddress", ")", "{", "if", "(", "err", ")", "{", "return", "pfnCallback", "(", "err", ")", ";", "}", "//", "//\tquery deposit", "//", "let", "nDeposit", "=", "0", ";", "//\t...", "return", "pfnCallback", "(", "null", ",", "nDeposit", ")", ";", "}", ")", ";", "}" ]
read miner deposit @param {string} sSuperNodeAddress @param {function} pfnCallback( err, nDeposit )
[ "read", "miner", "deposit" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/wallet/supernode.js#L284-L301
20,695
trustnote/trustnote-pow-common
asset/divisible_asset.js
getSavingCallbacks
function getSavingCallbacks(callbacks){ return { ifError: callbacks.ifError, ifNotEnoughFunds: callbacks.ifNotEnoughFunds, ifOk: function(objJoint, private_payload, composer_unlock){ var objUnit = objJoint.unit; var unit = objUnit.unit; validation.validate(objJoint, { ifUnitError: function(err){ composer_unlock(); callbacks.ifError("Validation error: "+err); // throw Error("unexpected validation error: "+err); }, ifJointError: function(err){ throw Error("unexpected validation joint error: "+err); }, ifTransientError: function(err){ throw Error("unexpected validation transient error: "+err); }, ifNeedHashTree: function(){ throw Error("unexpected need hash tree"); }, ifNeedParentUnits: function(arrMissingUnits){ throw Error("unexpected dependencies: "+arrMissingUnits.join(", ")); }, ifOk: function(objValidationState, validation_unlock){ console.log("divisible asset OK "+objValidationState.sequence); if (objValidationState.sequence !== 'good'){ validation_unlock(); composer_unlock(); return callbacks.ifError("Divisible asset bad sequence "+objValidationState.sequence); } var bPrivate = !!private_payload; var objPrivateElement; var preCommitCallback = null; if (bPrivate){ preCommitCallback = function(conn, cb){ var payload_hash = objectHash.getBase64Hash(private_payload); var message_index = composer.getMessageIndexByPayloadHash(objUnit, payload_hash); objPrivateElement = { unit: unit, message_index: message_index, payload: private_payload }; validateAndSaveDivisiblePrivatePayment(conn, objPrivateElement, { ifError: function(err){ cb(err); }, ifOk: function(){ cb(); } }); }; } composer.postJointToLightVendorIfNecessaryAndSave( objJoint, function onLightError(err){ // light only console.log("failed to post divisible payment "+unit); validation_unlock(); composer_unlock(); callbacks.ifError(err); }, function save(){ writer.saveJoint( objJoint, objValidationState, preCommitCallback, function onDone(err){ console.log("saved unit "+unit, objPrivateElement); validation_unlock(); composer_unlock(); var arrChains = objPrivateElement ? [[objPrivateElement]] : null; // only one chain that consists of one element callbacks.ifOk(objJoint, arrChains, arrChains); } ); } ); } // ifOk validation }); // validate } }; }
javascript
function getSavingCallbacks(callbacks){ return { ifError: callbacks.ifError, ifNotEnoughFunds: callbacks.ifNotEnoughFunds, ifOk: function(objJoint, private_payload, composer_unlock){ var objUnit = objJoint.unit; var unit = objUnit.unit; validation.validate(objJoint, { ifUnitError: function(err){ composer_unlock(); callbacks.ifError("Validation error: "+err); // throw Error("unexpected validation error: "+err); }, ifJointError: function(err){ throw Error("unexpected validation joint error: "+err); }, ifTransientError: function(err){ throw Error("unexpected validation transient error: "+err); }, ifNeedHashTree: function(){ throw Error("unexpected need hash tree"); }, ifNeedParentUnits: function(arrMissingUnits){ throw Error("unexpected dependencies: "+arrMissingUnits.join(", ")); }, ifOk: function(objValidationState, validation_unlock){ console.log("divisible asset OK "+objValidationState.sequence); if (objValidationState.sequence !== 'good'){ validation_unlock(); composer_unlock(); return callbacks.ifError("Divisible asset bad sequence "+objValidationState.sequence); } var bPrivate = !!private_payload; var objPrivateElement; var preCommitCallback = null; if (bPrivate){ preCommitCallback = function(conn, cb){ var payload_hash = objectHash.getBase64Hash(private_payload); var message_index = composer.getMessageIndexByPayloadHash(objUnit, payload_hash); objPrivateElement = { unit: unit, message_index: message_index, payload: private_payload }; validateAndSaveDivisiblePrivatePayment(conn, objPrivateElement, { ifError: function(err){ cb(err); }, ifOk: function(){ cb(); } }); }; } composer.postJointToLightVendorIfNecessaryAndSave( objJoint, function onLightError(err){ // light only console.log("failed to post divisible payment "+unit); validation_unlock(); composer_unlock(); callbacks.ifError(err); }, function save(){ writer.saveJoint( objJoint, objValidationState, preCommitCallback, function onDone(err){ console.log("saved unit "+unit, objPrivateElement); validation_unlock(); composer_unlock(); var arrChains = objPrivateElement ? [[objPrivateElement]] : null; // only one chain that consists of one element callbacks.ifOk(objJoint, arrChains, arrChains); } ); } ); } // ifOk validation }); // validate } }; }
[ "function", "getSavingCallbacks", "(", "callbacks", ")", "{", "return", "{", "ifError", ":", "callbacks", ".", "ifError", ",", "ifNotEnoughFunds", ":", "callbacks", ".", "ifNotEnoughFunds", ",", "ifOk", ":", "function", "(", "objJoint", ",", "private_payload", ",", "composer_unlock", ")", "{", "var", "objUnit", "=", "objJoint", ".", "unit", ";", "var", "unit", "=", "objUnit", ".", "unit", ";", "validation", ".", "validate", "(", "objJoint", ",", "{", "ifUnitError", ":", "function", "(", "err", ")", "{", "composer_unlock", "(", ")", ";", "callbacks", ".", "ifError", "(", "\"Validation error: \"", "+", "err", ")", ";", "//\tthrow Error(\"unexpected validation error: \"+err);", "}", ",", "ifJointError", ":", "function", "(", "err", ")", "{", "throw", "Error", "(", "\"unexpected validation joint error: \"", "+", "err", ")", ";", "}", ",", "ifTransientError", ":", "function", "(", "err", ")", "{", "throw", "Error", "(", "\"unexpected validation transient error: \"", "+", "err", ")", ";", "}", ",", "ifNeedHashTree", ":", "function", "(", ")", "{", "throw", "Error", "(", "\"unexpected need hash tree\"", ")", ";", "}", ",", "ifNeedParentUnits", ":", "function", "(", "arrMissingUnits", ")", "{", "throw", "Error", "(", "\"unexpected dependencies: \"", "+", "arrMissingUnits", ".", "join", "(", "\", \"", ")", ")", ";", "}", ",", "ifOk", ":", "function", "(", "objValidationState", ",", "validation_unlock", ")", "{", "console", ".", "log", "(", "\"divisible asset OK \"", "+", "objValidationState", ".", "sequence", ")", ";", "if", "(", "objValidationState", ".", "sequence", "!==", "'good'", ")", "{", "validation_unlock", "(", ")", ";", "composer_unlock", "(", ")", ";", "return", "callbacks", ".", "ifError", "(", "\"Divisible asset bad sequence \"", "+", "objValidationState", ".", "sequence", ")", ";", "}", "var", "bPrivate", "=", "!", "!", "private_payload", ";", "var", "objPrivateElement", ";", "var", "preCommitCallback", "=", "null", ";", "if", "(", "bPrivate", ")", "{", "preCommitCallback", "=", "function", "(", "conn", ",", "cb", ")", "{", "var", "payload_hash", "=", "objectHash", ".", "getBase64Hash", "(", "private_payload", ")", ";", "var", "message_index", "=", "composer", ".", "getMessageIndexByPayloadHash", "(", "objUnit", ",", "payload_hash", ")", ";", "objPrivateElement", "=", "{", "unit", ":", "unit", ",", "message_index", ":", "message_index", ",", "payload", ":", "private_payload", "}", ";", "validateAndSaveDivisiblePrivatePayment", "(", "conn", ",", "objPrivateElement", ",", "{", "ifError", ":", "function", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "}", ",", "ifOk", ":", "function", "(", ")", "{", "cb", "(", ")", ";", "}", "}", ")", ";", "}", ";", "}", "composer", ".", "postJointToLightVendorIfNecessaryAndSave", "(", "objJoint", ",", "function", "onLightError", "(", "err", ")", "{", "// light only", "console", ".", "log", "(", "\"failed to post divisible payment \"", "+", "unit", ")", ";", "validation_unlock", "(", ")", ";", "composer_unlock", "(", ")", ";", "callbacks", ".", "ifError", "(", "err", ")", ";", "}", ",", "function", "save", "(", ")", "{", "writer", ".", "saveJoint", "(", "objJoint", ",", "objValidationState", ",", "preCommitCallback", ",", "function", "onDone", "(", "err", ")", "{", "console", ".", "log", "(", "\"saved unit \"", "+", "unit", ",", "objPrivateElement", ")", ";", "validation_unlock", "(", ")", ";", "composer_unlock", "(", ")", ";", "var", "arrChains", "=", "objPrivateElement", "?", "[", "[", "objPrivateElement", "]", "]", ":", "null", ";", "// only one chain that consists of one element", "callbacks", ".", "ifOk", "(", "objJoint", ",", "arrChains", ",", "arrChains", ")", ";", "}", ")", ";", "}", ")", ";", "}", "// ifOk validation", "}", ")", ";", "// validate", "}", "}", ";", "}" ]
ifOk validates and saves before calling back
[ "ifOk", "validates", "and", "saves", "before", "calling", "back" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/asset/divisible_asset.js#L258-L340
20,696
trustnote/trustnote-pow-common
unit/composer.js
pickDivisibleCoinsForAmount
function pickDivisibleCoinsForAmount(conn, objAsset, arrAddresses, last_ball_mci, amount, bMultiAuthored, onDone){ var asset = objAsset ? objAsset.asset : null; console.log("pick coins "+asset+" amount "+amount); var is_base = objAsset ? 0 : 1; var arrInputsWithProofs = []; var total_amount = 0; var required_amount = amount; // adds element to arrInputsWithProofs function addInput(input){ total_amount += input.amount; var objInputWithProof = {input: input}; if (objAsset && objAsset.is_private){ // for type=payment only var spend_proof = objectHash.getBase64Hash({ asset: asset, amount: input.amount, address: input.address, unit: input.unit, message_index: input.message_index, output_index: input.output_index, blinding: input.blinding }); var objSpendProof = {spend_proof: spend_proof}; if (bMultiAuthored) objSpendProof.address = input.address; objInputWithProof.spend_proof = objSpendProof; } if (!bMultiAuthored || !input.type) delete input.address; delete input.amount; delete input.blinding; arrInputsWithProofs.push(objInputWithProof); } // first, try to find a coin just bigger than the required amount function pickOneCoinJustBiggerAndContinue(){ if (amount === Infinity) return pickMultipleCoinsAndContinue(); var more = is_base ? '>' : '>='; conn.query( "SELECT unit, message_index, output_index, amount, blinding, address \n\ FROM outputs \n\ CROSS JOIN units USING(unit) \n\ WHERE address IN(?) AND asset"+(asset ? "="+conn.escape(asset) : " IS NULL")+" AND is_spent=0 AND amount "+more+" ? \n\ AND is_stable=1 AND sequence='good' AND main_chain_index<=? \n\ ORDER BY amount LIMIT 1", [arrSpendableAddresses, amount+is_base*TRANSFER_INPUT_SIZE, last_ball_mci], function(rows){ if (rows.length === 1){ var input = rows[0]; // default type is "transfer" addInput(input); onDone(arrInputsWithProofs, total_amount); } else pickMultipleCoinsAndContinue(); } ); } // then, try to add smaller coins until we accumulate the target amount function pickMultipleCoinsAndContinue(){ conn.query( "SELECT unit, message_index, output_index, amount, address, blinding \n\ FROM outputs \n\ CROSS JOIN units USING(unit) \n\ WHERE address IN(?) AND asset"+(asset ? "="+conn.escape(asset) : " IS NULL")+" AND is_spent=0 \n\ AND is_stable=1 AND sequence='good' AND main_chain_index<=? \n\ ORDER BY amount DESC", [arrSpendableAddresses, last_ball_mci], function(rows){ async.eachSeries( rows, function(row, cb){ var input = row; objectHash.cleanNulls(input); required_amount += is_base*TRANSFER_INPUT_SIZE; addInput(input); // if we allow equality, we might get 0 amount for change which is invalid var bFound = is_base ? (total_amount > required_amount) : (total_amount >= required_amount); bFound ? cb('found') : cb(); }, function(err){ if (err === 'found') onDone(arrInputsWithProofs, total_amount); else if (asset) issueAsset(); else{ // pow modi //addHeadersCommissionInputs(); finish(); } } ); } ); } // pow del // function addHeadersCommissionInputs(){ // addMcInputs("headers_commission", HEADERS_COMMISSION_INPUT_SIZE, // headers_commission.getMaxSpendableMciForLastBallMci(last_ball_mci), addWitnessingInputs); // } // function addWitnessingInputs(){ // addMcInputs("witnessing", WITNESSING_INPUT_SIZE, paid_witnessing.getMaxSpendableMciForLastBallMci(last_ball_mci), issueAsset); // } // function addMcInputs(type, input_size, max_mci, onStillNotEnough){ // async.eachSeries( // arrAddresses, // function(address, cb){ // var target_amount = required_amount + input_size + (bMultiAuthored ? ADDRESS_SIZE : 0) - total_amount; // mc_outputs.findMcIndexIntervalToTargetAmount(conn, type, address, max_mci, target_amount, { // ifNothing: cb, // ifFound: function(from_mc_index, to_mc_index, earnings, bSufficient){ // if (earnings === 0) // throw Error("earnings === 0"); // total_amount += earnings; // var input = { // type: type, // from_main_chain_index: from_mc_index, // to_main_chain_index: to_mc_index // }; // var full_input_size = input_size; // if (bMultiAuthored){ // full_input_size += ADDRESS_SIZE; // address length // input.address = address; // } // required_amount += full_input_size; // arrInputsWithProofs.push({input: input}); // (total_amount > required_amount) // ? cb("found") // break eachSeries // : cb(); // try next address // } // }); // }, // function(err){ // if (!err) // console.log(arrAddresses+" "+type+": got only "+total_amount+" out of required "+required_amount); // (err === "found") ? onDone(arrInputsWithProofs, total_amount) : onStillNotEnough(); // } // ); // } function issueAsset(){ if (!asset) return finish(); else{ if (amount === Infinity && !objAsset.cap) // don't try to create infinite issue return onDone(null); } console.log("will try to issue asset "+asset); // for issue, we use full list of addresses rather than spendable addresses if (objAsset.issued_by_definer_only && arrAddresses.indexOf(objAsset.definer_address) === -1) return finish(); var issuer_address = objAsset.issued_by_definer_only ? objAsset.definer_address : arrAddresses[0]; var issue_amount = objAsset.cap || (required_amount - total_amount) || 1; // 1 currency unit in case required_amount = total_amount function addIssueInput(serial_number){ total_amount += issue_amount; var input = { type: "issue", amount: issue_amount, serial_number: serial_number }; if (bMultiAuthored) input.address = issuer_address; var objInputWithProof = {input: input}; if (objAsset && objAsset.is_private){ var spend_proof = objectHash.getBase64Hash({ asset: asset, amount: issue_amount, denomination: 1, address: issuer_address, serial_number: serial_number }); var objSpendProof = {spend_proof: spend_proof}; if (bMultiAuthored) objSpendProof.address = input.address; objInputWithProof.spend_proof = objSpendProof; } arrInputsWithProofs.push(objInputWithProof); var bFound = is_base ? (total_amount > required_amount) : (total_amount >= required_amount); bFound ? onDone(arrInputsWithProofs, total_amount) : finish(); } if (objAsset.cap){ conn.query("SELECT 1 FROM inputs WHERE type='issue' AND asset=?", [asset], function(rows){ if (rows.length > 0) // already issued return finish(); addIssueInput(1); }); } else{ conn.query( "SELECT MAX(serial_number) AS max_serial_number FROM inputs WHERE type='issue' AND asset=? AND address=?", [asset, issuer_address], function(rows){ var max_serial_number = (rows.length === 0) ? 0 : rows[0].max_serial_number; addIssueInput(max_serial_number+1); } ); } } function finish(){ if (amount === Infinity && arrInputsWithProofs.length > 0) onDone(arrInputsWithProofs, total_amount); else onDone(null); } var arrSpendableAddresses = arrAddresses.concat(); // cloning if (objAsset && objAsset.auto_destroy){ var i = arrAddresses.indexOf(objAsset.definer_address); if (i>=0) arrSpendableAddresses.splice(i, 1); } if (arrSpendableAddresses.length > 0) pickOneCoinJustBiggerAndContinue(); else issueAsset(); }
javascript
function pickDivisibleCoinsForAmount(conn, objAsset, arrAddresses, last_ball_mci, amount, bMultiAuthored, onDone){ var asset = objAsset ? objAsset.asset : null; console.log("pick coins "+asset+" amount "+amount); var is_base = objAsset ? 0 : 1; var arrInputsWithProofs = []; var total_amount = 0; var required_amount = amount; // adds element to arrInputsWithProofs function addInput(input){ total_amount += input.amount; var objInputWithProof = {input: input}; if (objAsset && objAsset.is_private){ // for type=payment only var spend_proof = objectHash.getBase64Hash({ asset: asset, amount: input.amount, address: input.address, unit: input.unit, message_index: input.message_index, output_index: input.output_index, blinding: input.blinding }); var objSpendProof = {spend_proof: spend_proof}; if (bMultiAuthored) objSpendProof.address = input.address; objInputWithProof.spend_proof = objSpendProof; } if (!bMultiAuthored || !input.type) delete input.address; delete input.amount; delete input.blinding; arrInputsWithProofs.push(objInputWithProof); } // first, try to find a coin just bigger than the required amount function pickOneCoinJustBiggerAndContinue(){ if (amount === Infinity) return pickMultipleCoinsAndContinue(); var more = is_base ? '>' : '>='; conn.query( "SELECT unit, message_index, output_index, amount, blinding, address \n\ FROM outputs \n\ CROSS JOIN units USING(unit) \n\ WHERE address IN(?) AND asset"+(asset ? "="+conn.escape(asset) : " IS NULL")+" AND is_spent=0 AND amount "+more+" ? \n\ AND is_stable=1 AND sequence='good' AND main_chain_index<=? \n\ ORDER BY amount LIMIT 1", [arrSpendableAddresses, amount+is_base*TRANSFER_INPUT_SIZE, last_ball_mci], function(rows){ if (rows.length === 1){ var input = rows[0]; // default type is "transfer" addInput(input); onDone(arrInputsWithProofs, total_amount); } else pickMultipleCoinsAndContinue(); } ); } // then, try to add smaller coins until we accumulate the target amount function pickMultipleCoinsAndContinue(){ conn.query( "SELECT unit, message_index, output_index, amount, address, blinding \n\ FROM outputs \n\ CROSS JOIN units USING(unit) \n\ WHERE address IN(?) AND asset"+(asset ? "="+conn.escape(asset) : " IS NULL")+" AND is_spent=0 \n\ AND is_stable=1 AND sequence='good' AND main_chain_index<=? \n\ ORDER BY amount DESC", [arrSpendableAddresses, last_ball_mci], function(rows){ async.eachSeries( rows, function(row, cb){ var input = row; objectHash.cleanNulls(input); required_amount += is_base*TRANSFER_INPUT_SIZE; addInput(input); // if we allow equality, we might get 0 amount for change which is invalid var bFound = is_base ? (total_amount > required_amount) : (total_amount >= required_amount); bFound ? cb('found') : cb(); }, function(err){ if (err === 'found') onDone(arrInputsWithProofs, total_amount); else if (asset) issueAsset(); else{ // pow modi //addHeadersCommissionInputs(); finish(); } } ); } ); } // pow del // function addHeadersCommissionInputs(){ // addMcInputs("headers_commission", HEADERS_COMMISSION_INPUT_SIZE, // headers_commission.getMaxSpendableMciForLastBallMci(last_ball_mci), addWitnessingInputs); // } // function addWitnessingInputs(){ // addMcInputs("witnessing", WITNESSING_INPUT_SIZE, paid_witnessing.getMaxSpendableMciForLastBallMci(last_ball_mci), issueAsset); // } // function addMcInputs(type, input_size, max_mci, onStillNotEnough){ // async.eachSeries( // arrAddresses, // function(address, cb){ // var target_amount = required_amount + input_size + (bMultiAuthored ? ADDRESS_SIZE : 0) - total_amount; // mc_outputs.findMcIndexIntervalToTargetAmount(conn, type, address, max_mci, target_amount, { // ifNothing: cb, // ifFound: function(from_mc_index, to_mc_index, earnings, bSufficient){ // if (earnings === 0) // throw Error("earnings === 0"); // total_amount += earnings; // var input = { // type: type, // from_main_chain_index: from_mc_index, // to_main_chain_index: to_mc_index // }; // var full_input_size = input_size; // if (bMultiAuthored){ // full_input_size += ADDRESS_SIZE; // address length // input.address = address; // } // required_amount += full_input_size; // arrInputsWithProofs.push({input: input}); // (total_amount > required_amount) // ? cb("found") // break eachSeries // : cb(); // try next address // } // }); // }, // function(err){ // if (!err) // console.log(arrAddresses+" "+type+": got only "+total_amount+" out of required "+required_amount); // (err === "found") ? onDone(arrInputsWithProofs, total_amount) : onStillNotEnough(); // } // ); // } function issueAsset(){ if (!asset) return finish(); else{ if (amount === Infinity && !objAsset.cap) // don't try to create infinite issue return onDone(null); } console.log("will try to issue asset "+asset); // for issue, we use full list of addresses rather than spendable addresses if (objAsset.issued_by_definer_only && arrAddresses.indexOf(objAsset.definer_address) === -1) return finish(); var issuer_address = objAsset.issued_by_definer_only ? objAsset.definer_address : arrAddresses[0]; var issue_amount = objAsset.cap || (required_amount - total_amount) || 1; // 1 currency unit in case required_amount = total_amount function addIssueInput(serial_number){ total_amount += issue_amount; var input = { type: "issue", amount: issue_amount, serial_number: serial_number }; if (bMultiAuthored) input.address = issuer_address; var objInputWithProof = {input: input}; if (objAsset && objAsset.is_private){ var spend_proof = objectHash.getBase64Hash({ asset: asset, amount: issue_amount, denomination: 1, address: issuer_address, serial_number: serial_number }); var objSpendProof = {spend_proof: spend_proof}; if (bMultiAuthored) objSpendProof.address = input.address; objInputWithProof.spend_proof = objSpendProof; } arrInputsWithProofs.push(objInputWithProof); var bFound = is_base ? (total_amount > required_amount) : (total_amount >= required_amount); bFound ? onDone(arrInputsWithProofs, total_amount) : finish(); } if (objAsset.cap){ conn.query("SELECT 1 FROM inputs WHERE type='issue' AND asset=?", [asset], function(rows){ if (rows.length > 0) // already issued return finish(); addIssueInput(1); }); } else{ conn.query( "SELECT MAX(serial_number) AS max_serial_number FROM inputs WHERE type='issue' AND asset=? AND address=?", [asset, issuer_address], function(rows){ var max_serial_number = (rows.length === 0) ? 0 : rows[0].max_serial_number; addIssueInput(max_serial_number+1); } ); } } function finish(){ if (amount === Infinity && arrInputsWithProofs.length > 0) onDone(arrInputsWithProofs, total_amount); else onDone(null); } var arrSpendableAddresses = arrAddresses.concat(); // cloning if (objAsset && objAsset.auto_destroy){ var i = arrAddresses.indexOf(objAsset.definer_address); if (i>=0) arrSpendableAddresses.splice(i, 1); } if (arrSpendableAddresses.length > 0) pickOneCoinJustBiggerAndContinue(); else issueAsset(); }
[ "function", "pickDivisibleCoinsForAmount", "(", "conn", ",", "objAsset", ",", "arrAddresses", ",", "last_ball_mci", ",", "amount", ",", "bMultiAuthored", ",", "onDone", ")", "{", "var", "asset", "=", "objAsset", "?", "objAsset", ".", "asset", ":", "null", ";", "console", ".", "log", "(", "\"pick coins \"", "+", "asset", "+", "\" amount \"", "+", "amount", ")", ";", "var", "is_base", "=", "objAsset", "?", "0", ":", "1", ";", "var", "arrInputsWithProofs", "=", "[", "]", ";", "var", "total_amount", "=", "0", ";", "var", "required_amount", "=", "amount", ";", "// adds element to arrInputsWithProofs", "function", "addInput", "(", "input", ")", "{", "total_amount", "+=", "input", ".", "amount", ";", "var", "objInputWithProof", "=", "{", "input", ":", "input", "}", ";", "if", "(", "objAsset", "&&", "objAsset", ".", "is_private", ")", "{", "// for type=payment only", "var", "spend_proof", "=", "objectHash", ".", "getBase64Hash", "(", "{", "asset", ":", "asset", ",", "amount", ":", "input", ".", "amount", ",", "address", ":", "input", ".", "address", ",", "unit", ":", "input", ".", "unit", ",", "message_index", ":", "input", ".", "message_index", ",", "output_index", ":", "input", ".", "output_index", ",", "blinding", ":", "input", ".", "blinding", "}", ")", ";", "var", "objSpendProof", "=", "{", "spend_proof", ":", "spend_proof", "}", ";", "if", "(", "bMultiAuthored", ")", "objSpendProof", ".", "address", "=", "input", ".", "address", ";", "objInputWithProof", ".", "spend_proof", "=", "objSpendProof", ";", "}", "if", "(", "!", "bMultiAuthored", "||", "!", "input", ".", "type", ")", "delete", "input", ".", "address", ";", "delete", "input", ".", "amount", ";", "delete", "input", ".", "blinding", ";", "arrInputsWithProofs", ".", "push", "(", "objInputWithProof", ")", ";", "}", "// first, try to find a coin just bigger than the required amount", "function", "pickOneCoinJustBiggerAndContinue", "(", ")", "{", "if", "(", "amount", "===", "Infinity", ")", "return", "pickMultipleCoinsAndContinue", "(", ")", ";", "var", "more", "=", "is_base", "?", "'>'", ":", "'>='", ";", "conn", ".", "query", "(", "\"SELECT unit, message_index, output_index, amount, blinding, address \\n\\\n\t\t\tFROM outputs \\n\\\n\t\t\tCROSS JOIN units USING(unit) \\n\\\n\t\t\tWHERE address IN(?) AND asset\"", "+", "(", "asset", "?", "\"=\"", "+", "conn", ".", "escape", "(", "asset", ")", ":", "\" IS NULL\"", ")", "+", "\" AND is_spent=0 AND amount \"", "+", "more", "+", "\" ? \\n\\\n\t\t\t\tAND is_stable=1 AND sequence='good' AND main_chain_index<=? \\n\\\n\t\t\tORDER BY amount LIMIT 1\"", ",", "[", "arrSpendableAddresses", ",", "amount", "+", "is_base", "*", "TRANSFER_INPUT_SIZE", ",", "last_ball_mci", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "1", ")", "{", "var", "input", "=", "rows", "[", "0", "]", ";", "// default type is \"transfer\"", "addInput", "(", "input", ")", ";", "onDone", "(", "arrInputsWithProofs", ",", "total_amount", ")", ";", "}", "else", "pickMultipleCoinsAndContinue", "(", ")", ";", "}", ")", ";", "}", "// then, try to add smaller coins until we accumulate the target amount", "function", "pickMultipleCoinsAndContinue", "(", ")", "{", "conn", ".", "query", "(", "\"SELECT unit, message_index, output_index, amount, address, blinding \\n\\\n\t\t\tFROM outputs \\n\\\n\t\t\tCROSS JOIN units USING(unit) \\n\\\n\t\t\tWHERE address IN(?) AND asset\"", "+", "(", "asset", "?", "\"=\"", "+", "conn", ".", "escape", "(", "asset", ")", ":", "\" IS NULL\"", ")", "+", "\" AND is_spent=0 \\n\\\n\t\t\t\tAND is_stable=1 AND sequence='good' AND main_chain_index<=? \\n\\\n\t\t\tORDER BY amount DESC\"", ",", "[", "arrSpendableAddresses", ",", "last_ball_mci", "]", ",", "function", "(", "rows", ")", "{", "async", ".", "eachSeries", "(", "rows", ",", "function", "(", "row", ",", "cb", ")", "{", "var", "input", "=", "row", ";", "objectHash", ".", "cleanNulls", "(", "input", ")", ";", "required_amount", "+=", "is_base", "*", "TRANSFER_INPUT_SIZE", ";", "addInput", "(", "input", ")", ";", "// if we allow equality, we might get 0 amount for change which is invalid", "var", "bFound", "=", "is_base", "?", "(", "total_amount", ">", "required_amount", ")", ":", "(", "total_amount", ">=", "required_amount", ")", ";", "bFound", "?", "cb", "(", "'found'", ")", ":", "cb", "(", ")", ";", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", "===", "'found'", ")", "onDone", "(", "arrInputsWithProofs", ",", "total_amount", ")", ";", "else", "if", "(", "asset", ")", "issueAsset", "(", ")", ";", "else", "{", "// pow modi", "//addHeadersCommissionInputs();", "finish", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", "// pow del", "// function addHeadersCommissionInputs(){", "// \taddMcInputs(\"headers_commission\", HEADERS_COMMISSION_INPUT_SIZE,", "// \t\theaders_commission.getMaxSpendableMciForLastBallMci(last_ball_mci), addWitnessingInputs);", "// }", "// function addWitnessingInputs(){", "// \taddMcInputs(\"witnessing\", WITNESSING_INPUT_SIZE, paid_witnessing.getMaxSpendableMciForLastBallMci(last_ball_mci), issueAsset);", "// }", "// function addMcInputs(type, input_size, max_mci, onStillNotEnough){", "// \tasync.eachSeries(", "// \t\tarrAddresses,", "// \t\tfunction(address, cb){", "// \t\t\tvar target_amount = required_amount + input_size + (bMultiAuthored ? ADDRESS_SIZE : 0) - total_amount;", "// \t\t\tmc_outputs.findMcIndexIntervalToTargetAmount(conn, type, address, max_mci, target_amount, {", "// \t\t\t\tifNothing: cb,", "// \t\t\t\tifFound: function(from_mc_index, to_mc_index, earnings, bSufficient){", "// \t\t\t\t\tif (earnings === 0)", "// \t\t\t\t\t\tthrow Error(\"earnings === 0\");", "// \t\t\t\t\ttotal_amount += earnings;", "// \t\t\t\t\tvar input = {", "// \t\t\t\t\t\ttype: type,", "// \t\t\t\t\t\tfrom_main_chain_index: from_mc_index,", "// \t\t\t\t\t\tto_main_chain_index: to_mc_index", "// \t\t\t\t\t};", "// \t\t\t\t\tvar full_input_size = input_size;", "// \t\t\t\t\tif (bMultiAuthored){", "// \t\t\t\t\t\tfull_input_size += ADDRESS_SIZE; // address length", "// \t\t\t\t\t\tinput.address = address;", "// \t\t\t\t\t}", "// \t\t\t\t\trequired_amount += full_input_size;", "// \t\t\t\t\tarrInputsWithProofs.push({input: input});", "// \t\t\t\t\t(total_amount > required_amount)", "// \t\t\t\t\t\t? cb(\"found\") // break eachSeries", "// \t\t\t\t\t\t: cb(); // try next address", "// \t\t\t\t}", "// \t\t\t});", "// \t\t},", "// \t\tfunction(err){", "// \t\t\tif (!err)", "// \t\t\t\tconsole.log(arrAddresses+\" \"+type+\": got only \"+total_amount+\" out of required \"+required_amount);", "// \t\t\t(err === \"found\") ? onDone(arrInputsWithProofs, total_amount) : onStillNotEnough();", "// \t\t}", "// \t);", "// }", "function", "issueAsset", "(", ")", "{", "if", "(", "!", "asset", ")", "return", "finish", "(", ")", ";", "else", "{", "if", "(", "amount", "===", "Infinity", "&&", "!", "objAsset", ".", "cap", ")", "// don't try to create infinite issue", "return", "onDone", "(", "null", ")", ";", "}", "console", ".", "log", "(", "\"will try to issue asset \"", "+", "asset", ")", ";", "// for issue, we use full list of addresses rather than spendable addresses", "if", "(", "objAsset", ".", "issued_by_definer_only", "&&", "arrAddresses", ".", "indexOf", "(", "objAsset", ".", "definer_address", ")", "===", "-", "1", ")", "return", "finish", "(", ")", ";", "var", "issuer_address", "=", "objAsset", ".", "issued_by_definer_only", "?", "objAsset", ".", "definer_address", ":", "arrAddresses", "[", "0", "]", ";", "var", "issue_amount", "=", "objAsset", ".", "cap", "||", "(", "required_amount", "-", "total_amount", ")", "||", "1", ";", "// 1 currency unit in case required_amount = total_amount", "function", "addIssueInput", "(", "serial_number", ")", "{", "total_amount", "+=", "issue_amount", ";", "var", "input", "=", "{", "type", ":", "\"issue\"", ",", "amount", ":", "issue_amount", ",", "serial_number", ":", "serial_number", "}", ";", "if", "(", "bMultiAuthored", ")", "input", ".", "address", "=", "issuer_address", ";", "var", "objInputWithProof", "=", "{", "input", ":", "input", "}", ";", "if", "(", "objAsset", "&&", "objAsset", ".", "is_private", ")", "{", "var", "spend_proof", "=", "objectHash", ".", "getBase64Hash", "(", "{", "asset", ":", "asset", ",", "amount", ":", "issue_amount", ",", "denomination", ":", "1", ",", "address", ":", "issuer_address", ",", "serial_number", ":", "serial_number", "}", ")", ";", "var", "objSpendProof", "=", "{", "spend_proof", ":", "spend_proof", "}", ";", "if", "(", "bMultiAuthored", ")", "objSpendProof", ".", "address", "=", "input", ".", "address", ";", "objInputWithProof", ".", "spend_proof", "=", "objSpendProof", ";", "}", "arrInputsWithProofs", ".", "push", "(", "objInputWithProof", ")", ";", "var", "bFound", "=", "is_base", "?", "(", "total_amount", ">", "required_amount", ")", ":", "(", "total_amount", ">=", "required_amount", ")", ";", "bFound", "?", "onDone", "(", "arrInputsWithProofs", ",", "total_amount", ")", ":", "finish", "(", ")", ";", "}", "if", "(", "objAsset", ".", "cap", ")", "{", "conn", ".", "query", "(", "\"SELECT 1 FROM inputs WHERE type='issue' AND asset=?\"", ",", "[", "asset", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", ">", "0", ")", "// already issued", "return", "finish", "(", ")", ";", "addIssueInput", "(", "1", ")", ";", "}", ")", ";", "}", "else", "{", "conn", ".", "query", "(", "\"SELECT MAX(serial_number) AS max_serial_number FROM inputs WHERE type='issue' AND asset=? AND address=?\"", ",", "[", "asset", ",", "issuer_address", "]", ",", "function", "(", "rows", ")", "{", "var", "max_serial_number", "=", "(", "rows", ".", "length", "===", "0", ")", "?", "0", ":", "rows", "[", "0", "]", ".", "max_serial_number", ";", "addIssueInput", "(", "max_serial_number", "+", "1", ")", ";", "}", ")", ";", "}", "}", "function", "finish", "(", ")", "{", "if", "(", "amount", "===", "Infinity", "&&", "arrInputsWithProofs", ".", "length", ">", "0", ")", "onDone", "(", "arrInputsWithProofs", ",", "total_amount", ")", ";", "else", "onDone", "(", "null", ")", ";", "}", "var", "arrSpendableAddresses", "=", "arrAddresses", ".", "concat", "(", ")", ";", "// cloning", "if", "(", "objAsset", "&&", "objAsset", ".", "auto_destroy", ")", "{", "var", "i", "=", "arrAddresses", ".", "indexOf", "(", "objAsset", ".", "definer_address", ")", ";", "if", "(", "i", ">=", "0", ")", "arrSpendableAddresses", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "if", "(", "arrSpendableAddresses", ".", "length", ">", "0", ")", "pickOneCoinJustBiggerAndContinue", "(", ")", ";", "else", "issueAsset", "(", ")", ";", "}" ]
bMultiAuthored includes all addresses, not just those that pay arrAddresses is paying addresses
[ "bMultiAuthored", "includes", "all", "addresses", "not", "just", "those", "that", "pay", "arrAddresses", "is", "paying", "addresses" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/unit/composer.js#L57-L280
20,697
trustnote/trustnote-pow-common
unit/composer.js
composePowJoint
function composePowJoint(from_address, round_index, seed, deposit, solution, signer, callbacks){ var payload = {seed: seed, deposit:deposit, solution: solution}; var objMessage = { app: "pow_equihash", payload_location: "inline", payload_hash: objectHash.getBase64Hash(payload), payload: payload }; composeJoint({ paying_addresses: [from_address], outputs: [{address: from_address, amount: 0}], messages: [objMessage], round_index: round_index, pow_type: constants.POW_TYPE_POW_EQUHASH, signer: signer, callbacks: callbacks }); }
javascript
function composePowJoint(from_address, round_index, seed, deposit, solution, signer, callbacks){ var payload = {seed: seed, deposit:deposit, solution: solution}; var objMessage = { app: "pow_equihash", payload_location: "inline", payload_hash: objectHash.getBase64Hash(payload), payload: payload }; composeJoint({ paying_addresses: [from_address], outputs: [{address: from_address, amount: 0}], messages: [objMessage], round_index: round_index, pow_type: constants.POW_TYPE_POW_EQUHASH, signer: signer, callbacks: callbacks }); }
[ "function", "composePowJoint", "(", "from_address", ",", "round_index", ",", "seed", ",", "deposit", ",", "solution", ",", "signer", ",", "callbacks", ")", "{", "var", "payload", "=", "{", "seed", ":", "seed", ",", "deposit", ":", "deposit", ",", "solution", ":", "solution", "}", ";", "var", "objMessage", "=", "{", "app", ":", "\"pow_equihash\"", ",", "payload_location", ":", "\"inline\"", ",", "payload_hash", ":", "objectHash", ".", "getBase64Hash", "(", "payload", ")", ",", "payload", ":", "payload", "}", ";", "composeJoint", "(", "{", "paying_addresses", ":", "[", "from_address", "]", ",", "outputs", ":", "[", "{", "address", ":", "from_address", ",", "amount", ":", "0", "}", "]", ",", "messages", ":", "[", "objMessage", "]", ",", "round_index", ":", "round_index", ",", "pow_type", ":", "constants", ".", "POW_TYPE_POW_EQUHASH", ",", "signer", ":", "signer", ",", "callbacks", ":", "callbacks", "}", ")", ";", "}" ]
pow add pow joint
[ "pow", "add", "pow", "joint" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/unit/composer.js#L371-L388
20,698
trustnote/trustnote-pow-common
unit/composer.js
composeTrustMEJoint
function composeTrustMEJoint(from_address, round_index, signer, callbacks){ composeJoint({ paying_addresses: [from_address], outputs: [{address: from_address, amount: 0}], round_index: round_index, pow_type: constants.POW_TYPE_TRUSTME, signer: signer, callbacks: callbacks }); }
javascript
function composeTrustMEJoint(from_address, round_index, signer, callbacks){ composeJoint({ paying_addresses: [from_address], outputs: [{address: from_address, amount: 0}], round_index: round_index, pow_type: constants.POW_TYPE_TRUSTME, signer: signer, callbacks: callbacks }); }
[ "function", "composeTrustMEJoint", "(", "from_address", ",", "round_index", ",", "signer", ",", "callbacks", ")", "{", "composeJoint", "(", "{", "paying_addresses", ":", "[", "from_address", "]", ",", "outputs", ":", "[", "{", "address", ":", "from_address", ",", "amount", ":", "0", "}", "]", ",", "round_index", ":", "round_index", ",", "pow_type", ":", "constants", ".", "POW_TYPE_TRUSTME", ",", "signer", ":", "signer", ",", "callbacks", ":", "callbacks", "}", ")", ";", "}" ]
pow add trustme joint
[ "pow", "add", "trustme", "joint" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/unit/composer.js#L391-L400
20,699
trustnote/trustnote-pow-common
unit/composer.js
composeCoinbaseJoint
function composeCoinbaseJoint(from_address, coinbase_address, round_index, coinbase_amount, signer, callbacks){ var coinbase_foundation_amount = Math.floor(coinbase_amount*constants.FOUNDATION_RATIO); composeJoint({ paying_addresses: [from_address], outputs: [{address: coinbase_address, amount: 0}, {address: constants.FOUNDATION_ADDRESS, amount: coinbase_foundation_amount}], //inputs: [{type: "coinbase", amount: coinbase_amount, address: from_address}], inputs: [{type: "coinbase", amount: coinbase_amount}], round_index: round_index, input_amount: coinbase_amount, pow_type: constants.POW_TYPE_COIN_BASE, signer: signer, callbacks: callbacks }); }
javascript
function composeCoinbaseJoint(from_address, coinbase_address, round_index, coinbase_amount, signer, callbacks){ var coinbase_foundation_amount = Math.floor(coinbase_amount*constants.FOUNDATION_RATIO); composeJoint({ paying_addresses: [from_address], outputs: [{address: coinbase_address, amount: 0}, {address: constants.FOUNDATION_ADDRESS, amount: coinbase_foundation_amount}], //inputs: [{type: "coinbase", amount: coinbase_amount, address: from_address}], inputs: [{type: "coinbase", amount: coinbase_amount}], round_index: round_index, input_amount: coinbase_amount, pow_type: constants.POW_TYPE_COIN_BASE, signer: signer, callbacks: callbacks }); }
[ "function", "composeCoinbaseJoint", "(", "from_address", ",", "coinbase_address", ",", "round_index", ",", "coinbase_amount", ",", "signer", ",", "callbacks", ")", "{", "var", "coinbase_foundation_amount", "=", "Math", ".", "floor", "(", "coinbase_amount", "*", "constants", ".", "FOUNDATION_RATIO", ")", ";", "composeJoint", "(", "{", "paying_addresses", ":", "[", "from_address", "]", ",", "outputs", ":", "[", "{", "address", ":", "coinbase_address", ",", "amount", ":", "0", "}", ",", "{", "address", ":", "constants", ".", "FOUNDATION_ADDRESS", ",", "amount", ":", "coinbase_foundation_amount", "}", "]", ",", "//inputs: [{type: \"coinbase\", amount: coinbase_amount, address: from_address}],", "inputs", ":", "[", "{", "type", ":", "\"coinbase\"", ",", "amount", ":", "coinbase_amount", "}", "]", ",", "round_index", ":", "round_index", ",", "input_amount", ":", "coinbase_amount", ",", "pow_type", ":", "constants", ".", "POW_TYPE_COIN_BASE", ",", "signer", ":", "signer", ",", "callbacks", ":", "callbacks", "}", ")", ";", "}" ]
pow add Coinbase joint
[ "pow", "add", "Coinbase", "joint" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/unit/composer.js#L403-L416