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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
7,400
melonjs/melonJS
examples/whack-a-mole/js/entities/entities.js
function ( dt ) { if (this.isVisible) { // call the super function to manage animation this._super(me.Sprite, "update", [dt] ); // hide the mode after 1/2 sec if (this.isOut===true) { this.timer += dt; if ((this.timer) >= 500) { this.isOut = false; // set default one this.setCurrentAnimation("laugh"); this.hide(); // play laugh FX //me.audio.play("laugh"); // decrease score by 25 pts game.data.score -= 25; if (game.data.score < 0) { game.data.score = 0; } } return true; } } return this.isVisible; }
javascript
function ( dt ) { if (this.isVisible) { // call the super function to manage animation this._super(me.Sprite, "update", [dt] ); // hide the mode after 1/2 sec if (this.isOut===true) { this.timer += dt; if ((this.timer) >= 500) { this.isOut = false; // set default one this.setCurrentAnimation("laugh"); this.hide(); // play laugh FX //me.audio.play("laugh"); // decrease score by 25 pts game.data.score -= 25; if (game.data.score < 0) { game.data.score = 0; } } return true; } } return this.isVisible; }
[ "function", "(", "dt", ")", "{", "if", "(", "this", ".", "isVisible", ")", "{", "// call the super function to manage animation", "this", ".", "_super", "(", "me", ".", "Sprite", ",", "\"update\"", ",", "[", "dt", "]", ")", ";", "// hide the mode after 1/2 sec", "if", "(", "this", ".", "isOut", "===", "true", ")", "{", "this", ".", "timer", "+=", "dt", ";", "if", "(", "(", "this", ".", "timer", ")", ">=", "500", ")", "{", "this", ".", "isOut", "=", "false", ";", "// set default one", "this", ".", "setCurrentAnimation", "(", "\"laugh\"", ")", ";", "this", ".", "hide", "(", ")", ";", "// play laugh FX", "//me.audio.play(\"laugh\");", "// decrease score by 25 pts", "game", ".", "data", ".", "score", "-=", "25", ";", "if", "(", "game", ".", "data", ".", "score", "<", "0", ")", "{", "game", ".", "data", ".", "score", "=", "0", ";", "}", "}", "return", "true", ";", "}", "}", "return", "this", ".", "isVisible", ";", "}" ]
update the mole
[ "update", "the", "mole" ]
6c1823cc245df7c958db243a0531506eb838d72c
https://github.com/melonjs/melonJS/blob/6c1823cc245df7c958db243a0531506eb838d72c/examples/whack-a-mole/js/entities/entities.js#L122-L150
7,401
melonjs/melonJS
src/input/keyboard.js
function (e, keyCode, mouseButton) { keyCode = keyCode || e.keyCode || e.button; var action = keyBindings[keyCode]; // publish a message for keydown event me.event.publish(me.event.KEYDOWN, [ action, keyCode, action ? !keyLocked[action] : true ]); if (action) { if (!keyLocked[action]) { var trigger = (typeof mouseButton !== "undefined") ? mouseButton : keyCode; if (!keyRefs[action][trigger]) { keyStatus[action]++; keyRefs[action][trigger] = true; } } // prevent event propagation if (preventDefaultForKeys[keyCode] && (typeof e.preventDefault === "function")) { // "fake" events generated through triggerKeyEvent do not have a preventDefault fn return e.preventDefault(); } else { return true; } } return true; }
javascript
function (e, keyCode, mouseButton) { keyCode = keyCode || e.keyCode || e.button; var action = keyBindings[keyCode]; // publish a message for keydown event me.event.publish(me.event.KEYDOWN, [ action, keyCode, action ? !keyLocked[action] : true ]); if (action) { if (!keyLocked[action]) { var trigger = (typeof mouseButton !== "undefined") ? mouseButton : keyCode; if (!keyRefs[action][trigger]) { keyStatus[action]++; keyRefs[action][trigger] = true; } } // prevent event propagation if (preventDefaultForKeys[keyCode] && (typeof e.preventDefault === "function")) { // "fake" events generated through triggerKeyEvent do not have a preventDefault fn return e.preventDefault(); } else { return true; } } return true; }
[ "function", "(", "e", ",", "keyCode", ",", "mouseButton", ")", "{", "keyCode", "=", "keyCode", "||", "e", ".", "keyCode", "||", "e", ".", "button", ";", "var", "action", "=", "keyBindings", "[", "keyCode", "]", ";", "// publish a message for keydown event", "me", ".", "event", ".", "publish", "(", "me", ".", "event", ".", "KEYDOWN", ",", "[", "action", ",", "keyCode", ",", "action", "?", "!", "keyLocked", "[", "action", "]", ":", "true", "]", ")", ";", "if", "(", "action", ")", "{", "if", "(", "!", "keyLocked", "[", "action", "]", ")", "{", "var", "trigger", "=", "(", "typeof", "mouseButton", "!==", "\"undefined\"", ")", "?", "mouseButton", ":", "keyCode", ";", "if", "(", "!", "keyRefs", "[", "action", "]", "[", "trigger", "]", ")", "{", "keyStatus", "[", "action", "]", "++", ";", "keyRefs", "[", "action", "]", "[", "trigger", "]", "=", "true", ";", "}", "}", "// prevent event propagation", "if", "(", "preventDefaultForKeys", "[", "keyCode", "]", "&&", "(", "typeof", "e", ".", "preventDefault", "===", "\"function\"", ")", ")", "{", "// \"fake\" events generated through triggerKeyEvent do not have a preventDefault fn", "return", "e", ".", "preventDefault", "(", ")", ";", "}", "else", "{", "return", "true", ";", "}", "}", "return", "true", ";", "}" ]
key down event @ignore
[ "key", "down", "event" ]
6c1823cc245df7c958db243a0531506eb838d72c
https://github.com/melonjs/melonJS/blob/6c1823cc245df7c958db243a0531506eb838d72c/src/input/keyboard.js#L27-L58
7,402
melonjs/melonJS
src/renderable/container.js
function () { // cancel any sort operation if (this.pendingSort) { clearTimeout(this.pendingSort); this.pendingSort = null; } // delete all children for (var i = this.children.length, obj; i >= 0; (obj = this.children[--i])) { // don't remove it if a persistent object if (obj && !obj.isPersistent) { this.removeChildNow(obj); } } if (typeof this.currentTransform !== "undefined") { // just reset some variables this.currentTransform.identity(); } }
javascript
function () { // cancel any sort operation if (this.pendingSort) { clearTimeout(this.pendingSort); this.pendingSort = null; } // delete all children for (var i = this.children.length, obj; i >= 0; (obj = this.children[--i])) { // don't remove it if a persistent object if (obj && !obj.isPersistent) { this.removeChildNow(obj); } } if (typeof this.currentTransform !== "undefined") { // just reset some variables this.currentTransform.identity(); } }
[ "function", "(", ")", "{", "// cancel any sort operation", "if", "(", "this", ".", "pendingSort", ")", "{", "clearTimeout", "(", "this", ".", "pendingSort", ")", ";", "this", ".", "pendingSort", "=", "null", ";", "}", "// delete all children", "for", "(", "var", "i", "=", "this", ".", "children", ".", "length", ",", "obj", ";", "i", ">=", "0", ";", "(", "obj", "=", "this", ".", "children", "[", "--", "i", "]", ")", ")", "{", "// don't remove it if a persistent object", "if", "(", "obj", "&&", "!", "obj", ".", "isPersistent", ")", "{", "this", ".", "removeChildNow", "(", "obj", ")", ";", "}", "}", "if", "(", "typeof", "this", ".", "currentTransform", "!==", "\"undefined\"", ")", "{", "// just reset some variables", "this", ".", "currentTransform", ".", "identity", "(", ")", ";", "}", "}" ]
reset the container, removing all childrens, and reseting transforms. @name reset @memberOf me.Container @function
[ "reset", "the", "container", "removing", "all", "childrens", "and", "reseting", "transforms", "." ]
6c1823cc245df7c958db243a0531506eb838d72c
https://github.com/melonjs/melonJS/blob/6c1823cc245df7c958db243a0531506eb838d72c/src/renderable/container.js#L145-L164
7,403
melonjs/melonJS
src/renderable/container.js
function (a, b) { if (!b.pos || !a.pos) { return (a.pos ? -Infinity : Infinity); } var result = b.pos.z - a.pos.z; return (result ? result : (b.pos.x - a.pos.x)); }
javascript
function (a, b) { if (!b.pos || !a.pos) { return (a.pos ? -Infinity : Infinity); } var result = b.pos.z - a.pos.z; return (result ? result : (b.pos.x - a.pos.x)); }
[ "function", "(", "a", ",", "b", ")", "{", "if", "(", "!", "b", ".", "pos", "||", "!", "a", ".", "pos", ")", "{", "return", "(", "a", ".", "pos", "?", "-", "Infinity", ":", "Infinity", ")", ";", "}", "var", "result", "=", "b", ".", "pos", ".", "z", "-", "a", ".", "pos", ".", "z", ";", "return", "(", "result", "?", "result", ":", "(", "b", ".", "pos", ".", "x", "-", "a", ".", "pos", ".", "x", ")", ")", ";", "}" ]
X Sorting function @ignore
[ "X", "Sorting", "function" ]
6c1823cc245df7c958db243a0531506eb838d72c
https://github.com/melonjs/melonJS/blob/6c1823cc245df7c958db243a0531506eb838d72c/src/renderable/container.js#L773-L779
7,404
melonjs/melonJS
src/renderable/container.js
function (a, b) { if (!b.pos || !a.pos) { return (a.pos ? -Infinity : Infinity); } var result = b.pos.z - a.pos.z; return (result ? result : (b.pos.y - a.pos.y)); }
javascript
function (a, b) { if (!b.pos || !a.pos) { return (a.pos ? -Infinity : Infinity); } var result = b.pos.z - a.pos.z; return (result ? result : (b.pos.y - a.pos.y)); }
[ "function", "(", "a", ",", "b", ")", "{", "if", "(", "!", "b", ".", "pos", "||", "!", "a", ".", "pos", ")", "{", "return", "(", "a", ".", "pos", "?", "-", "Infinity", ":", "Infinity", ")", ";", "}", "var", "result", "=", "b", ".", "pos", ".", "z", "-", "a", ".", "pos", ".", "z", ";", "return", "(", "result", "?", "result", ":", "(", "b", ".", "pos", ".", "y", "-", "a", ".", "pos", ".", "y", ")", ")", ";", "}" ]
Y Sorting function @ignore
[ "Y", "Sorting", "function" ]
6c1823cc245df7c958db243a0531506eb838d72c
https://github.com/melonjs/melonJS/blob/6c1823cc245df7c958db243a0531506eb838d72c/src/renderable/container.js#L785-L791
7,405
melonjs/melonJS
src/renderable/imagelayer.js
function (renderer) { var viewport = me.game.viewport, width = this.imagewidth, height = this.imageheight, bw = viewport.bounds.width, bh = viewport.bounds.height, ax = this.anchorPoint.x, ay = this.anchorPoint.y, x = this.pos.x, y = this.pos.y; if (this.ratio.x === this.ratio.y === 0) { x = x + ax * (bw - width); y = y + ay * (bh - height); } renderer.translate(x, y); renderer.drawPattern( this._pattern, 0, 0, viewport.width * 2, viewport.height * 2 ); }
javascript
function (renderer) { var viewport = me.game.viewport, width = this.imagewidth, height = this.imageheight, bw = viewport.bounds.width, bh = viewport.bounds.height, ax = this.anchorPoint.x, ay = this.anchorPoint.y, x = this.pos.x, y = this.pos.y; if (this.ratio.x === this.ratio.y === 0) { x = x + ax * (bw - width); y = y + ay * (bh - height); } renderer.translate(x, y); renderer.drawPattern( this._pattern, 0, 0, viewport.width * 2, viewport.height * 2 ); }
[ "function", "(", "renderer", ")", "{", "var", "viewport", "=", "me", ".", "game", ".", "viewport", ",", "width", "=", "this", ".", "imagewidth", ",", "height", "=", "this", ".", "imageheight", ",", "bw", "=", "viewport", ".", "bounds", ".", "width", ",", "bh", "=", "viewport", ".", "bounds", ".", "height", ",", "ax", "=", "this", ".", "anchorPoint", ".", "x", ",", "ay", "=", "this", ".", "anchorPoint", ".", "y", ",", "x", "=", "this", ".", "pos", ".", "x", ",", "y", "=", "this", ".", "pos", ".", "y", ";", "if", "(", "this", ".", "ratio", ".", "x", "===", "this", ".", "ratio", ".", "y", "===", "0", ")", "{", "x", "=", "x", "+", "ax", "*", "(", "bw", "-", "width", ")", ";", "y", "=", "y", "+", "ay", "*", "(", "bh", "-", "height", ")", ";", "}", "renderer", ".", "translate", "(", "x", ",", "y", ")", ";", "renderer", ".", "drawPattern", "(", "this", ".", "_pattern", ",", "0", ",", "0", ",", "viewport", ".", "width", "*", "2", ",", "viewport", ".", "height", "*", "2", ")", ";", "}" ]
draw the image layer @ignore
[ "draw", "the", "image", "layer" ]
6c1823cc245df7c958db243a0531506eb838d72c
https://github.com/melonjs/melonJS/blob/6c1823cc245df7c958db243a0531506eb838d72c/src/renderable/imagelayer.js#L275-L299
7,406
melonjs/melonJS
examples/drag-and-drop/js/entities/entities.js
function (e) { // save a reference to this to use in the timeout var self = this; // call the super function this._super(me.DroptargetEntity, "draw", [e]); // indicate a succesful drop this.color = "green"; // set the color back to red after a second window.setTimeout(function () { self.color = "red"; }, 1000); }
javascript
function (e) { // save a reference to this to use in the timeout var self = this; // call the super function this._super(me.DroptargetEntity, "draw", [e]); // indicate a succesful drop this.color = "green"; // set the color back to red after a second window.setTimeout(function () { self.color = "red"; }, 1000); }
[ "function", "(", "e", ")", "{", "// save a reference to this to use in the timeout", "var", "self", "=", "this", ";", "// call the super function", "this", ".", "_super", "(", "me", ".", "DroptargetEntity", ",", "\"draw\"", ",", "[", "e", "]", ")", ";", "// indicate a succesful drop", "this", ".", "color", "=", "\"green\"", ";", "// set the color back to red after a second", "window", ".", "setTimeout", "(", "function", "(", ")", "{", "self", ".", "color", "=", "\"red\"", ";", "}", ",", "1000", ")", ";", "}" ]
drop overwrite function
[ "drop", "overwrite", "function" ]
6c1823cc245df7c958db243a0531506eb838d72c
https://github.com/melonjs/melonJS/blob/6c1823cc245df7c958db243a0531506eb838d72c/examples/drag-and-drop/js/entities/entities.js#L79-L90
7,407
serverless-heaven/serverless-webpack
lib/packExternalModules.js
addModulesToPackageJson
function addModulesToPackageJson(externalModules, packageJson, pathToPackageRoot) { _.forEach(externalModules, externalModule => { const splitModule = _.split(externalModule, '@'); // If we have a scoped module we have to re-add the @ if (_.startsWith(externalModule, '@')) { splitModule.splice(0, 1); splitModule[0] = '@' + splitModule[0]; } let moduleVersion = _.join(_.tail(splitModule), '@'); // We have to rebase file references to the target package.json moduleVersion = rebaseFileReferences(pathToPackageRoot, moduleVersion); packageJson.dependencies = packageJson.dependencies || {}; packageJson.dependencies[_.first(splitModule)] = moduleVersion; }); }
javascript
function addModulesToPackageJson(externalModules, packageJson, pathToPackageRoot) { _.forEach(externalModules, externalModule => { const splitModule = _.split(externalModule, '@'); // If we have a scoped module we have to re-add the @ if (_.startsWith(externalModule, '@')) { splitModule.splice(0, 1); splitModule[0] = '@' + splitModule[0]; } let moduleVersion = _.join(_.tail(splitModule), '@'); // We have to rebase file references to the target package.json moduleVersion = rebaseFileReferences(pathToPackageRoot, moduleVersion); packageJson.dependencies = packageJson.dependencies || {}; packageJson.dependencies[_.first(splitModule)] = moduleVersion; }); }
[ "function", "addModulesToPackageJson", "(", "externalModules", ",", "packageJson", ",", "pathToPackageRoot", ")", "{", "_", ".", "forEach", "(", "externalModules", ",", "externalModule", "=>", "{", "const", "splitModule", "=", "_", ".", "split", "(", "externalModule", ",", "'@'", ")", ";", "// If we have a scoped module we have to re-add the @", "if", "(", "_", ".", "startsWith", "(", "externalModule", ",", "'@'", ")", ")", "{", "splitModule", ".", "splice", "(", "0", ",", "1", ")", ";", "splitModule", "[", "0", "]", "=", "'@'", "+", "splitModule", "[", "0", "]", ";", "}", "let", "moduleVersion", "=", "_", ".", "join", "(", "_", ".", "tail", "(", "splitModule", ")", ",", "'@'", ")", ";", "// We have to rebase file references to the target package.json", "moduleVersion", "=", "rebaseFileReferences", "(", "pathToPackageRoot", ",", "moduleVersion", ")", ";", "packageJson", ".", "dependencies", "=", "packageJson", ".", "dependencies", "||", "{", "}", ";", "packageJson", ".", "dependencies", "[", "_", ".", "first", "(", "splitModule", ")", "]", "=", "moduleVersion", ";", "}", ")", ";", "}" ]
Add the given modules to a package json's dependencies.
[ "Add", "the", "given", "modules", "to", "a", "package", "json", "s", "dependencies", "." ]
fc2cffdce9f9a74a5e04f6ac527ed4fbb7b69699
https://github.com/serverless-heaven/serverless-webpack/blob/fc2cffdce9f9a74a5e04f6ac527ed4fbb7b69699/lib/packExternalModules.js#L23-L37
7,408
serverless-heaven/serverless-webpack
lib/packExternalModules.js
removeExcludedModules
function removeExcludedModules(modules, packageForceExcludes, log) { const excludedModules = _.remove(modules, externalModule => { // eslint-disable-line lodash/prefer-immutable-method const splitModule = _.split(externalModule, '@'); // If we have a scoped module we have to re-add the @ if (_.startsWith(externalModule, '@')) { splitModule.splice(0, 1); splitModule[0] = '@' + splitModule[0]; } const moduleName = _.first(splitModule); return _.includes(packageForceExcludes, moduleName); }); if (log && !_.isEmpty(excludedModules)) { this.serverless.cli.log(`Excluding external modules: ${_.join(excludedModules, ', ')}`); } }
javascript
function removeExcludedModules(modules, packageForceExcludes, log) { const excludedModules = _.remove(modules, externalModule => { // eslint-disable-line lodash/prefer-immutable-method const splitModule = _.split(externalModule, '@'); // If we have a scoped module we have to re-add the @ if (_.startsWith(externalModule, '@')) { splitModule.splice(0, 1); splitModule[0] = '@' + splitModule[0]; } const moduleName = _.first(splitModule); return _.includes(packageForceExcludes, moduleName); }); if (log && !_.isEmpty(excludedModules)) { this.serverless.cli.log(`Excluding external modules: ${_.join(excludedModules, ', ')}`); } }
[ "function", "removeExcludedModules", "(", "modules", ",", "packageForceExcludes", ",", "log", ")", "{", "const", "excludedModules", "=", "_", ".", "remove", "(", "modules", ",", "externalModule", "=>", "{", "// eslint-disable-line lodash/prefer-immutable-method", "const", "splitModule", "=", "_", ".", "split", "(", "externalModule", ",", "'@'", ")", ";", "// If we have a scoped module we have to re-add the @", "if", "(", "_", ".", "startsWith", "(", "externalModule", ",", "'@'", ")", ")", "{", "splitModule", ".", "splice", "(", "0", ",", "1", ")", ";", "splitModule", "[", "0", "]", "=", "'@'", "+", "splitModule", "[", "0", "]", ";", "}", "const", "moduleName", "=", "_", ".", "first", "(", "splitModule", ")", ";", "return", "_", ".", "includes", "(", "packageForceExcludes", ",", "moduleName", ")", ";", "}", ")", ";", "if", "(", "log", "&&", "!", "_", ".", "isEmpty", "(", "excludedModules", ")", ")", "{", "this", ".", "serverless", ".", "cli", ".", "log", "(", "`", "${", "_", ".", "join", "(", "excludedModules", ",", "', '", ")", "}", "`", ")", ";", "}", "}" ]
Remove a given list of excluded modules from a module list @this - The active plugin instance
[ "Remove", "a", "given", "list", "of", "excluded", "modules", "from", "a", "module", "list" ]
fc2cffdce9f9a74a5e04f6ac527ed4fbb7b69699
https://github.com/serverless-heaven/serverless-webpack/blob/fc2cffdce9f9a74a5e04f6ac527ed4fbb7b69699/lib/packExternalModules.js#L43-L58
7,409
serverless-heaven/serverless-webpack
lib/packExternalModules.js
getProdModules
function getProdModules(externalModules, packagePath, dependencyGraph, forceExcludes) { const packageJsonPath = path.join(process.cwd(), packagePath); const packageJson = require(packageJsonPath); const prodModules = []; // only process the module stated in dependencies section if (!packageJson.dependencies) { return []; } // Get versions of all transient modules _.forEach(externalModules, module => { let moduleVersion = packageJson.dependencies[module.external]; if (moduleVersion) { prodModules.push(`${module.external}@${moduleVersion}`); // Check if the module has any peer dependencies and include them too try { const modulePackagePath = path.join( path.dirname(path.join(process.cwd(), packagePath)), 'node_modules', module.external, 'package.json' ); const peerDependencies = require(modulePackagePath).peerDependencies; if (!_.isEmpty(peerDependencies)) { this.options.verbose && this.serverless.cli.log(`Adding explicit peers for dependency ${module.external}`); const peerModules = getProdModules.call(this, _.map(peerDependencies, (value, key) => ({ external: key })), packagePath, dependencyGraph, forceExcludes); Array.prototype.push.apply(prodModules, peerModules); } } catch (e) { this.serverless.cli.log(`WARNING: Could not check for peer dependencies of ${module.external}`); } } else { if (!packageJson.devDependencies || !packageJson.devDependencies[module.external]) { // Add transient dependencies if they appear not in the service's dev dependencies const originInfo = _.get(dependencyGraph, 'dependencies', {})[module.origin] || {}; moduleVersion = _.get(_.get(originInfo, 'dependencies', {})[module.external], 'version'); if (!moduleVersion) { this.serverless.cli.log(`WARNING: Could not determine version of module ${module.external}`); } prodModules.push(moduleVersion ? `${module.external}@${moduleVersion}` : module.external); } else if (packageJson.devDependencies && packageJson.devDependencies[module.external] && !_.includes(forceExcludes, module.external)) { // To minimize the chance of breaking setups we whitelist packages available on AWS here. These are due to the previously missing check // most likely set in devDependencies and should not lead to an error now. const ignoredDevDependencies = ['aws-sdk']; if (!_.includes(ignoredDevDependencies, module.external)) { // Runtime dependency found in devDependencies but not forcefully excluded this.serverless.cli.log(`ERROR: Runtime dependency '${module.external}' found in devDependencies. Move it to dependencies or use forceExclude to explicitly exclude it.`); throw new this.serverless.classes.Error(`Serverless-webpack dependency error: ${module.external}.`); } this.options.verbose && this.serverless.cli.log(`INFO: Runtime dependency '${module.external}' found in devDependencies. It has been excluded automatically.`); } } }); return prodModules; }
javascript
function getProdModules(externalModules, packagePath, dependencyGraph, forceExcludes) { const packageJsonPath = path.join(process.cwd(), packagePath); const packageJson = require(packageJsonPath); const prodModules = []; // only process the module stated in dependencies section if (!packageJson.dependencies) { return []; } // Get versions of all transient modules _.forEach(externalModules, module => { let moduleVersion = packageJson.dependencies[module.external]; if (moduleVersion) { prodModules.push(`${module.external}@${moduleVersion}`); // Check if the module has any peer dependencies and include them too try { const modulePackagePath = path.join( path.dirname(path.join(process.cwd(), packagePath)), 'node_modules', module.external, 'package.json' ); const peerDependencies = require(modulePackagePath).peerDependencies; if (!_.isEmpty(peerDependencies)) { this.options.verbose && this.serverless.cli.log(`Adding explicit peers for dependency ${module.external}`); const peerModules = getProdModules.call(this, _.map(peerDependencies, (value, key) => ({ external: key })), packagePath, dependencyGraph, forceExcludes); Array.prototype.push.apply(prodModules, peerModules); } } catch (e) { this.serverless.cli.log(`WARNING: Could not check for peer dependencies of ${module.external}`); } } else { if (!packageJson.devDependencies || !packageJson.devDependencies[module.external]) { // Add transient dependencies if they appear not in the service's dev dependencies const originInfo = _.get(dependencyGraph, 'dependencies', {})[module.origin] || {}; moduleVersion = _.get(_.get(originInfo, 'dependencies', {})[module.external], 'version'); if (!moduleVersion) { this.serverless.cli.log(`WARNING: Could not determine version of module ${module.external}`); } prodModules.push(moduleVersion ? `${module.external}@${moduleVersion}` : module.external); } else if (packageJson.devDependencies && packageJson.devDependencies[module.external] && !_.includes(forceExcludes, module.external)) { // To minimize the chance of breaking setups we whitelist packages available on AWS here. These are due to the previously missing check // most likely set in devDependencies and should not lead to an error now. const ignoredDevDependencies = ['aws-sdk']; if (!_.includes(ignoredDevDependencies, module.external)) { // Runtime dependency found in devDependencies but not forcefully excluded this.serverless.cli.log(`ERROR: Runtime dependency '${module.external}' found in devDependencies. Move it to dependencies or use forceExclude to explicitly exclude it.`); throw new this.serverless.classes.Error(`Serverless-webpack dependency error: ${module.external}.`); } this.options.verbose && this.serverless.cli.log(`INFO: Runtime dependency '${module.external}' found in devDependencies. It has been excluded automatically.`); } } }); return prodModules; }
[ "function", "getProdModules", "(", "externalModules", ",", "packagePath", ",", "dependencyGraph", ",", "forceExcludes", ")", "{", "const", "packageJsonPath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "packagePath", ")", ";", "const", "packageJson", "=", "require", "(", "packageJsonPath", ")", ";", "const", "prodModules", "=", "[", "]", ";", "// only process the module stated in dependencies section", "if", "(", "!", "packageJson", ".", "dependencies", ")", "{", "return", "[", "]", ";", "}", "// Get versions of all transient modules", "_", ".", "forEach", "(", "externalModules", ",", "module", "=>", "{", "let", "moduleVersion", "=", "packageJson", ".", "dependencies", "[", "module", ".", "external", "]", ";", "if", "(", "moduleVersion", ")", "{", "prodModules", ".", "push", "(", "`", "${", "module", ".", "external", "}", "${", "moduleVersion", "}", "`", ")", ";", "// Check if the module has any peer dependencies and include them too", "try", "{", "const", "modulePackagePath", "=", "path", ".", "join", "(", "path", ".", "dirname", "(", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "packagePath", ")", ")", ",", "'node_modules'", ",", "module", ".", "external", ",", "'package.json'", ")", ";", "const", "peerDependencies", "=", "require", "(", "modulePackagePath", ")", ".", "peerDependencies", ";", "if", "(", "!", "_", ".", "isEmpty", "(", "peerDependencies", ")", ")", "{", "this", ".", "options", ".", "verbose", "&&", "this", ".", "serverless", ".", "cli", ".", "log", "(", "`", "${", "module", ".", "external", "}", "`", ")", ";", "const", "peerModules", "=", "getProdModules", ".", "call", "(", "this", ",", "_", ".", "map", "(", "peerDependencies", ",", "(", "value", ",", "key", ")", "=>", "(", "{", "external", ":", "key", "}", ")", ")", ",", "packagePath", ",", "dependencyGraph", ",", "forceExcludes", ")", ";", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "prodModules", ",", "peerModules", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "this", ".", "serverless", ".", "cli", ".", "log", "(", "`", "${", "module", ".", "external", "}", "`", ")", ";", "}", "}", "else", "{", "if", "(", "!", "packageJson", ".", "devDependencies", "||", "!", "packageJson", ".", "devDependencies", "[", "module", ".", "external", "]", ")", "{", "// Add transient dependencies if they appear not in the service's dev dependencies", "const", "originInfo", "=", "_", ".", "get", "(", "dependencyGraph", ",", "'dependencies'", ",", "{", "}", ")", "[", "module", ".", "origin", "]", "||", "{", "}", ";", "moduleVersion", "=", "_", ".", "get", "(", "_", ".", "get", "(", "originInfo", ",", "'dependencies'", ",", "{", "}", ")", "[", "module", ".", "external", "]", ",", "'version'", ")", ";", "if", "(", "!", "moduleVersion", ")", "{", "this", ".", "serverless", ".", "cli", ".", "log", "(", "`", "${", "module", ".", "external", "}", "`", ")", ";", "}", "prodModules", ".", "push", "(", "moduleVersion", "?", "`", "${", "module", ".", "external", "}", "${", "moduleVersion", "}", "`", ":", "module", ".", "external", ")", ";", "}", "else", "if", "(", "packageJson", ".", "devDependencies", "&&", "packageJson", ".", "devDependencies", "[", "module", ".", "external", "]", "&&", "!", "_", ".", "includes", "(", "forceExcludes", ",", "module", ".", "external", ")", ")", "{", "// To minimize the chance of breaking setups we whitelist packages available on AWS here. These are due to the previously missing check", "// most likely set in devDependencies and should not lead to an error now.", "const", "ignoredDevDependencies", "=", "[", "'aws-sdk'", "]", ";", "if", "(", "!", "_", ".", "includes", "(", "ignoredDevDependencies", ",", "module", ".", "external", ")", ")", "{", "// Runtime dependency found in devDependencies but not forcefully excluded", "this", ".", "serverless", ".", "cli", ".", "log", "(", "`", "${", "module", ".", "external", "}", "`", ")", ";", "throw", "new", "this", ".", "serverless", ".", "classes", ".", "Error", "(", "`", "${", "module", ".", "external", "}", "`", ")", ";", "}", "this", ".", "options", ".", "verbose", "&&", "this", ".", "serverless", ".", "cli", ".", "log", "(", "`", "${", "module", ".", "external", "}", "`", ")", ";", "}", "}", "}", ")", ";", "return", "prodModules", ";", "}" ]
Resolve the needed versions of production dependencies for external modules. @this - The active plugin instance
[ "Resolve", "the", "needed", "versions", "of", "production", "dependencies", "for", "external", "modules", "." ]
fc2cffdce9f9a74a5e04f6ac527ed4fbb7b69699
https://github.com/serverless-heaven/serverless-webpack/blob/fc2cffdce9f9a74a5e04f6ac527ed4fbb7b69699/lib/packExternalModules.js#L64-L124
7,410
serverless-heaven/serverless-webpack
lib/packExternalModules.js
findExternalOrigin
function findExternalOrigin(issuer) { if (!_.isNil(issuer) && _.startsWith(issuer.rawRequest, './')) { return findExternalOrigin(issuer.issuer); } return issuer; }
javascript
function findExternalOrigin(issuer) { if (!_.isNil(issuer) && _.startsWith(issuer.rawRequest, './')) { return findExternalOrigin(issuer.issuer); } return issuer; }
[ "function", "findExternalOrigin", "(", "issuer", ")", "{", "if", "(", "!", "_", ".", "isNil", "(", "issuer", ")", "&&", "_", ".", "startsWith", "(", "issuer", ".", "rawRequest", ",", "'./'", ")", ")", "{", "return", "findExternalOrigin", "(", "issuer", ".", "issuer", ")", ";", "}", "return", "issuer", ";", "}" ]
Find the original module that required the transient dependency. Returns undefined if the module is a first level dependency. @param {Object} issuer - Module issuer
[ "Find", "the", "original", "module", "that", "required", "the", "transient", "dependency", ".", "Returns", "undefined", "if", "the", "module", "is", "a", "first", "level", "dependency", "." ]
fc2cffdce9f9a74a5e04f6ac527ed4fbb7b69699
https://github.com/serverless-heaven/serverless-webpack/blob/fc2cffdce9f9a74a5e04f6ac527ed4fbb7b69699/lib/packExternalModules.js#L148-L153
7,411
serverless-heaven/serverless-webpack
lib/utils.js
purgeCache
function purgeCache(moduleName) { return searchAndProcessCache(moduleName, function (mod) { delete require.cache[mod.id]; }) .then(() => { _.forEach(_.keys(module.constructor._pathCache), function(cacheKey) { if (cacheKey.indexOf(moduleName)>0) { delete module.constructor._pathCache[cacheKey]; } }); return BbPromise.resolve(); }); }
javascript
function purgeCache(moduleName) { return searchAndProcessCache(moduleName, function (mod) { delete require.cache[mod.id]; }) .then(() => { _.forEach(_.keys(module.constructor._pathCache), function(cacheKey) { if (cacheKey.indexOf(moduleName)>0) { delete module.constructor._pathCache[cacheKey]; } }); return BbPromise.resolve(); }); }
[ "function", "purgeCache", "(", "moduleName", ")", "{", "return", "searchAndProcessCache", "(", "moduleName", ",", "function", "(", "mod", ")", "{", "delete", "require", ".", "cache", "[", "mod", ".", "id", "]", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "_", ".", "forEach", "(", "_", ".", "keys", "(", "module", ".", "constructor", ".", "_pathCache", ")", ",", "function", "(", "cacheKey", ")", "{", "if", "(", "cacheKey", ".", "indexOf", "(", "moduleName", ")", ">", "0", ")", "{", "delete", "module", ".", "constructor", ".", "_pathCache", "[", "cacheKey", "]", ";", "}", "}", ")", ";", "return", "BbPromise", ".", "resolve", "(", ")", ";", "}", ")", ";", "}" ]
Remove the specified module from the require cache. @param {string} moduleName
[ "Remove", "the", "specified", "module", "from", "the", "require", "cache", "." ]
fc2cffdce9f9a74a5e04f6ac527ed4fbb7b69699
https://github.com/serverless-heaven/serverless-webpack/blob/fc2cffdce9f9a74a5e04f6ac527ed4fbb7b69699/lib/utils.js#L20-L32
7,412
SAP/fundamental
docs/js/customscripts.js
getBlock
function getBlock(control) { var block = control.parentNode; while (block.getAttribute("role") !== "tablist") { block = block.parentNode; } return block; }
javascript
function getBlock(control) { var block = control.parentNode; while (block.getAttribute("role") !== "tablist") { block = block.parentNode; } return block; }
[ "function", "getBlock", "(", "control", ")", "{", "var", "block", "=", "control", ".", "parentNode", ";", "while", "(", "block", ".", "getAttribute", "(", "\"role\"", ")", "!==", "\"tablist\"", ")", "{", "block", "=", "block", ".", "parentNode", ";", "}", "return", "block", ";", "}" ]
climb up DOM to get block element
[ "climb", "up", "DOM", "to", "get", "block", "element" ]
1b10ee982d42b7bcd95d6bb4249ebe026afd9a68
https://github.com/SAP/fundamental/blob/1b10ee982d42b7bcd95d6bb4249ebe026afd9a68/docs/js/customscripts.js#L99-L105
7,413
SAP/fundamental
docs/js/jquery.shuffle.min.js
dashify
function dashify( prop ) { if (!prop) { return ''; } // Replace upper case with dash-lowercase, // then fix ms- prefixes because they're not capitalized. return prop.replace(/([A-Z])/g, function( str, m1 ) { return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-'); }
javascript
function dashify( prop ) { if (!prop) { return ''; } // Replace upper case with dash-lowercase, // then fix ms- prefixes because they're not capitalized. return prop.replace(/([A-Z])/g, function( str, m1 ) { return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-'); }
[ "function", "dashify", "(", "prop", ")", "{", "if", "(", "!", "prop", ")", "{", "return", "''", ";", "}", "// Replace upper case with dash-lowercase,", "// then fix ms- prefixes because they're not capitalized.", "return", "prop", ".", "replace", "(", "/", "([A-Z])", "/", "g", ",", "function", "(", "str", ",", "m1", ")", "{", "return", "'-'", "+", "m1", ".", "toLowerCase", "(", ")", ";", "}", ")", ".", "replace", "(", "/", "^ms-", "/", ",", "'-ms-'", ")", ";", "}" ]
Returns css prefixed properties like `-webkit-transition` or `box-sizing` from `transition` or `boxSizing`, respectively. @param {(string|boolean)} prop Property to be prefixed. @return {string} The prefixed css property.
[ "Returns", "css", "prefixed", "properties", "like", "-", "webkit", "-", "transition", "or", "box", "-", "sizing", "from", "transition", "or", "boxSizing", "respectively", "." ]
1b10ee982d42b7bcd95d6bb4249ebe026afd9a68
https://github.com/SAP/fundamental/blob/1b10ee982d42b7bcd95d6bb4249ebe026afd9a68/docs/js/jquery.shuffle.min.js#L40-L50
7,414
SAP/fundamental
docs/js/jquery.shuffle.min.js
function( element, options ) { options = options || {}; $.extend( this, Shuffle.options, options, Shuffle.settings ); this.$el = $(element); this.element = element; this.unique = 'shuffle_' + id++; this._fire( Shuffle.EventType.LOADING ); this._init(); // Dispatch the done event asynchronously so that people can bind to it after // Shuffle has been initialized. defer(function() { this.initialized = true; this._fire( Shuffle.EventType.DONE ); }, this, 16); }
javascript
function( element, options ) { options = options || {}; $.extend( this, Shuffle.options, options, Shuffle.settings ); this.$el = $(element); this.element = element; this.unique = 'shuffle_' + id++; this._fire( Shuffle.EventType.LOADING ); this._init(); // Dispatch the done event asynchronously so that people can bind to it after // Shuffle has been initialized. defer(function() { this.initialized = true; this._fire( Shuffle.EventType.DONE ); }, this, 16); }
[ "function", "(", "element", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "$", ".", "extend", "(", "this", ",", "Shuffle", ".", "options", ",", "options", ",", "Shuffle", ".", "settings", ")", ";", "this", ".", "$el", "=", "$", "(", "element", ")", ";", "this", ".", "element", "=", "element", ";", "this", ".", "unique", "=", "'shuffle_'", "+", "id", "++", ";", "this", ".", "_fire", "(", "Shuffle", ".", "EventType", ".", "LOADING", ")", ";", "this", ".", "_init", "(", ")", ";", "// Dispatch the done event asynchronously so that people can bind to it after", "// Shuffle has been initialized.", "defer", "(", "function", "(", ")", "{", "this", ".", "initialized", "=", "true", ";", "this", ".", "_fire", "(", "Shuffle", ".", "EventType", ".", "DONE", ")", ";", "}", ",", "this", ",", "16", ")", ";", "}" ]
Categorize, sort, and filter a responsive grid of items. @param {Element} element An element which is the parent container for the grid items. @param {Object} [options=Shuffle.options] Options object. @constructor
[ "Categorize", "sort", "and", "filter", "a", "responsive", "grid", "of", "items", "." ]
1b10ee982d42b7bcd95d6bb4249ebe026afd9a68
https://github.com/SAP/fundamental/blob/1b10ee982d42b7bcd95d6bb4249ebe026afd9a68/docs/js/jquery.shuffle.min.js#L181-L198
7,415
SAP/fundamental
docs/js/jquery.shuffle.min.js
handleTransitionEnd
function handleTransitionEnd( evt ) { // Make sure this event handler has not bubbled up from a child. if ( evt.target === evt.currentTarget ) { $( evt.target ).off( TRANSITIONEND, handleTransitionEnd ); callback(); } }
javascript
function handleTransitionEnd( evt ) { // Make sure this event handler has not bubbled up from a child. if ( evt.target === evt.currentTarget ) { $( evt.target ).off( TRANSITIONEND, handleTransitionEnd ); callback(); } }
[ "function", "handleTransitionEnd", "(", "evt", ")", "{", "// Make sure this event handler has not bubbled up from a child.", "if", "(", "evt", ".", "target", "===", "evt", ".", "currentTarget", ")", "{", "$", "(", "evt", ".", "target", ")", ".", "off", "(", "TRANSITIONEND", ",", "handleTransitionEnd", ")", ";", "callback", "(", ")", ";", "}", "}" ]
Transition end handler removes its listener.
[ "Transition", "end", "handler", "removes", "its", "listener", "." ]
1b10ee982d42b7bcd95d6bb4249ebe026afd9a68
https://github.com/SAP/fundamental/blob/1b10ee982d42b7bcd95d6bb4249ebe026afd9a68/docs/js/jquery.shuffle.min.js#L1090-L1096
7,416
Leaflet/Leaflet.markercluster
src/MarkerClusterGroup.Refresh.js
function (layers) { var id, parent; // Assumes layers is an Array or an Object whose prototype is non-enumerable. for (id in layers) { // Flag parent clusters' icon as "dirty", all the way up. // Dumb process that flags multiple times upper parents, but still // much more efficient than trying to be smart and make short lists, // at least in the case of a hierarchy following a power law: // http://jsperf.com/flag-nodes-in-power-hierarchy/2 parent = layers[id].__parent; while (parent) { parent._iconNeedsUpdate = true; parent = parent.__parent; } } }
javascript
function (layers) { var id, parent; // Assumes layers is an Array or an Object whose prototype is non-enumerable. for (id in layers) { // Flag parent clusters' icon as "dirty", all the way up. // Dumb process that flags multiple times upper parents, but still // much more efficient than trying to be smart and make short lists, // at least in the case of a hierarchy following a power law: // http://jsperf.com/flag-nodes-in-power-hierarchy/2 parent = layers[id].__parent; while (parent) { parent._iconNeedsUpdate = true; parent = parent.__parent; } } }
[ "function", "(", "layers", ")", "{", "var", "id", ",", "parent", ";", "// Assumes layers is an Array or an Object whose prototype is non-enumerable.", "for", "(", "id", "in", "layers", ")", "{", "// Flag parent clusters' icon as \"dirty\", all the way up.", "// Dumb process that flags multiple times upper parents, but still", "// much more efficient than trying to be smart and make short lists,", "// at least in the case of a hierarchy following a power law:", "// http://jsperf.com/flag-nodes-in-power-hierarchy/2", "parent", "=", "layers", "[", "id", "]", ".", "__parent", ";", "while", "(", "parent", ")", "{", "parent", ".", "_iconNeedsUpdate", "=", "true", ";", "parent", "=", "parent", ".", "__parent", ";", "}", "}", "}" ]
Simply flags all parent clusters of the given markers as having a "dirty" icon. @param layers Array(L.Marker)|Map(L.Marker) list of markers. @private
[ "Simply", "flags", "all", "parent", "clusters", "of", "the", "given", "markers", "as", "having", "a", "dirty", "icon", "." ]
93bf5408ad84b74ea42f55ccb6ca0450daa41427
https://github.com/Leaflet/Leaflet.markercluster/blob/93bf5408ad84b74ea42f55ccb6ca0450daa41427/src/MarkerClusterGroup.Refresh.js#L46-L62
7,417
Leaflet/Leaflet.markercluster
src/MarkerClusterGroup.Refresh.js
function (layers) { var id, layer; for (id in layers) { layer = layers[id]; // Make sure we do not override markers that do not belong to THIS group. if (this.hasLayer(layer)) { // Need to re-create the icon first, then re-draw the marker. layer.setIcon(this._overrideMarkerIcon(layer)); } } }
javascript
function (layers) { var id, layer; for (id in layers) { layer = layers[id]; // Make sure we do not override markers that do not belong to THIS group. if (this.hasLayer(layer)) { // Need to re-create the icon first, then re-draw the marker. layer.setIcon(this._overrideMarkerIcon(layer)); } } }
[ "function", "(", "layers", ")", "{", "var", "id", ",", "layer", ";", "for", "(", "id", "in", "layers", ")", "{", "layer", "=", "layers", "[", "id", "]", ";", "// Make sure we do not override markers that do not belong to THIS group.", "if", "(", "this", ".", "hasLayer", "(", "layer", ")", ")", "{", "// Need to re-create the icon first, then re-draw the marker.", "layer", ".", "setIcon", "(", "this", ".", "_overrideMarkerIcon", "(", "layer", ")", ")", ";", "}", "}", "}" ]
Re-draws the icon of the supplied markers. To be used in singleMarkerMode only. @param layers Array(L.Marker)|Map(L.Marker) list of markers. @private
[ "Re", "-", "draws", "the", "icon", "of", "the", "supplied", "markers", ".", "To", "be", "used", "in", "singleMarkerMode", "only", "." ]
93bf5408ad84b74ea42f55ccb6ca0450daa41427
https://github.com/Leaflet/Leaflet.markercluster/blob/93bf5408ad84b74ea42f55ccb6ca0450daa41427/src/MarkerClusterGroup.Refresh.js#L70-L82
7,418
Leaflet/Leaflet.markercluster
src/MarkerClusterGroup.Refresh.js
function (options, directlyRefreshClusters) { var icon = this.options.icon; L.setOptions(icon, options); this.setIcon(icon); // Shortcut to refresh the associated MCG clusters right away. // To be used when refreshing a single marker. // Otherwise, better use MCG.refreshClusters() once at the end with // the list of modified markers. if (directlyRefreshClusters && this.__parent) { this.__parent._group.refreshClusters(this); } return this; }
javascript
function (options, directlyRefreshClusters) { var icon = this.options.icon; L.setOptions(icon, options); this.setIcon(icon); // Shortcut to refresh the associated MCG clusters right away. // To be used when refreshing a single marker. // Otherwise, better use MCG.refreshClusters() once at the end with // the list of modified markers. if (directlyRefreshClusters && this.__parent) { this.__parent._group.refreshClusters(this); } return this; }
[ "function", "(", "options", ",", "directlyRefreshClusters", ")", "{", "var", "icon", "=", "this", ".", "options", ".", "icon", ";", "L", ".", "setOptions", "(", "icon", ",", "options", ")", ";", "this", ".", "setIcon", "(", "icon", ")", ";", "// Shortcut to refresh the associated MCG clusters right away.", "// To be used when refreshing a single marker.", "// Otherwise, better use MCG.refreshClusters() once at the end with", "// the list of modified markers.", "if", "(", "directlyRefreshClusters", "&&", "this", ".", "__parent", ")", "{", "this", ".", "__parent", ".", "_group", ".", "refreshClusters", "(", "this", ")", ";", "}", "return", "this", ";", "}" ]
Updates the given options in the marker's icon and refreshes the marker. @param options map object of icon options. @param directlyRefreshClusters boolean (optional) true to trigger MCG.refreshClustersOf() right away with this single marker. @returns {L.Marker}
[ "Updates", "the", "given", "options", "in", "the", "marker", "s", "icon", "and", "refreshes", "the", "marker", "." ]
93bf5408ad84b74ea42f55ccb6ca0450daa41427
https://github.com/Leaflet/Leaflet.markercluster/blob/93bf5408ad84b74ea42f55ccb6ca0450daa41427/src/MarkerClusterGroup.Refresh.js#L93-L109
7,419
Leaflet/Leaflet.markercluster
src/MarkerCluster.Spiderfier.js
function (layer) { if (layer._spiderLeg) { this._featureGroup.removeLayer(layer); if (layer.clusterShow) { layer.clusterShow(); } //Position will be fixed up immediately in _animationUnspiderfy if (layer.setZIndexOffset) { layer.setZIndexOffset(0); } this._map.removeLayer(layer._spiderLeg); delete layer._spiderLeg; } }
javascript
function (layer) { if (layer._spiderLeg) { this._featureGroup.removeLayer(layer); if (layer.clusterShow) { layer.clusterShow(); } //Position will be fixed up immediately in _animationUnspiderfy if (layer.setZIndexOffset) { layer.setZIndexOffset(0); } this._map.removeLayer(layer._spiderLeg); delete layer._spiderLeg; } }
[ "function", "(", "layer", ")", "{", "if", "(", "layer", ".", "_spiderLeg", ")", "{", "this", ".", "_featureGroup", ".", "removeLayer", "(", "layer", ")", ";", "if", "(", "layer", ".", "clusterShow", ")", "{", "layer", ".", "clusterShow", "(", ")", ";", "}", "//Position will be fixed up immediately in _animationUnspiderfy", "if", "(", "layer", ".", "setZIndexOffset", ")", "{", "layer", ".", "setZIndexOffset", "(", "0", ")", ";", "}", "this", ".", "_map", ".", "removeLayer", "(", "layer", ".", "_spiderLeg", ")", ";", "delete", "layer", ".", "_spiderLeg", ";", "}", "}" ]
If the given layer is currently being spiderfied then we unspiderfy it so it isn't on the map anymore etc
[ "If", "the", "given", "layer", "is", "currently", "being", "spiderfied", "then", "we", "unspiderfy", "it", "so", "it", "isn", "t", "on", "the", "map", "anymore", "etc" ]
93bf5408ad84b74ea42f55ccb6ca0450daa41427
https://github.com/Leaflet/Leaflet.markercluster/blob/93bf5408ad84b74ea42f55ccb6ca0450daa41427/src/MarkerCluster.Spiderfier.js#L461-L476
7,420
Leaflet/Leaflet.markercluster
src/DistanceGrid.js
function (obj, point) { var x = this._getCoord(point.x), y = this._getCoord(point.y), grid = this._grid, row = grid[y] = grid[y] || {}, cell = row[x] = row[x] || [], i, len; delete this._objectPoint[L.Util.stamp(obj)]; for (i = 0, len = cell.length; i < len; i++) { if (cell[i] === obj) { cell.splice(i, 1); if (len === 1) { delete row[x]; } return true; } } }
javascript
function (obj, point) { var x = this._getCoord(point.x), y = this._getCoord(point.y), grid = this._grid, row = grid[y] = grid[y] || {}, cell = row[x] = row[x] || [], i, len; delete this._objectPoint[L.Util.stamp(obj)]; for (i = 0, len = cell.length; i < len; i++) { if (cell[i] === obj) { cell.splice(i, 1); if (len === 1) { delete row[x]; } return true; } } }
[ "function", "(", "obj", ",", "point", ")", "{", "var", "x", "=", "this", ".", "_getCoord", "(", "point", ".", "x", ")", ",", "y", "=", "this", ".", "_getCoord", "(", "point", ".", "y", ")", ",", "grid", "=", "this", ".", "_grid", ",", "row", "=", "grid", "[", "y", "]", "=", "grid", "[", "y", "]", "||", "{", "}", ",", "cell", "=", "row", "[", "x", "]", "=", "row", "[", "x", "]", "||", "[", "]", ",", "i", ",", "len", ";", "delete", "this", ".", "_objectPoint", "[", "L", ".", "Util", ".", "stamp", "(", "obj", ")", "]", ";", "for", "(", "i", "=", "0", ",", "len", "=", "cell", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "cell", "[", "i", "]", "===", "obj", ")", "{", "cell", ".", "splice", "(", "i", ",", "1", ")", ";", "if", "(", "len", "===", "1", ")", "{", "delete", "row", "[", "x", "]", ";", "}", "return", "true", ";", "}", "}", "}" ]
Returns true if the object was found
[ "Returns", "true", "if", "the", "object", "was", "found" ]
93bf5408ad84b74ea42f55ccb6ca0450daa41427
https://github.com/Leaflet/Leaflet.markercluster/blob/93bf5408ad84b74ea42f55ccb6ca0450daa41427/src/DistanceGrid.js#L30-L53
7,421
bitpay/cordova-plugin-qrscanner
src/common/src/createQRScannerAdapter.js
clearBackground
function clearBackground() { var body = document.body; if (body.style) { body.style.backgroundColor = 'rgba(0,0,0,0.01)'; body.style.backgroundImage = ''; setTimeout(function() { body.style.backgroundColor = 'transparent'; }, 1); if (body.parentNode && body.parentNode.style) { body.parentNode.style.backgroundColor = 'transparent'; body.parentNode.style.backgroundImage = ''; } } }
javascript
function clearBackground() { var body = document.body; if (body.style) { body.style.backgroundColor = 'rgba(0,0,0,0.01)'; body.style.backgroundImage = ''; setTimeout(function() { body.style.backgroundColor = 'transparent'; }, 1); if (body.parentNode && body.parentNode.style) { body.parentNode.style.backgroundColor = 'transparent'; body.parentNode.style.backgroundImage = ''; } } }
[ "function", "clearBackground", "(", ")", "{", "var", "body", "=", "document", ".", "body", ";", "if", "(", "body", ".", "style", ")", "{", "body", ".", "style", ".", "backgroundColor", "=", "'rgba(0,0,0,0.01)'", ";", "body", ".", "style", ".", "backgroundImage", "=", "''", ";", "setTimeout", "(", "function", "(", ")", "{", "body", ".", "style", ".", "backgroundColor", "=", "'transparent'", ";", "}", ",", "1", ")", ";", "if", "(", "body", ".", "parentNode", "&&", "body", ".", "parentNode", ".", "style", ")", "{", "body", ".", "parentNode", ".", "style", ".", "backgroundColor", "=", "'transparent'", ";", "body", ".", "parentNode", ".", "style", ".", "backgroundImage", "=", "''", ";", "}", "}", "}" ]
Simple utility method to ensure the background is transparent. Used by the plugin to force re-rendering immediately after the native webview background is made transparent.
[ "Simple", "utility", "method", "to", "ensure", "the", "background", "is", "transparent", ".", "Used", "by", "the", "plugin", "to", "force", "re", "-", "rendering", "immediately", "after", "the", "native", "webview", "background", "is", "made", "transparent", "." ]
b62efb64801ba0b830f0aac556935c0978d2fb98
https://github.com/bitpay/cordova-plugin-qrscanner/blob/b62efb64801ba0b830f0aac556935c0978d2fb98/src/common/src/createQRScannerAdapter.js#L36-L49
7,422
bitpay/cordova-plugin-qrscanner
src/browser/src/createQRScannerInternal.js
getCameraSpecsById
function getCameraSpecsById(deviceId){ // return a getUserMedia Constraints function getConstraintObj(deviceId, facingMode, width, height){ var obj = { audio: false, video: {} }; obj.video.deviceId = {exact: deviceId}; if(facingMode) { obj.video.facingMode = {exact: facingMode}; } if(width) { obj.video.width = {exact: width}; } if(height) { obj.video.height = {exact: height}; } return obj; } var facingModeConstraints = facingModes.map(function(mode){ return getConstraintObj(deviceId, mode); }); var widthConstraints = standardWidthsAndHeights.map(function(width){ return getConstraintObj(deviceId, null, width); }); var heightConstraints = standardWidthsAndHeights.map(function(height){ return getConstraintObj(deviceId, null, null, height); }); // create a promise which tries to resolve the best constraints for this deviceId // rather than reject, failures return a value of `null` function getFirstResolvingConstraint(constraintsBestToWorst){ return new Promise(function(resolveBestConstraints){ // build a chain of promises which either resolves or continues searching return constraintsBestToWorst.reduce(function(chain, next){ return chain.then(function(searchState){ if(searchState.found){ // The best working constraint was found. Skip further tests. return searchState; } else { searchState.nextConstraint = next; return window.navigator.mediaDevices.getUserMedia(searchState.nextConstraint).then(function(mediaStream){ // We found the first working constraint object, now we can stop // the stream and short-circuit the search. killStream(mediaStream); searchState.found = true; return searchState; }, function(){ // didn't get a media stream. The search continues: return searchState; }); } }); }, Promise.resolve({ // kick off the search: found: false, nextConstraint: {} })).then(function(searchState){ if(searchState.found){ resolveBestConstraints(searchState.nextConstraint); } else { resolveBestConstraints(null); } }); }); } return getFirstResolvingConstraint(facingModeConstraints).then(function(facingModeSpecs){ return getFirstResolvingConstraint(widthConstraints).then(function(widthSpecs){ return getFirstResolvingConstraint(heightConstraints).then(function(heightSpecs){ return { deviceId: deviceId, facingMode: facingModeSpecs === null ? null : facingModeSpecs.video.facingMode.exact, width: widthSpecs === null ? null : widthSpecs.video.width.exact, height: heightSpecs === null ? null : heightSpecs.video.height.exact }; }); }); }); }
javascript
function getCameraSpecsById(deviceId){ // return a getUserMedia Constraints function getConstraintObj(deviceId, facingMode, width, height){ var obj = { audio: false, video: {} }; obj.video.deviceId = {exact: deviceId}; if(facingMode) { obj.video.facingMode = {exact: facingMode}; } if(width) { obj.video.width = {exact: width}; } if(height) { obj.video.height = {exact: height}; } return obj; } var facingModeConstraints = facingModes.map(function(mode){ return getConstraintObj(deviceId, mode); }); var widthConstraints = standardWidthsAndHeights.map(function(width){ return getConstraintObj(deviceId, null, width); }); var heightConstraints = standardWidthsAndHeights.map(function(height){ return getConstraintObj(deviceId, null, null, height); }); // create a promise which tries to resolve the best constraints for this deviceId // rather than reject, failures return a value of `null` function getFirstResolvingConstraint(constraintsBestToWorst){ return new Promise(function(resolveBestConstraints){ // build a chain of promises which either resolves or continues searching return constraintsBestToWorst.reduce(function(chain, next){ return chain.then(function(searchState){ if(searchState.found){ // The best working constraint was found. Skip further tests. return searchState; } else { searchState.nextConstraint = next; return window.navigator.mediaDevices.getUserMedia(searchState.nextConstraint).then(function(mediaStream){ // We found the first working constraint object, now we can stop // the stream and short-circuit the search. killStream(mediaStream); searchState.found = true; return searchState; }, function(){ // didn't get a media stream. The search continues: return searchState; }); } }); }, Promise.resolve({ // kick off the search: found: false, nextConstraint: {} })).then(function(searchState){ if(searchState.found){ resolveBestConstraints(searchState.nextConstraint); } else { resolveBestConstraints(null); } }); }); } return getFirstResolvingConstraint(facingModeConstraints).then(function(facingModeSpecs){ return getFirstResolvingConstraint(widthConstraints).then(function(widthSpecs){ return getFirstResolvingConstraint(heightConstraints).then(function(heightSpecs){ return { deviceId: deviceId, facingMode: facingModeSpecs === null ? null : facingModeSpecs.video.facingMode.exact, width: widthSpecs === null ? null : widthSpecs.video.width.exact, height: heightSpecs === null ? null : heightSpecs.video.height.exact }; }); }); }); }
[ "function", "getCameraSpecsById", "(", "deviceId", ")", "{", "// return a getUserMedia Constraints", "function", "getConstraintObj", "(", "deviceId", ",", "facingMode", ",", "width", ",", "height", ")", "{", "var", "obj", "=", "{", "audio", ":", "false", ",", "video", ":", "{", "}", "}", ";", "obj", ".", "video", ".", "deviceId", "=", "{", "exact", ":", "deviceId", "}", ";", "if", "(", "facingMode", ")", "{", "obj", ".", "video", ".", "facingMode", "=", "{", "exact", ":", "facingMode", "}", ";", "}", "if", "(", "width", ")", "{", "obj", ".", "video", ".", "width", "=", "{", "exact", ":", "width", "}", ";", "}", "if", "(", "height", ")", "{", "obj", ".", "video", ".", "height", "=", "{", "exact", ":", "height", "}", ";", "}", "return", "obj", ";", "}", "var", "facingModeConstraints", "=", "facingModes", ".", "map", "(", "function", "(", "mode", ")", "{", "return", "getConstraintObj", "(", "deviceId", ",", "mode", ")", ";", "}", ")", ";", "var", "widthConstraints", "=", "standardWidthsAndHeights", ".", "map", "(", "function", "(", "width", ")", "{", "return", "getConstraintObj", "(", "deviceId", ",", "null", ",", "width", ")", ";", "}", ")", ";", "var", "heightConstraints", "=", "standardWidthsAndHeights", ".", "map", "(", "function", "(", "height", ")", "{", "return", "getConstraintObj", "(", "deviceId", ",", "null", ",", "null", ",", "height", ")", ";", "}", ")", ";", "// create a promise which tries to resolve the best constraints for this deviceId", "// rather than reject, failures return a value of `null`", "function", "getFirstResolvingConstraint", "(", "constraintsBestToWorst", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolveBestConstraints", ")", "{", "// build a chain of promises which either resolves or continues searching", "return", "constraintsBestToWorst", ".", "reduce", "(", "function", "(", "chain", ",", "next", ")", "{", "return", "chain", ".", "then", "(", "function", "(", "searchState", ")", "{", "if", "(", "searchState", ".", "found", ")", "{", "// The best working constraint was found. Skip further tests.", "return", "searchState", ";", "}", "else", "{", "searchState", ".", "nextConstraint", "=", "next", ";", "return", "window", ".", "navigator", ".", "mediaDevices", ".", "getUserMedia", "(", "searchState", ".", "nextConstraint", ")", ".", "then", "(", "function", "(", "mediaStream", ")", "{", "// We found the first working constraint object, now we can stop", "// the stream and short-circuit the search.", "killStream", "(", "mediaStream", ")", ";", "searchState", ".", "found", "=", "true", ";", "return", "searchState", ";", "}", ",", "function", "(", ")", "{", "// didn't get a media stream. The search continues:", "return", "searchState", ";", "}", ")", ";", "}", "}", ")", ";", "}", ",", "Promise", ".", "resolve", "(", "{", "// kick off the search:", "found", ":", "false", ",", "nextConstraint", ":", "{", "}", "}", ")", ")", ".", "then", "(", "function", "(", "searchState", ")", "{", "if", "(", "searchState", ".", "found", ")", "{", "resolveBestConstraints", "(", "searchState", ".", "nextConstraint", ")", ";", "}", "else", "{", "resolveBestConstraints", "(", "null", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", "return", "getFirstResolvingConstraint", "(", "facingModeConstraints", ")", ".", "then", "(", "function", "(", "facingModeSpecs", ")", "{", "return", "getFirstResolvingConstraint", "(", "widthConstraints", ")", ".", "then", "(", "function", "(", "widthSpecs", ")", "{", "return", "getFirstResolvingConstraint", "(", "heightConstraints", ")", ".", "then", "(", "function", "(", "heightSpecs", ")", "{", "return", "{", "deviceId", ":", "deviceId", ",", "facingMode", ":", "facingModeSpecs", "===", "null", "?", "null", ":", "facingModeSpecs", ".", "video", ".", "facingMode", ".", "exact", ",", "width", ":", "widthSpecs", "===", "null", "?", "null", ":", "widthSpecs", ".", "video", ".", "width", ".", "exact", ",", "height", ":", "heightSpecs", "===", "null", "?", "null", ":", "heightSpecs", ".", "video", ".", "height", ".", "exact", "}", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
For performance, we test best-to-worst constraints. Once we find a match, we move to the next test. Since `ConstraintNotSatisfiedError`s are thrown much faster than streams can be started and stopped, the scan is much faster, even though it may iterate through more constraint objects.
[ "For", "performance", "we", "test", "best", "-", "to", "-", "worst", "constraints", ".", "Once", "we", "find", "a", "match", "we", "move", "to", "the", "next", "test", ".", "Since", "ConstraintNotSatisfiedError", "s", "are", "thrown", "much", "faster", "than", "streams", "can", "be", "started", "and", "stopped", "the", "scan", "is", "much", "faster", "even", "though", "it", "may", "iterate", "through", "more", "constraint", "objects", "." ]
b62efb64801ba0b830f0aac556935c0978d2fb98
https://github.com/bitpay/cordova-plugin-qrscanner/blob/b62efb64801ba0b830f0aac556935c0978d2fb98/src/browser/src/createQRScannerInternal.js#L51-L129
7,423
bitpay/cordova-plugin-qrscanner
src/browser/src/createQRScannerInternal.js
getConstraintObj
function getConstraintObj(deviceId, facingMode, width, height){ var obj = { audio: false, video: {} }; obj.video.deviceId = {exact: deviceId}; if(facingMode) { obj.video.facingMode = {exact: facingMode}; } if(width) { obj.video.width = {exact: width}; } if(height) { obj.video.height = {exact: height}; } return obj; }
javascript
function getConstraintObj(deviceId, facingMode, width, height){ var obj = { audio: false, video: {} }; obj.video.deviceId = {exact: deviceId}; if(facingMode) { obj.video.facingMode = {exact: facingMode}; } if(width) { obj.video.width = {exact: width}; } if(height) { obj.video.height = {exact: height}; } return obj; }
[ "function", "getConstraintObj", "(", "deviceId", ",", "facingMode", ",", "width", ",", "height", ")", "{", "var", "obj", "=", "{", "audio", ":", "false", ",", "video", ":", "{", "}", "}", ";", "obj", ".", "video", ".", "deviceId", "=", "{", "exact", ":", "deviceId", "}", ";", "if", "(", "facingMode", ")", "{", "obj", ".", "video", ".", "facingMode", "=", "{", "exact", ":", "facingMode", "}", ";", "}", "if", "(", "width", ")", "{", "obj", ".", "video", ".", "width", "=", "{", "exact", ":", "width", "}", ";", "}", "if", "(", "height", ")", "{", "obj", ".", "video", ".", "height", "=", "{", "exact", ":", "height", "}", ";", "}", "return", "obj", ";", "}" ]
return a getUserMedia Constraints
[ "return", "a", "getUserMedia", "Constraints" ]
b62efb64801ba0b830f0aac556935c0978d2fb98
https://github.com/bitpay/cordova-plugin-qrscanner/blob/b62efb64801ba0b830f0aac556935c0978d2fb98/src/browser/src/createQRScannerInternal.js#L54-L67
7,424
bitpay/cordova-plugin-qrscanner
src/browser/src/createQRScannerInternal.js
getFirstResolvingConstraint
function getFirstResolvingConstraint(constraintsBestToWorst){ return new Promise(function(resolveBestConstraints){ // build a chain of promises which either resolves or continues searching return constraintsBestToWorst.reduce(function(chain, next){ return chain.then(function(searchState){ if(searchState.found){ // The best working constraint was found. Skip further tests. return searchState; } else { searchState.nextConstraint = next; return window.navigator.mediaDevices.getUserMedia(searchState.nextConstraint).then(function(mediaStream){ // We found the first working constraint object, now we can stop // the stream and short-circuit the search. killStream(mediaStream); searchState.found = true; return searchState; }, function(){ // didn't get a media stream. The search continues: return searchState; }); } }); }, Promise.resolve({ // kick off the search: found: false, nextConstraint: {} })).then(function(searchState){ if(searchState.found){ resolveBestConstraints(searchState.nextConstraint); } else { resolveBestConstraints(null); } }); }); }
javascript
function getFirstResolvingConstraint(constraintsBestToWorst){ return new Promise(function(resolveBestConstraints){ // build a chain of promises which either resolves or continues searching return constraintsBestToWorst.reduce(function(chain, next){ return chain.then(function(searchState){ if(searchState.found){ // The best working constraint was found. Skip further tests. return searchState; } else { searchState.nextConstraint = next; return window.navigator.mediaDevices.getUserMedia(searchState.nextConstraint).then(function(mediaStream){ // We found the first working constraint object, now we can stop // the stream and short-circuit the search. killStream(mediaStream); searchState.found = true; return searchState; }, function(){ // didn't get a media stream. The search continues: return searchState; }); } }); }, Promise.resolve({ // kick off the search: found: false, nextConstraint: {} })).then(function(searchState){ if(searchState.found){ resolveBestConstraints(searchState.nextConstraint); } else { resolveBestConstraints(null); } }); }); }
[ "function", "getFirstResolvingConstraint", "(", "constraintsBestToWorst", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolveBestConstraints", ")", "{", "// build a chain of promises which either resolves or continues searching", "return", "constraintsBestToWorst", ".", "reduce", "(", "function", "(", "chain", ",", "next", ")", "{", "return", "chain", ".", "then", "(", "function", "(", "searchState", ")", "{", "if", "(", "searchState", ".", "found", ")", "{", "// The best working constraint was found. Skip further tests.", "return", "searchState", ";", "}", "else", "{", "searchState", ".", "nextConstraint", "=", "next", ";", "return", "window", ".", "navigator", ".", "mediaDevices", ".", "getUserMedia", "(", "searchState", ".", "nextConstraint", ")", ".", "then", "(", "function", "(", "mediaStream", ")", "{", "// We found the first working constraint object, now we can stop", "// the stream and short-circuit the search.", "killStream", "(", "mediaStream", ")", ";", "searchState", ".", "found", "=", "true", ";", "return", "searchState", ";", "}", ",", "function", "(", ")", "{", "// didn't get a media stream. The search continues:", "return", "searchState", ";", "}", ")", ";", "}", "}", ")", ";", "}", ",", "Promise", ".", "resolve", "(", "{", "// kick off the search:", "found", ":", "false", ",", "nextConstraint", ":", "{", "}", "}", ")", ")", ".", "then", "(", "function", "(", "searchState", ")", "{", "if", "(", "searchState", ".", "found", ")", "{", "resolveBestConstraints", "(", "searchState", ".", "nextConstraint", ")", ";", "}", "else", "{", "resolveBestConstraints", "(", "null", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
create a promise which tries to resolve the best constraints for this deviceId rather than reject, failures return a value of `null`
[ "create", "a", "promise", "which", "tries", "to", "resolve", "the", "best", "constraints", "for", "this", "deviceId", "rather", "than", "reject", "failures", "return", "a", "value", "of", "null" ]
b62efb64801ba0b830f0aac556935c0978d2fb98
https://github.com/bitpay/cordova-plugin-qrscanner/blob/b62efb64801ba0b830f0aac556935c0978d2fb98/src/browser/src/createQRScannerInternal.js#L81-L115
7,425
openpgpjs/openpgpjs
src/openpgp.js
convertStream
async function convertStream(data, streaming) { if (!streaming && util.isStream(data)) { return stream.readToEnd(data); } if (streaming && !util.isStream(data)) { data = new ReadableStream({ start(controller) { controller.enqueue(data); controller.close(); } }); } if (streaming === 'node') { data = stream.webToNode(data); } return data; }
javascript
async function convertStream(data, streaming) { if (!streaming && util.isStream(data)) { return stream.readToEnd(data); } if (streaming && !util.isStream(data)) { data = new ReadableStream({ start(controller) { controller.enqueue(data); controller.close(); } }); } if (streaming === 'node') { data = stream.webToNode(data); } return data; }
[ "async", "function", "convertStream", "(", "data", ",", "streaming", ")", "{", "if", "(", "!", "streaming", "&&", "util", ".", "isStream", "(", "data", ")", ")", "{", "return", "stream", ".", "readToEnd", "(", "data", ")", ";", "}", "if", "(", "streaming", "&&", "!", "util", ".", "isStream", "(", "data", ")", ")", "{", "data", "=", "new", "ReadableStream", "(", "{", "start", "(", "controller", ")", "{", "controller", ".", "enqueue", "(", "data", ")", ";", "controller", ".", "close", "(", ")", ";", "}", "}", ")", ";", "}", "if", "(", "streaming", "===", "'node'", ")", "{", "data", "=", "stream", ".", "webToNode", "(", "data", ")", ";", "}", "return", "data", ";", "}" ]
Convert data to or from Stream @param {Object} data the data to convert @param {'web'|'node'|false} streaming (optional) whether to return a ReadableStream @returns {Object} the data in the respective format
[ "Convert", "data", "to", "or", "from", "Stream" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/openpgp.js#L622-L638
7,426
openpgpjs/openpgpjs
src/openpgp.js
convertStreams
async function convertStreams(obj, streaming, keys=[]) { if (Object.prototype.isPrototypeOf(obj) && !Uint8Array.prototype.isPrototypeOf(obj)) { await Promise.all(Object.entries(obj).map(async ([key, value]) => { // recursively search all children if (util.isStream(value) || keys.includes(key)) { obj[key] = await convertStream(value, streaming); } else { await convertStreams(obj[key], streaming); } })); } return obj; }
javascript
async function convertStreams(obj, streaming, keys=[]) { if (Object.prototype.isPrototypeOf(obj) && !Uint8Array.prototype.isPrototypeOf(obj)) { await Promise.all(Object.entries(obj).map(async ([key, value]) => { // recursively search all children if (util.isStream(value) || keys.includes(key)) { obj[key] = await convertStream(value, streaming); } else { await convertStreams(obj[key], streaming); } })); } return obj; }
[ "async", "function", "convertStreams", "(", "obj", ",", "streaming", ",", "keys", "=", "[", "]", ")", "{", "if", "(", "Object", ".", "prototype", ".", "isPrototypeOf", "(", "obj", ")", "&&", "!", "Uint8Array", ".", "prototype", ".", "isPrototypeOf", "(", "obj", ")", ")", "{", "await", "Promise", ".", "all", "(", "Object", ".", "entries", "(", "obj", ")", ".", "map", "(", "async", "(", "[", "key", ",", "value", "]", ")", "=>", "{", "// recursively search all children", "if", "(", "util", ".", "isStream", "(", "value", ")", "||", "keys", ".", "includes", "(", "key", ")", ")", "{", "obj", "[", "key", "]", "=", "await", "convertStream", "(", "value", ",", "streaming", ")", ";", "}", "else", "{", "await", "convertStreams", "(", "obj", "[", "key", "]", ",", "streaming", ")", ";", "}", "}", ")", ")", ";", "}", "return", "obj", ";", "}" ]
Convert object properties from Stream @param {Object} obj the data to convert @param {'web'|'node'|false} streaming (optional) whether to return ReadableStreams @param {Array<String>} keys (optional) which keys to return as streams, if possible @returns {Object} the data in the respective format
[ "Convert", "object", "properties", "from", "Stream" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/openpgp.js#L647-L658
7,427
openpgpjs/openpgpjs
src/openpgp.js
linkStreams
function linkStreams(result, message, erroringStream) { result.data = stream.transformPair(message.packets.stream, async (readable, writable) => { await stream.pipe(result.data, writable, { preventClose: true }); const writer = stream.getWriter(writable); try { // Forward errors in erroringStream (defaulting to the message stream) to result.data. await stream.readToEnd(erroringStream || readable, arr => arr); await writer.close(); } catch(e) { await writer.abort(e); } }); }
javascript
function linkStreams(result, message, erroringStream) { result.data = stream.transformPair(message.packets.stream, async (readable, writable) => { await stream.pipe(result.data, writable, { preventClose: true }); const writer = stream.getWriter(writable); try { // Forward errors in erroringStream (defaulting to the message stream) to result.data. await stream.readToEnd(erroringStream || readable, arr => arr); await writer.close(); } catch(e) { await writer.abort(e); } }); }
[ "function", "linkStreams", "(", "result", ",", "message", ",", "erroringStream", ")", "{", "result", ".", "data", "=", "stream", ".", "transformPair", "(", "message", ".", "packets", ".", "stream", ",", "async", "(", "readable", ",", "writable", ")", "=>", "{", "await", "stream", ".", "pipe", "(", "result", ".", "data", ",", "writable", ",", "{", "preventClose", ":", "true", "}", ")", ";", "const", "writer", "=", "stream", ".", "getWriter", "(", "writable", ")", ";", "try", "{", "// Forward errors in erroringStream (defaulting to the message stream) to result.data.", "await", "stream", ".", "readToEnd", "(", "erroringStream", "||", "readable", ",", "arr", "=>", "arr", ")", ";", "await", "writer", ".", "close", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "await", "writer", ".", "abort", "(", "e", ")", ";", "}", "}", ")", ";", "}" ]
Link result.data to the message stream for cancellation. Also, forward errors in the message to result.data. @param {Object} result the data to convert @param {Message} message message object @param {ReadableStream} erroringStream (optional) stream which either errors or gets closed without data @returns {Object}
[ "Link", "result", ".", "data", "to", "the", "message", "stream", "for", "cancellation", ".", "Also", "forward", "errors", "in", "the", "message", "to", "result", ".", "data", "." ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/openpgp.js#L668-L682
7,428
openpgpjs/openpgpjs
src/openpgp.js
prepareSignatures
async function prepareSignatures(signatures) { await Promise.all(signatures.map(async signature => { signature.signature = await signature.signature; try { signature.valid = await signature.verified; } catch(e) { signature.valid = null; signature.error = e; util.print_debug_error(e); } })); }
javascript
async function prepareSignatures(signatures) { await Promise.all(signatures.map(async signature => { signature.signature = await signature.signature; try { signature.valid = await signature.verified; } catch(e) { signature.valid = null; signature.error = e; util.print_debug_error(e); } })); }
[ "async", "function", "prepareSignatures", "(", "signatures", ")", "{", "await", "Promise", ".", "all", "(", "signatures", ".", "map", "(", "async", "signature", "=>", "{", "signature", ".", "signature", "=", "await", "signature", ".", "signature", ";", "try", "{", "signature", ".", "valid", "=", "await", "signature", ".", "verified", ";", "}", "catch", "(", "e", ")", "{", "signature", ".", "valid", "=", "null", ";", "signature", ".", "error", "=", "e", ";", "util", ".", "print_debug_error", "(", "e", ")", ";", "}", "}", ")", ")", ";", "}" ]
Wait until signature objects have been verified @param {Object} signatures list of signatures
[ "Wait", "until", "signature", "objects", "have", "been", "verified" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/openpgp.js#L688-L699
7,429
openpgpjs/openpgpjs
src/openpgp.js
onError
function onError(message, error) { // log the stack trace util.print_debug_error(error); // update error message try { error.message = message + ': ' + error.message; } catch(e) {} throw error; }
javascript
function onError(message, error) { // log the stack trace util.print_debug_error(error); // update error message try { error.message = message + ': ' + error.message; } catch(e) {} throw error; }
[ "function", "onError", "(", "message", ",", "error", ")", "{", "// log the stack trace", "util", ".", "print_debug_error", "(", "error", ")", ";", "// update error message", "try", "{", "error", ".", "message", "=", "message", "+", "': '", "+", "error", ".", "message", ";", "}", "catch", "(", "e", ")", "{", "}", "throw", "error", ";", "}" ]
Global error handler that logs the stack trace and rethrows a high lvl error message. @param {String} message A human readable high level error Message @param {Error} error The internal error that caused the failure
[ "Global", "error", "handler", "that", "logs", "the", "stack", "trace", "and", "rethrows", "a", "high", "lvl", "error", "message", "." ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/openpgp.js#L707-L717
7,430
openpgpjs/openpgpjs
src/openpgp.js
nativeAEAD
function nativeAEAD() { return config.aead_protect && ( ((config.aead_protect_version !== 4 || config.aead_mode === enums.aead.experimental_gcm) && util.getWebCrypto()) || (config.aead_protect_version === 4 && config.aead_mode === enums.aead.eax && util.getWebCrypto()) ); }
javascript
function nativeAEAD() { return config.aead_protect && ( ((config.aead_protect_version !== 4 || config.aead_mode === enums.aead.experimental_gcm) && util.getWebCrypto()) || (config.aead_protect_version === 4 && config.aead_mode === enums.aead.eax && util.getWebCrypto()) ); }
[ "function", "nativeAEAD", "(", ")", "{", "return", "config", ".", "aead_protect", "&&", "(", "(", "(", "config", ".", "aead_protect_version", "!==", "4", "||", "config", ".", "aead_mode", "===", "enums", ".", "aead", ".", "experimental_gcm", ")", "&&", "util", ".", "getWebCrypto", "(", ")", ")", "||", "(", "config", ".", "aead_protect_version", "===", "4", "&&", "config", ".", "aead_mode", "===", "enums", ".", "aead", ".", "eax", "&&", "util", ".", "getWebCrypto", "(", ")", ")", ")", ";", "}" ]
Check for native AEAD support and configuration by the user. Only browsers that implement the current WebCrypto specification support native GCM. Native EAX is built on CTR and CBC, which current browsers support. OCB and CFB are not natively supported. @returns {Boolean} If authenticated encryption should be used
[ "Check", "for", "native", "AEAD", "support", "and", "configuration", "by", "the", "user", ".", "Only", "browsers", "that", "implement", "the", "current", "WebCrypto", "specification", "support", "native", "GCM", ".", "Native", "EAX", "is", "built", "on", "CTR", "and", "CBC", "which", "current", "browsers", "support", ".", "OCB", "and", "CFB", "are", "not", "natively", "supported", "." ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/openpgp.js#L726-L731
7,431
openpgpjs/openpgpjs
src/crypto/public_key/rsa.js
promisifyIE11Op
function promisifyIE11Op(keyObj, err) { if (typeof keyObj.then !== 'function') { // IE11 KeyOperation return new Promise(function(resolve, reject) { keyObj.onerror = function () { reject(new Error(err)); }; keyObj.oncomplete = function (e) { resolve(e.target.result); }; }); } return keyObj; }
javascript
function promisifyIE11Op(keyObj, err) { if (typeof keyObj.then !== 'function') { // IE11 KeyOperation return new Promise(function(resolve, reject) { keyObj.onerror = function () { reject(new Error(err)); }; keyObj.oncomplete = function (e) { resolve(e.target.result); }; }); } return keyObj; }
[ "function", "promisifyIE11Op", "(", "keyObj", ",", "err", ")", "{", "if", "(", "typeof", "keyObj", ".", "then", "!==", "'function'", ")", "{", "// IE11 KeyOperation", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "keyObj", ".", "onerror", "=", "function", "(", ")", "{", "reject", "(", "new", "Error", "(", "err", ")", ")", ";", "}", ";", "keyObj", ".", "oncomplete", "=", "function", "(", "e", ")", "{", "resolve", "(", "e", ".", "target", ".", "result", ")", ";", "}", ";", "}", ")", ";", "}", "return", "keyObj", ";", "}" ]
Helper for IE11 KeyOperation objects
[ "Helper", "for", "IE11", "KeyOperation", "objects" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/crypto/public_key/rsa.js#L35-L47
7,432
openpgpjs/openpgpjs
src/crypto/public_key/rsa.js
async function(m, n, e, d, p, q, u) { if (n.cmp(m) <= 0) { throw new Error('Data too large.'); } const dq = d.mod(q.subn(1)); // d mod (q-1) const dp = d.mod(p.subn(1)); // d mod (p-1) const pred = new BN.red(p); const qred = new BN.red(q); const nred = new BN.red(n); let blinder; let unblinder; if (config.rsa_blinding) { unblinder = (await random.getRandomBN(new BN(2), n)).toRed(nred); blinder = unblinder.redInvm().redPow(e); m = m.toRed(nred).redMul(blinder).fromRed(); } const mp = m.toRed(pred).redPow(dp); const mq = m.toRed(qred).redPow(dq); const t = mq.redSub(mp.fromRed().toRed(qred)); const h = u.toRed(qred).redMul(t).fromRed(); let result = h.mul(p).add(mp).toRed(nred); if (config.rsa_blinding) { result = result.redMul(unblinder); } return result.toArrayLike(Uint8Array, 'be', n.byteLength()); }
javascript
async function(m, n, e, d, p, q, u) { if (n.cmp(m) <= 0) { throw new Error('Data too large.'); } const dq = d.mod(q.subn(1)); // d mod (q-1) const dp = d.mod(p.subn(1)); // d mod (p-1) const pred = new BN.red(p); const qred = new BN.red(q); const nred = new BN.red(n); let blinder; let unblinder; if (config.rsa_blinding) { unblinder = (await random.getRandomBN(new BN(2), n)).toRed(nred); blinder = unblinder.redInvm().redPow(e); m = m.toRed(nred).redMul(blinder).fromRed(); } const mp = m.toRed(pred).redPow(dp); const mq = m.toRed(qred).redPow(dq); const t = mq.redSub(mp.fromRed().toRed(qred)); const h = u.toRed(qred).redMul(t).fromRed(); let result = h.mul(p).add(mp).toRed(nred); if (config.rsa_blinding) { result = result.redMul(unblinder); } return result.toArrayLike(Uint8Array, 'be', n.byteLength()); }
[ "async", "function", "(", "m", ",", "n", ",", "e", ",", "d", ",", "p", ",", "q", ",", "u", ")", "{", "if", "(", "n", ".", "cmp", "(", "m", ")", "<=", "0", ")", "{", "throw", "new", "Error", "(", "'Data too large.'", ")", ";", "}", "const", "dq", "=", "d", ".", "mod", "(", "q", ".", "subn", "(", "1", ")", ")", ";", "// d mod (q-1)", "const", "dp", "=", "d", ".", "mod", "(", "p", ".", "subn", "(", "1", ")", ")", ";", "// d mod (p-1)", "const", "pred", "=", "new", "BN", ".", "red", "(", "p", ")", ";", "const", "qred", "=", "new", "BN", ".", "red", "(", "q", ")", ";", "const", "nred", "=", "new", "BN", ".", "red", "(", "n", ")", ";", "let", "blinder", ";", "let", "unblinder", ";", "if", "(", "config", ".", "rsa_blinding", ")", "{", "unblinder", "=", "(", "await", "random", ".", "getRandomBN", "(", "new", "BN", "(", "2", ")", ",", "n", ")", ")", ".", "toRed", "(", "nred", ")", ";", "blinder", "=", "unblinder", ".", "redInvm", "(", ")", ".", "redPow", "(", "e", ")", ";", "m", "=", "m", ".", "toRed", "(", "nred", ")", ".", "redMul", "(", "blinder", ")", ".", "fromRed", "(", ")", ";", "}", "const", "mp", "=", "m", ".", "toRed", "(", "pred", ")", ".", "redPow", "(", "dp", ")", ";", "const", "mq", "=", "m", ".", "toRed", "(", "qred", ")", ".", "redPow", "(", "dq", ")", ";", "const", "t", "=", "mq", ".", "redSub", "(", "mp", ".", "fromRed", "(", ")", ".", "toRed", "(", "qred", ")", ")", ";", "const", "h", "=", "u", ".", "toRed", "(", "qred", ")", ".", "redMul", "(", "t", ")", ".", "fromRed", "(", ")", ";", "let", "result", "=", "h", ".", "mul", "(", "p", ")", ".", "add", "(", "mp", ")", ".", "toRed", "(", "nred", ")", ";", "if", "(", "config", ".", "rsa_blinding", ")", "{", "result", "=", "result", ".", "redMul", "(", "unblinder", ")", ";", "}", "return", "result", ".", "toArrayLike", "(", "Uint8Array", ",", "'be'", ",", "n", ".", "byteLength", "(", ")", ")", ";", "}" ]
Decrypt RSA message @param {BN} m message @param {BN} n RSA public modulus @param {BN} e RSA public exponent @param {BN} d RSA private exponent @param {BN} p RSA private prime p @param {BN} q RSA private prime q @param {BN} u RSA private inverse of prime q @returns {BN} RSA Plaintext @async
[ "Decrypt", "RSA", "message" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/crypto/public_key/rsa.js#L110-L140
7,433
openpgpjs/openpgpjs
src/crypto/public_key/rsa.js
async function(B, E) { let key; E = new BN(E, 16); const webCrypto = util.getWebCryptoAll(); // Native RSA keygen using Web Crypto if (webCrypto) { let keyPair; let keyGenOpt; if ((window.crypto && window.crypto.subtle) || window.msCrypto) { // current standard spec keyGenOpt = { name: 'RSASSA-PKCS1-v1_5', modulusLength: B, // the specified keysize in bits publicExponent: E.toArrayLike(Uint8Array), // take three bytes (max 65537) for exponent hash: { name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify' } }; keyPair = webCrypto.generateKey(keyGenOpt, true, ['sign', 'verify']); keyPair = await promisifyIE11Op(keyPair, 'Error generating RSA key pair.'); } else if (window.crypto && window.crypto.webkitSubtle) { // outdated spec implemented by old Webkit keyGenOpt = { name: 'RSA-OAEP', modulusLength: B, // the specified keysize in bits publicExponent: E.toArrayLike(Uint8Array), // take three bytes (max 65537) for exponent hash: { name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify' } }; keyPair = await webCrypto.generateKey(keyGenOpt, true, ['encrypt', 'decrypt']); } else { throw new Error('Unknown WebCrypto implementation'); } // export the generated keys as JsonWebKey (JWK) // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33 let jwk = webCrypto.exportKey('jwk', keyPair.privateKey); jwk = await promisifyIE11Op(jwk, 'Error exporting RSA key pair.'); // parse raw ArrayBuffer bytes to jwk/json (WebKit/Safari/IE11 quirk) if (jwk instanceof ArrayBuffer) { jwk = JSON.parse(String.fromCharCode.apply(null, new Uint8Array(jwk))); } // map JWK parameters to BN key = {}; key.n = new BN(util.b64_to_Uint8Array(jwk.n)); key.e = E; key.d = new BN(util.b64_to_Uint8Array(jwk.d)); key.p = new BN(util.b64_to_Uint8Array(jwk.p)); key.q = new BN(util.b64_to_Uint8Array(jwk.q)); key.u = key.p.invm(key.q); return key; } // RSA keygen fallback using 40 iterations of the Miller-Rabin test // See https://stackoverflow.com/a/6330138 for justification // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST let p = await prime.randomProbablePrime(B - (B >> 1), E, 40); let q = await prime.randomProbablePrime(B >> 1, E, 40); if (p.cmp(q) < 0) { [p, q] = [q, p]; } const phi = p.subn(1).mul(q.subn(1)); return { n: p.mul(q), e: E, d: E.invm(phi), p: p, q: q, // dp: d.mod(p.subn(1)), // dq: d.mod(q.subn(1)), u: p.invm(q) }; }
javascript
async function(B, E) { let key; E = new BN(E, 16); const webCrypto = util.getWebCryptoAll(); // Native RSA keygen using Web Crypto if (webCrypto) { let keyPair; let keyGenOpt; if ((window.crypto && window.crypto.subtle) || window.msCrypto) { // current standard spec keyGenOpt = { name: 'RSASSA-PKCS1-v1_5', modulusLength: B, // the specified keysize in bits publicExponent: E.toArrayLike(Uint8Array), // take three bytes (max 65537) for exponent hash: { name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify' } }; keyPair = webCrypto.generateKey(keyGenOpt, true, ['sign', 'verify']); keyPair = await promisifyIE11Op(keyPair, 'Error generating RSA key pair.'); } else if (window.crypto && window.crypto.webkitSubtle) { // outdated spec implemented by old Webkit keyGenOpt = { name: 'RSA-OAEP', modulusLength: B, // the specified keysize in bits publicExponent: E.toArrayLike(Uint8Array), // take three bytes (max 65537) for exponent hash: { name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify' } }; keyPair = await webCrypto.generateKey(keyGenOpt, true, ['encrypt', 'decrypt']); } else { throw new Error('Unknown WebCrypto implementation'); } // export the generated keys as JsonWebKey (JWK) // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33 let jwk = webCrypto.exportKey('jwk', keyPair.privateKey); jwk = await promisifyIE11Op(jwk, 'Error exporting RSA key pair.'); // parse raw ArrayBuffer bytes to jwk/json (WebKit/Safari/IE11 quirk) if (jwk instanceof ArrayBuffer) { jwk = JSON.parse(String.fromCharCode.apply(null, new Uint8Array(jwk))); } // map JWK parameters to BN key = {}; key.n = new BN(util.b64_to_Uint8Array(jwk.n)); key.e = E; key.d = new BN(util.b64_to_Uint8Array(jwk.d)); key.p = new BN(util.b64_to_Uint8Array(jwk.p)); key.q = new BN(util.b64_to_Uint8Array(jwk.q)); key.u = key.p.invm(key.q); return key; } // RSA keygen fallback using 40 iterations of the Miller-Rabin test // See https://stackoverflow.com/a/6330138 for justification // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST let p = await prime.randomProbablePrime(B - (B >> 1), E, 40); let q = await prime.randomProbablePrime(B >> 1, E, 40); if (p.cmp(q) < 0) { [p, q] = [q, p]; } const phi = p.subn(1).mul(q.subn(1)); return { n: p.mul(q), e: E, d: E.invm(phi), p: p, q: q, // dp: d.mod(p.subn(1)), // dq: d.mod(q.subn(1)), u: p.invm(q) }; }
[ "async", "function", "(", "B", ",", "E", ")", "{", "let", "key", ";", "E", "=", "new", "BN", "(", "E", ",", "16", ")", ";", "const", "webCrypto", "=", "util", ".", "getWebCryptoAll", "(", ")", ";", "// Native RSA keygen using Web Crypto", "if", "(", "webCrypto", ")", "{", "let", "keyPair", ";", "let", "keyGenOpt", ";", "if", "(", "(", "window", ".", "crypto", "&&", "window", ".", "crypto", ".", "subtle", ")", "||", "window", ".", "msCrypto", ")", "{", "// current standard spec", "keyGenOpt", "=", "{", "name", ":", "'RSASSA-PKCS1-v1_5'", ",", "modulusLength", ":", "B", ",", "// the specified keysize in bits", "publicExponent", ":", "E", ".", "toArrayLike", "(", "Uint8Array", ")", ",", "// take three bytes (max 65537) for exponent", "hash", ":", "{", "name", ":", "'SHA-1'", "// not required for actual RSA keys, but for crypto api 'sign' and 'verify'", "}", "}", ";", "keyPair", "=", "webCrypto", ".", "generateKey", "(", "keyGenOpt", ",", "true", ",", "[", "'sign'", ",", "'verify'", "]", ")", ";", "keyPair", "=", "await", "promisifyIE11Op", "(", "keyPair", ",", "'Error generating RSA key pair.'", ")", ";", "}", "else", "if", "(", "window", ".", "crypto", "&&", "window", ".", "crypto", ".", "webkitSubtle", ")", "{", "// outdated spec implemented by old Webkit", "keyGenOpt", "=", "{", "name", ":", "'RSA-OAEP'", ",", "modulusLength", ":", "B", ",", "// the specified keysize in bits", "publicExponent", ":", "E", ".", "toArrayLike", "(", "Uint8Array", ")", ",", "// take three bytes (max 65537) for exponent", "hash", ":", "{", "name", ":", "'SHA-1'", "// not required for actual RSA keys, but for crypto api 'sign' and 'verify'", "}", "}", ";", "keyPair", "=", "await", "webCrypto", ".", "generateKey", "(", "keyGenOpt", ",", "true", ",", "[", "'encrypt'", ",", "'decrypt'", "]", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Unknown WebCrypto implementation'", ")", ";", "}", "// export the generated keys as JsonWebKey (JWK)", "// https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33", "let", "jwk", "=", "webCrypto", ".", "exportKey", "(", "'jwk'", ",", "keyPair", ".", "privateKey", ")", ";", "jwk", "=", "await", "promisifyIE11Op", "(", "jwk", ",", "'Error exporting RSA key pair.'", ")", ";", "// parse raw ArrayBuffer bytes to jwk/json (WebKit/Safari/IE11 quirk)", "if", "(", "jwk", "instanceof", "ArrayBuffer", ")", "{", "jwk", "=", "JSON", ".", "parse", "(", "String", ".", "fromCharCode", ".", "apply", "(", "null", ",", "new", "Uint8Array", "(", "jwk", ")", ")", ")", ";", "}", "// map JWK parameters to BN", "key", "=", "{", "}", ";", "key", ".", "n", "=", "new", "BN", "(", "util", ".", "b64_to_Uint8Array", "(", "jwk", ".", "n", ")", ")", ";", "key", ".", "e", "=", "E", ";", "key", ".", "d", "=", "new", "BN", "(", "util", ".", "b64_to_Uint8Array", "(", "jwk", ".", "d", ")", ")", ";", "key", ".", "p", "=", "new", "BN", "(", "util", ".", "b64_to_Uint8Array", "(", "jwk", ".", "p", ")", ")", ";", "key", ".", "q", "=", "new", "BN", "(", "util", ".", "b64_to_Uint8Array", "(", "jwk", ".", "q", ")", ")", ";", "key", ".", "u", "=", "key", ".", "p", ".", "invm", "(", "key", ".", "q", ")", ";", "return", "key", ";", "}", "// RSA keygen fallback using 40 iterations of the Miller-Rabin test", "// See https://stackoverflow.com/a/6330138 for justification", "// Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST", "let", "p", "=", "await", "prime", ".", "randomProbablePrime", "(", "B", "-", "(", "B", ">>", "1", ")", ",", "E", ",", "40", ")", ";", "let", "q", "=", "await", "prime", ".", "randomProbablePrime", "(", "B", ">>", "1", ",", "E", ",", "40", ")", ";", "if", "(", "p", ".", "cmp", "(", "q", ")", "<", "0", ")", "{", "[", "p", ",", "q", "]", "=", "[", "q", ",", "p", "]", ";", "}", "const", "phi", "=", "p", ".", "subn", "(", "1", ")", ".", "mul", "(", "q", ".", "subn", "(", "1", ")", ")", ";", "return", "{", "n", ":", "p", ".", "mul", "(", "q", ")", ",", "e", ":", "E", ",", "d", ":", "E", ".", "invm", "(", "phi", ")", ",", "p", ":", "p", ",", "q", ":", "q", ",", "// dp: d.mod(p.subn(1)),", "// dq: d.mod(q.subn(1)),", "u", ":", "p", ".", "invm", "(", "q", ")", "}", ";", "}" ]
Generate a new random private key B bits long with public exponent E. When possible, webCrypto is used. Otherwise, primes are generated using 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm. @see module:crypto/public_key/prime @param {Integer} B RSA bit length @param {String} E RSA public exponent in hex string @returns {{n: BN, e: BN, d: BN, p: BN, q: BN, u: BN}} RSA public modulus, RSA public exponent, RSA private exponent, RSA private prime p, RSA private prime q, u = q ** -1 mod p @async
[ "Generate", "a", "new", "random", "private", "key", "B", "bits", "long", "with", "public", "exponent", "E", "." ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/crypto/public_key/rsa.js#L155-L233
7,434
openpgpjs/openpgpjs
src/crypto/cipher/des.js
DES
function DES(key) { this.key = key; this.encrypt = function(block, padding) { const keys = des_createKeys(this.key); return des(keys, block, true, 0, null, padding); }; this.decrypt = function(block, padding) { const keys = des_createKeys(this.key); return des(keys, block, false, 0, null, padding); }; }
javascript
function DES(key) { this.key = key; this.encrypt = function(block, padding) { const keys = des_createKeys(this.key); return des(keys, block, true, 0, null, padding); }; this.decrypt = function(block, padding) { const keys = des_createKeys(this.key); return des(keys, block, false, 0, null, padding); }; }
[ "function", "DES", "(", "key", ")", "{", "this", ".", "key", "=", "key", ";", "this", ".", "encrypt", "=", "function", "(", "block", ",", "padding", ")", "{", "const", "keys", "=", "des_createKeys", "(", "this", ".", "key", ")", ";", "return", "des", "(", "keys", ",", "block", ",", "true", ",", "0", ",", "null", ",", "padding", ")", ";", "}", ";", "this", ".", "decrypt", "=", "function", "(", "block", ",", "padding", ")", "{", "const", "keys", "=", "des_createKeys", "(", "this", ".", "key", ")", ";", "return", "des", "(", "keys", ",", "block", ",", "false", ",", "0", ",", "null", ",", "padding", ")", ";", "}", ";", "}" ]
This is "original" DES
[ "This", "is", "original", "DES" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/crypto/cipher/des.js#L462-L474
7,435
openpgpjs/openpgpjs
src/crypto/crypto.js
function(algo) { switch (algo) { // Algorithm-Specific Fields for RSA secret keys: // - multiprecision integer (MPI) of RSA secret exponent d. // - MPI of RSA secret prime value p. // - MPI of RSA secret prime value q (p < q). // - MPI of u, the multiplicative inverse of p, mod q. case enums.publicKey.rsa_encrypt: case enums.publicKey.rsa_encrypt_sign: case enums.publicKey.rsa_sign: return [type_mpi, type_mpi, type_mpi, type_mpi]; // Algorithm-Specific Fields for Elgamal secret keys: // - MPI of Elgamal secret exponent x. case enums.publicKey.elgamal: return [type_mpi]; // Algorithm-Specific Fields for DSA secret keys: // - MPI of DSA secret exponent x. case enums.publicKey.dsa: return [type_mpi]; // Algorithm-Specific Fields for ECDSA or ECDH secret keys: // - MPI of an integer representing the secret key. case enums.publicKey.ecdh: case enums.publicKey.ecdsa: case enums.publicKey.eddsa: return [type_mpi]; default: throw new Error('Invalid public key encryption algorithm.'); } }
javascript
function(algo) { switch (algo) { // Algorithm-Specific Fields for RSA secret keys: // - multiprecision integer (MPI) of RSA secret exponent d. // - MPI of RSA secret prime value p. // - MPI of RSA secret prime value q (p < q). // - MPI of u, the multiplicative inverse of p, mod q. case enums.publicKey.rsa_encrypt: case enums.publicKey.rsa_encrypt_sign: case enums.publicKey.rsa_sign: return [type_mpi, type_mpi, type_mpi, type_mpi]; // Algorithm-Specific Fields for Elgamal secret keys: // - MPI of Elgamal secret exponent x. case enums.publicKey.elgamal: return [type_mpi]; // Algorithm-Specific Fields for DSA secret keys: // - MPI of DSA secret exponent x. case enums.publicKey.dsa: return [type_mpi]; // Algorithm-Specific Fields for ECDSA or ECDH secret keys: // - MPI of an integer representing the secret key. case enums.publicKey.ecdh: case enums.publicKey.ecdsa: case enums.publicKey.eddsa: return [type_mpi]; default: throw new Error('Invalid public key encryption algorithm.'); } }
[ "function", "(", "algo", ")", "{", "switch", "(", "algo", ")", "{", "// Algorithm-Specific Fields for RSA secret keys:", "// - multiprecision integer (MPI) of RSA secret exponent d.", "// - MPI of RSA secret prime value p.", "// - MPI of RSA secret prime value q (p < q).", "// - MPI of u, the multiplicative inverse of p, mod q.", "case", "enums", ".", "publicKey", ".", "rsa_encrypt", ":", "case", "enums", ".", "publicKey", ".", "rsa_encrypt_sign", ":", "case", "enums", ".", "publicKey", ".", "rsa_sign", ":", "return", "[", "type_mpi", ",", "type_mpi", ",", "type_mpi", ",", "type_mpi", "]", ";", "// Algorithm-Specific Fields for Elgamal secret keys:", "// - MPI of Elgamal secret exponent x.", "case", "enums", ".", "publicKey", ".", "elgamal", ":", "return", "[", "type_mpi", "]", ";", "// Algorithm-Specific Fields for DSA secret keys:", "// - MPI of DSA secret exponent x.", "case", "enums", ".", "publicKey", ".", "dsa", ":", "return", "[", "type_mpi", "]", ";", "// Algorithm-Specific Fields for ECDSA or ECDH secret keys:", "// - MPI of an integer representing the secret key.", "case", "enums", ".", "publicKey", ".", "ecdh", ":", "case", "enums", ".", "publicKey", ".", "ecdsa", ":", "case", "enums", ".", "publicKey", ".", "eddsa", ":", "return", "[", "type_mpi", "]", ";", "default", ":", "throw", "new", "Error", "(", "'Invalid public key encryption algorithm.'", ")", ";", "}", "}" ]
Returns the types comprising the private key of an algorithm @param {String} algo The public key algorithm @returns {Array<String>} The array of types
[ "Returns", "the", "types", "comprising", "the", "private", "key", "of", "an", "algorithm" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/crypto/crypto.js#L154-L182
7,436
openpgpjs/openpgpjs
src/crypto/crypto.js
function(algo) { switch (algo) { // Algorithm-Specific Fields for RSA encrypted session keys: // - MPI of RSA encrypted value m**e mod n. case enums.publicKey.rsa_encrypt: case enums.publicKey.rsa_encrypt_sign: return [type_mpi]; // Algorithm-Specific Fields for Elgamal encrypted session keys: // - MPI of Elgamal value g**k mod p // - MPI of Elgamal value m * y**k mod p case enums.publicKey.elgamal: return [type_mpi, type_mpi]; // Algorithm-Specific Fields for ECDH encrypted session keys: // - MPI containing the ephemeral key used to establish the shared secret // - ECDH Symmetric Key case enums.publicKey.ecdh: return [type_mpi, type_ecdh_symkey]; default: throw new Error('Invalid public key encryption algorithm.'); } }
javascript
function(algo) { switch (algo) { // Algorithm-Specific Fields for RSA encrypted session keys: // - MPI of RSA encrypted value m**e mod n. case enums.publicKey.rsa_encrypt: case enums.publicKey.rsa_encrypt_sign: return [type_mpi]; // Algorithm-Specific Fields for Elgamal encrypted session keys: // - MPI of Elgamal value g**k mod p // - MPI of Elgamal value m * y**k mod p case enums.publicKey.elgamal: return [type_mpi, type_mpi]; // Algorithm-Specific Fields for ECDH encrypted session keys: // - MPI containing the ephemeral key used to establish the shared secret // - ECDH Symmetric Key case enums.publicKey.ecdh: return [type_mpi, type_ecdh_symkey]; default: throw new Error('Invalid public key encryption algorithm.'); } }
[ "function", "(", "algo", ")", "{", "switch", "(", "algo", ")", "{", "// Algorithm-Specific Fields for RSA encrypted session keys:", "// - MPI of RSA encrypted value m**e mod n.", "case", "enums", ".", "publicKey", ".", "rsa_encrypt", ":", "case", "enums", ".", "publicKey", ".", "rsa_encrypt_sign", ":", "return", "[", "type_mpi", "]", ";", "// Algorithm-Specific Fields for Elgamal encrypted session keys:", "// - MPI of Elgamal value g**k mod p", "// - MPI of Elgamal value m * y**k mod p", "case", "enums", ".", "publicKey", ".", "elgamal", ":", "return", "[", "type_mpi", ",", "type_mpi", "]", ";", "// Algorithm-Specific Fields for ECDH encrypted session keys:", "// - MPI containing the ephemeral key used to establish the shared secret", "// - ECDH Symmetric Key", "case", "enums", ".", "publicKey", ".", "ecdh", ":", "return", "[", "type_mpi", ",", "type_ecdh_symkey", "]", ";", "default", ":", "throw", "new", "Error", "(", "'Invalid public key encryption algorithm.'", ")", ";", "}", "}" ]
Returns the types comprising the encrypted session key of an algorithm @param {String} algo The public key algorithm @returns {Array<String>} The array of types
[ "Returns", "the", "types", "comprising", "the", "encrypted", "session", "key", "of", "an", "algorithm" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/crypto/crypto.js#L231-L252
7,437
openpgpjs/openpgpjs
src/crypto/crypto.js
function(algo, bits, oid) { const types = [].concat(this.getPubKeyParamTypes(algo), this.getPrivKeyParamTypes(algo)); switch (algo) { case enums.publicKey.rsa_encrypt: case enums.publicKey.rsa_encrypt_sign: case enums.publicKey.rsa_sign: { return publicKey.rsa.generate(bits, "10001").then(function(keyObject) { return constructParams( types, [keyObject.n, keyObject.e, keyObject.d, keyObject.p, keyObject.q, keyObject.u] ); }); } case enums.publicKey.dsa: case enums.publicKey.elgamal: throw new Error('Unsupported algorithm for key generation.'); case enums.publicKey.ecdsa: case enums.publicKey.eddsa: return publicKey.elliptic.generate(oid).then(function (keyObject) { return constructParams(types, [keyObject.oid, keyObject.Q, keyObject.d]); }); case enums.publicKey.ecdh: return publicKey.elliptic.generate(oid).then(function (keyObject) { return constructParams(types, [keyObject.oid, keyObject.Q, [keyObject.hash, keyObject.cipher], keyObject.d]); }); default: throw new Error('Invalid public key algorithm.'); } }
javascript
function(algo, bits, oid) { const types = [].concat(this.getPubKeyParamTypes(algo), this.getPrivKeyParamTypes(algo)); switch (algo) { case enums.publicKey.rsa_encrypt: case enums.publicKey.rsa_encrypt_sign: case enums.publicKey.rsa_sign: { return publicKey.rsa.generate(bits, "10001").then(function(keyObject) { return constructParams( types, [keyObject.n, keyObject.e, keyObject.d, keyObject.p, keyObject.q, keyObject.u] ); }); } case enums.publicKey.dsa: case enums.publicKey.elgamal: throw new Error('Unsupported algorithm for key generation.'); case enums.publicKey.ecdsa: case enums.publicKey.eddsa: return publicKey.elliptic.generate(oid).then(function (keyObject) { return constructParams(types, [keyObject.oid, keyObject.Q, keyObject.d]); }); case enums.publicKey.ecdh: return publicKey.elliptic.generate(oid).then(function (keyObject) { return constructParams(types, [keyObject.oid, keyObject.Q, [keyObject.hash, keyObject.cipher], keyObject.d]); }); default: throw new Error('Invalid public key algorithm.'); } }
[ "function", "(", "algo", ",", "bits", ",", "oid", ")", "{", "const", "types", "=", "[", "]", ".", "concat", "(", "this", ".", "getPubKeyParamTypes", "(", "algo", ")", ",", "this", ".", "getPrivKeyParamTypes", "(", "algo", ")", ")", ";", "switch", "(", "algo", ")", "{", "case", "enums", ".", "publicKey", ".", "rsa_encrypt", ":", "case", "enums", ".", "publicKey", ".", "rsa_encrypt_sign", ":", "case", "enums", ".", "publicKey", ".", "rsa_sign", ":", "{", "return", "publicKey", ".", "rsa", ".", "generate", "(", "bits", ",", "\"10001\"", ")", ".", "then", "(", "function", "(", "keyObject", ")", "{", "return", "constructParams", "(", "types", ",", "[", "keyObject", ".", "n", ",", "keyObject", ".", "e", ",", "keyObject", ".", "d", ",", "keyObject", ".", "p", ",", "keyObject", ".", "q", ",", "keyObject", ".", "u", "]", ")", ";", "}", ")", ";", "}", "case", "enums", ".", "publicKey", ".", "dsa", ":", "case", "enums", ".", "publicKey", ".", "elgamal", ":", "throw", "new", "Error", "(", "'Unsupported algorithm for key generation.'", ")", ";", "case", "enums", ".", "publicKey", ".", "ecdsa", ":", "case", "enums", ".", "publicKey", ".", "eddsa", ":", "return", "publicKey", ".", "elliptic", ".", "generate", "(", "oid", ")", ".", "then", "(", "function", "(", "keyObject", ")", "{", "return", "constructParams", "(", "types", ",", "[", "keyObject", ".", "oid", ",", "keyObject", ".", "Q", ",", "keyObject", ".", "d", "]", ")", ";", "}", ")", ";", "case", "enums", ".", "publicKey", ".", "ecdh", ":", "return", "publicKey", ".", "elliptic", ".", "generate", "(", "oid", ")", ".", "then", "(", "function", "(", "keyObject", ")", "{", "return", "constructParams", "(", "types", ",", "[", "keyObject", ".", "oid", ",", "keyObject", ".", "Q", ",", "[", "keyObject", ".", "hash", ",", "keyObject", ".", "cipher", "]", ",", "keyObject", ".", "d", "]", ")", ";", "}", ")", ";", "default", ":", "throw", "new", "Error", "(", "'Invalid public key algorithm.'", ")", ";", "}", "}" ]
Generate algorithm-specific key parameters @param {String} algo The public key algorithm @param {Integer} bits Bit length for RSA keys @param {module:type/oid} oid Object identifier for ECC keys @returns {Array} The array of parameters @async
[ "Generate", "algorithm", "-", "specific", "key", "parameters" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/crypto/crypto.js#L261-L288
7,438
openpgpjs/openpgpjs
src/crypto/eax.js
async function(plaintext, nonce, adata) { const [ omacNonce, omacAdata ] = await Promise.all([ omac(zero, nonce), omac(one, adata) ]); const ciphered = await ctr(plaintext, omacNonce); const omacCiphered = await omac(two, ciphered); const tag = omacCiphered; // Assumes that omac(*).length === tagLength. for (let i = 0; i < tagLength; i++) { tag[i] ^= omacAdata[i] ^ omacNonce[i]; } return util.concatUint8Array([ciphered, tag]); }
javascript
async function(plaintext, nonce, adata) { const [ omacNonce, omacAdata ] = await Promise.all([ omac(zero, nonce), omac(one, adata) ]); const ciphered = await ctr(plaintext, omacNonce); const omacCiphered = await omac(two, ciphered); const tag = omacCiphered; // Assumes that omac(*).length === tagLength. for (let i = 0; i < tagLength; i++) { tag[i] ^= omacAdata[i] ^ omacNonce[i]; } return util.concatUint8Array([ciphered, tag]); }
[ "async", "function", "(", "plaintext", ",", "nonce", ",", "adata", ")", "{", "const", "[", "omacNonce", ",", "omacAdata", "]", "=", "await", "Promise", ".", "all", "(", "[", "omac", "(", "zero", ",", "nonce", ")", ",", "omac", "(", "one", ",", "adata", ")", "]", ")", ";", "const", "ciphered", "=", "await", "ctr", "(", "plaintext", ",", "omacNonce", ")", ";", "const", "omacCiphered", "=", "await", "omac", "(", "two", ",", "ciphered", ")", ";", "const", "tag", "=", "omacCiphered", ";", "// Assumes that omac(*).length === tagLength.", "for", "(", "let", "i", "=", "0", ";", "i", "<", "tagLength", ";", "i", "++", ")", "{", "tag", "[", "i", "]", "^=", "omacAdata", "[", "i", "]", "^", "omacNonce", "[", "i", "]", ";", "}", "return", "util", ".", "concatUint8Array", "(", "[", "ciphered", ",", "tag", "]", ")", ";", "}" ]
Encrypt plaintext input. @param {Uint8Array} plaintext The cleartext input to be encrypted @param {Uint8Array} nonce The nonce (16 bytes) @param {Uint8Array} adata Associated data to sign @returns {Promise<Uint8Array>} The ciphertext output
[ "Encrypt", "plaintext", "input", "." ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/crypto/eax.js#L106-L121
7,439
openpgpjs/openpgpjs
src/worker/worker.js
randomCallback
function randomCallback() { if (!randomQueue.length) { self.postMessage({ event: 'request-seed', amount: MAX_SIZE_RANDOM_BUFFER }); } return new Promise(function(resolve) { randomQueue.push(resolve); }); }
javascript
function randomCallback() { if (!randomQueue.length) { self.postMessage({ event: 'request-seed', amount: MAX_SIZE_RANDOM_BUFFER }); } return new Promise(function(resolve) { randomQueue.push(resolve); }); }
[ "function", "randomCallback", "(", ")", "{", "if", "(", "!", "randomQueue", ".", "length", ")", "{", "self", ".", "postMessage", "(", "{", "event", ":", "'request-seed'", ",", "amount", ":", "MAX_SIZE_RANDOM_BUFFER", "}", ")", ";", "}", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "randomQueue", ".", "push", "(", "resolve", ")", ";", "}", ")", ";", "}" ]
Handle random buffer exhaustion by requesting more random bytes from the main window @returns {Promise<Object>} Empty promise whose resolution indicates that the buffer has been refilled
[ "Handle", "random", "buffer", "exhaustion", "by", "requesting", "more", "random", "bytes", "from", "the", "main", "window" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/worker/worker.js#L43-L52
7,440
openpgpjs/openpgpjs
src/worker/worker.js
configure
function configure(config) { Object.keys(config).forEach(function(key) { openpgp.config[key] = config[key]; }); }
javascript
function configure(config) { Object.keys(config).forEach(function(key) { openpgp.config[key] = config[key]; }); }
[ "function", "configure", "(", "config", ")", "{", "Object", ".", "keys", "(", "config", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "openpgp", ".", "config", "[", "key", "]", "=", "config", "[", "key", "]", ";", "}", ")", ";", "}" ]
Set config from main context to worker context. @param {Object} config The openpgp configuration
[ "Set", "config", "from", "main", "context", "to", "worker", "context", "." ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/worker/worker.js#L88-L92
7,441
openpgpjs/openpgpjs
src/worker/worker.js
seedRandom
function seedRandom(buffer) { if (!(buffer instanceof Uint8Array)) { buffer = new Uint8Array(buffer); } openpgp.crypto.random.randomBuffer.set(buffer); }
javascript
function seedRandom(buffer) { if (!(buffer instanceof Uint8Array)) { buffer = new Uint8Array(buffer); } openpgp.crypto.random.randomBuffer.set(buffer); }
[ "function", "seedRandom", "(", "buffer", ")", "{", "if", "(", "!", "(", "buffer", "instanceof", "Uint8Array", ")", ")", "{", "buffer", "=", "new", "Uint8Array", "(", "buffer", ")", ";", "}", "openpgp", ".", "crypto", ".", "random", ".", "randomBuffer", ".", "set", "(", "buffer", ")", ";", "}" ]
Seed the library with entropy gathered window.crypto.getRandomValues as this api is only avalible in the main window. @param {ArrayBuffer} buffer Some random bytes
[ "Seed", "the", "library", "with", "entropy", "gathered", "window", ".", "crypto", ".", "getRandomValues", "as", "this", "api", "is", "only", "avalible", "in", "the", "main", "window", "." ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/worker/worker.js#L99-L104
7,442
openpgpjs/openpgpjs
src/worker/worker.js
delegate
function delegate(id, method, options) { if (typeof openpgp[method] !== 'function') { response({ id:id, event:'method-return', err:'Unknown Worker Event' }); return; } // construct ReadableStreams from MessagePorts openpgp.util.restoreStreams(options); // parse cloned packets options = openpgp.packet.clone.parseClonedPackets(options, method); openpgp[method](options).then(function(data) { // clone packets (for web worker structured cloning algorithm) response({ id:id, event:'method-return', data:openpgp.packet.clone.clonePackets(data) }); }).catch(function(e) { openpgp.util.print_debug_error(e); response({ id:id, event:'method-return', err:e.message, stack:e.stack }); }); }
javascript
function delegate(id, method, options) { if (typeof openpgp[method] !== 'function') { response({ id:id, event:'method-return', err:'Unknown Worker Event' }); return; } // construct ReadableStreams from MessagePorts openpgp.util.restoreStreams(options); // parse cloned packets options = openpgp.packet.clone.parseClonedPackets(options, method); openpgp[method](options).then(function(data) { // clone packets (for web worker structured cloning algorithm) response({ id:id, event:'method-return', data:openpgp.packet.clone.clonePackets(data) }); }).catch(function(e) { openpgp.util.print_debug_error(e); response({ id:id, event:'method-return', err:e.message, stack:e.stack }); }); }
[ "function", "delegate", "(", "id", ",", "method", ",", "options", ")", "{", "if", "(", "typeof", "openpgp", "[", "method", "]", "!==", "'function'", ")", "{", "response", "(", "{", "id", ":", "id", ",", "event", ":", "'method-return'", ",", "err", ":", "'Unknown Worker Event'", "}", ")", ";", "return", ";", "}", "// construct ReadableStreams from MessagePorts", "openpgp", ".", "util", ".", "restoreStreams", "(", "options", ")", ";", "// parse cloned packets", "options", "=", "openpgp", ".", "packet", ".", "clone", ".", "parseClonedPackets", "(", "options", ",", "method", ")", ";", "openpgp", "[", "method", "]", "(", "options", ")", ".", "then", "(", "function", "(", "data", ")", "{", "// clone packets (for web worker structured cloning algorithm)", "response", "(", "{", "id", ":", "id", ",", "event", ":", "'method-return'", ",", "data", ":", "openpgp", ".", "packet", ".", "clone", ".", "clonePackets", "(", "data", ")", "}", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "e", ")", "{", "openpgp", ".", "util", ".", "print_debug_error", "(", "e", ")", ";", "response", "(", "{", "id", ":", "id", ",", "event", ":", "'method-return'", ",", "err", ":", "e", ".", "message", ",", "stack", ":", "e", ".", "stack", "}", ")", ";", "}", ")", ";", "}" ]
Generic proxy function that handles all commands from the public api. @param {String} method The public api function to be delegated to the worker thread @param {Object} options The api function's options
[ "Generic", "proxy", "function", "that", "handles", "all", "commands", "from", "the", "public", "api", "." ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/worker/worker.js#L111-L129
7,443
openpgpjs/openpgpjs
src/worker/worker.js
response
function response(event) { self.postMessage(event, openpgp.util.getTransferables(event.data, true)); }
javascript
function response(event) { self.postMessage(event, openpgp.util.getTransferables(event.data, true)); }
[ "function", "response", "(", "event", ")", "{", "self", ".", "postMessage", "(", "event", ",", "openpgp", ".", "util", ".", "getTransferables", "(", "event", ".", "data", ",", "true", ")", ")", ";", "}" ]
Respond to the main window. @param {Object} event Contains event type and data
[ "Respond", "to", "the", "main", "window", "." ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/worker/worker.js#L135-L137
7,444
openpgpjs/openpgpjs
src/keyring/localstore.js
LocalStore
function LocalStore(prefix) { prefix = prefix || 'openpgp-'; this.publicKeysItem = prefix + this.publicKeysItem; this.privateKeysItem = prefix + this.privateKeysItem; if (typeof window !== 'undefined' && window.localStorage) { this.storage = window.localStorage; } else { this.storage = new (require('node-localstorage').LocalStorage)(config.node_store); } }
javascript
function LocalStore(prefix) { prefix = prefix || 'openpgp-'; this.publicKeysItem = prefix + this.publicKeysItem; this.privateKeysItem = prefix + this.privateKeysItem; if (typeof window !== 'undefined' && window.localStorage) { this.storage = window.localStorage; } else { this.storage = new (require('node-localstorage').LocalStorage)(config.node_store); } }
[ "function", "LocalStore", "(", "prefix", ")", "{", "prefix", "=", "prefix", "||", "'openpgp-'", ";", "this", ".", "publicKeysItem", "=", "prefix", "+", "this", ".", "publicKeysItem", ";", "this", ".", "privateKeysItem", "=", "prefix", "+", "this", ".", "privateKeysItem", ";", "if", "(", "typeof", "window", "!==", "'undefined'", "&&", "window", ".", "localStorage", ")", "{", "this", ".", "storage", "=", "window", ".", "localStorage", ";", "}", "else", "{", "this", ".", "storage", "=", "new", "(", "require", "(", "'node-localstorage'", ")", ".", "LocalStorage", ")", "(", "config", ".", "node_store", ")", ";", "}", "}" ]
The class that deals with storage of the keyring. Currently the only option is to use HTML5 local storage. @constructor @param {String} prefix prefix for itemnames in localstore
[ "The", "class", "that", "deals", "with", "storage", "of", "the", "keyring", ".", "Currently", "the", "only", "option", "is", "to", "use", "HTML5", "local", "storage", "." ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/keyring/localstore.js#L38-L47
7,445
openpgpjs/openpgpjs
src/hkp.js
HKP
function HKP(keyServerBaseUrl) { this._baseUrl = keyServerBaseUrl || config.keyserver; this._fetch = typeof window !== 'undefined' ? window.fetch : require('node-fetch'); }
javascript
function HKP(keyServerBaseUrl) { this._baseUrl = keyServerBaseUrl || config.keyserver; this._fetch = typeof window !== 'undefined' ? window.fetch : require('node-fetch'); }
[ "function", "HKP", "(", "keyServerBaseUrl", ")", "{", "this", ".", "_baseUrl", "=", "keyServerBaseUrl", "||", "config", ".", "keyserver", ";", "this", ".", "_fetch", "=", "typeof", "window", "!==", "'undefined'", "?", "window", ".", "fetch", ":", "require", "(", "'node-fetch'", ")", ";", "}" ]
Initialize the HKP client and configure it with the key server url and fetch function. @constructor @param {String} keyServerBaseUrl (optional) The HKP key server base url including the protocol to use, e.g. 'https://pgp.mit.edu'; defaults to openpgp.config.keyserver (https://keyserver.ubuntu.com)
[ "Initialize", "the", "HKP", "client", "and", "configure", "it", "with", "the", "key", "server", "url", "and", "fetch", "function", "." ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/hkp.js#L33-L36
7,446
openpgpjs/openpgpjs
src/crypto/pkcs1.js
getPkcs1Padding
async function getPkcs1Padding(length) { let result = ''; while (result.length < length) { const randomBytes = await random.getRandomBytes(length - result.length); for (let i = 0; i < randomBytes.length; i++) { if (randomBytes[i] !== 0) { result += String.fromCharCode(randomBytes[i]); } } } return result; }
javascript
async function getPkcs1Padding(length) { let result = ''; while (result.length < length) { const randomBytes = await random.getRandomBytes(length - result.length); for (let i = 0; i < randomBytes.length; i++) { if (randomBytes[i] !== 0) { result += String.fromCharCode(randomBytes[i]); } } } return result; }
[ "async", "function", "getPkcs1Padding", "(", "length", ")", "{", "let", "result", "=", "''", ";", "while", "(", "result", ".", "length", "<", "length", ")", "{", "const", "randomBytes", "=", "await", "random", ".", "getRandomBytes", "(", "length", "-", "result", ".", "length", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "randomBytes", ".", "length", ";", "i", "++", ")", "{", "if", "(", "randomBytes", "[", "i", "]", "!==", "0", ")", "{", "result", "+=", "String", ".", "fromCharCode", "(", "randomBytes", "[", "i", "]", ")", ";", "}", "}", "}", "return", "result", ";", "}" ]
Create padding with secure random data @private @param {Integer} length Length of the padding in bytes @returns {String} Padding as string @async
[ "Create", "padding", "with", "secure", "random", "data" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/crypto/pkcs1.js#L63-L74
7,447
openpgpjs/openpgpjs
src/crypto/random.js
async function(length) { const buf = new Uint8Array(length); if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) { window.crypto.getRandomValues(buf); } else if (typeof window !== 'undefined' && typeof window.msCrypto === 'object' && typeof window.msCrypto.getRandomValues === 'function') { window.msCrypto.getRandomValues(buf); } else if (nodeCrypto) { const bytes = nodeCrypto.randomBytes(buf.length); buf.set(bytes); } else if (this.randomBuffer.buffer) { await this.randomBuffer.get(buf); } else { throw new Error('No secure random number generator available.'); } return buf; }
javascript
async function(length) { const buf = new Uint8Array(length); if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) { window.crypto.getRandomValues(buf); } else if (typeof window !== 'undefined' && typeof window.msCrypto === 'object' && typeof window.msCrypto.getRandomValues === 'function') { window.msCrypto.getRandomValues(buf); } else if (nodeCrypto) { const bytes = nodeCrypto.randomBytes(buf.length); buf.set(bytes); } else if (this.randomBuffer.buffer) { await this.randomBuffer.get(buf); } else { throw new Error('No secure random number generator available.'); } return buf; }
[ "async", "function", "(", "length", ")", "{", "const", "buf", "=", "new", "Uint8Array", "(", "length", ")", ";", "if", "(", "typeof", "window", "!==", "'undefined'", "&&", "window", ".", "crypto", "&&", "window", ".", "crypto", ".", "getRandomValues", ")", "{", "window", ".", "crypto", ".", "getRandomValues", "(", "buf", ")", ";", "}", "else", "if", "(", "typeof", "window", "!==", "'undefined'", "&&", "typeof", "window", ".", "msCrypto", "===", "'object'", "&&", "typeof", "window", ".", "msCrypto", ".", "getRandomValues", "===", "'function'", ")", "{", "window", ".", "msCrypto", ".", "getRandomValues", "(", "buf", ")", ";", "}", "else", "if", "(", "nodeCrypto", ")", "{", "const", "bytes", "=", "nodeCrypto", ".", "randomBytes", "(", "buf", ".", "length", ")", ";", "buf", ".", "set", "(", "bytes", ")", ";", "}", "else", "if", "(", "this", ".", "randomBuffer", ".", "buffer", ")", "{", "await", "this", ".", "randomBuffer", ".", "get", "(", "buf", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'No secure random number generator available.'", ")", ";", "}", "return", "buf", ";", "}" ]
Retrieve secure random byte array of the specified length @param {Integer} length Length in bytes to generate @returns {Uint8Array} Random byte array @async
[ "Retrieve", "secure", "random", "byte", "array", "of", "the", "specified", "length" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/crypto/random.js#L40-L55
7,448
openpgpjs/openpgpjs
src/crypto/random.js
async function(min, max) { if (max.cmp(min) <= 0) { throw new Error('Illegal parameter value: max <= min'); } const modulus = max.sub(min); const bytes = modulus.byteLength(); // Using a while loop is necessary to avoid bias introduced by the mod operation. // However, we request 64 extra random bits so that the bias is negligible. // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf const r = new BN(await this.getRandomBytes(bytes + 8)); return r.mod(modulus).add(min); }
javascript
async function(min, max) { if (max.cmp(min) <= 0) { throw new Error('Illegal parameter value: max <= min'); } const modulus = max.sub(min); const bytes = modulus.byteLength(); // Using a while loop is necessary to avoid bias introduced by the mod operation. // However, we request 64 extra random bits so that the bias is negligible. // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf const r = new BN(await this.getRandomBytes(bytes + 8)); return r.mod(modulus).add(min); }
[ "async", "function", "(", "min", ",", "max", ")", "{", "if", "(", "max", ".", "cmp", "(", "min", ")", "<=", "0", ")", "{", "throw", "new", "Error", "(", "'Illegal parameter value: max <= min'", ")", ";", "}", "const", "modulus", "=", "max", ".", "sub", "(", "min", ")", ";", "const", "bytes", "=", "modulus", ".", "byteLength", "(", ")", ";", "// Using a while loop is necessary to avoid bias introduced by the mod operation.", "// However, we request 64 extra random bits so that the bias is negligible.", "// Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf", "const", "r", "=", "new", "BN", "(", "await", "this", ".", "getRandomBytes", "(", "bytes", "+", "8", ")", ")", ";", "return", "r", ".", "mod", "(", "modulus", ")", ".", "add", "(", "min", ")", ";", "}" ]
Create a secure random MPI that is greater than or equal to min and less than max. @param {module:type/mpi} min Lower bound, included @param {module:type/mpi} max Upper bound, excluded @returns {module:BN} Random MPI @async
[ "Create", "a", "secure", "random", "MPI", "that", "is", "greater", "than", "or", "equal", "to", "min", "and", "less", "than", "max", "." ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/crypto/random.js#L64-L77
7,449
openpgpjs/openpgpjs
src/cleartext.js
verifyHeaders
function verifyHeaders(headers, packetlist) { const checkHashAlgos = function(hashAlgos) { const check = packet => algo => packet.hashAlgorithm === algo; for (let i = 0; i < packetlist.length; i++) { if (packetlist[i].tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) { return false; } } return true; }; let oneHeader = null; let hashAlgos = []; headers.forEach(function(header) { oneHeader = header.match(/Hash: (.+)/); // get header value if (oneHeader) { oneHeader = oneHeader[1].replace(/\s/g, ''); // remove whitespace oneHeader = oneHeader.split(','); oneHeader = oneHeader.map(function(hash) { hash = hash.toLowerCase(); try { return enums.write(enums.hash, hash); } catch (e) { throw new Error('Unknown hash algorithm in armor header: ' + hash); } }); hashAlgos = hashAlgos.concat(oneHeader); } else { throw new Error('Only "Hash" header allowed in cleartext signed message'); } }); if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) { throw new Error('If no "Hash" header in cleartext signed message, then only MD5 signatures allowed'); } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) { throw new Error('Hash algorithm mismatch in armor header and signature'); } }
javascript
function verifyHeaders(headers, packetlist) { const checkHashAlgos = function(hashAlgos) { const check = packet => algo => packet.hashAlgorithm === algo; for (let i = 0; i < packetlist.length; i++) { if (packetlist[i].tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) { return false; } } return true; }; let oneHeader = null; let hashAlgos = []; headers.forEach(function(header) { oneHeader = header.match(/Hash: (.+)/); // get header value if (oneHeader) { oneHeader = oneHeader[1].replace(/\s/g, ''); // remove whitespace oneHeader = oneHeader.split(','); oneHeader = oneHeader.map(function(hash) { hash = hash.toLowerCase(); try { return enums.write(enums.hash, hash); } catch (e) { throw new Error('Unknown hash algorithm in armor header: ' + hash); } }); hashAlgos = hashAlgos.concat(oneHeader); } else { throw new Error('Only "Hash" header allowed in cleartext signed message'); } }); if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) { throw new Error('If no "Hash" header in cleartext signed message, then only MD5 signatures allowed'); } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) { throw new Error('Hash algorithm mismatch in armor header and signature'); } }
[ "function", "verifyHeaders", "(", "headers", ",", "packetlist", ")", "{", "const", "checkHashAlgos", "=", "function", "(", "hashAlgos", ")", "{", "const", "check", "=", "packet", "=>", "algo", "=>", "packet", ".", "hashAlgorithm", "===", "algo", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "packetlist", ".", "length", ";", "i", "++", ")", "{", "if", "(", "packetlist", "[", "i", "]", ".", "tag", "===", "enums", ".", "packet", ".", "signature", "&&", "!", "hashAlgos", ".", "some", "(", "check", "(", "packetlist", "[", "i", "]", ")", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", ";", "let", "oneHeader", "=", "null", ";", "let", "hashAlgos", "=", "[", "]", ";", "headers", ".", "forEach", "(", "function", "(", "header", ")", "{", "oneHeader", "=", "header", ".", "match", "(", "/", "Hash: (.+)", "/", ")", ";", "// get header value", "if", "(", "oneHeader", ")", "{", "oneHeader", "=", "oneHeader", "[", "1", "]", ".", "replace", "(", "/", "\\s", "/", "g", ",", "''", ")", ";", "// remove whitespace", "oneHeader", "=", "oneHeader", ".", "split", "(", "','", ")", ";", "oneHeader", "=", "oneHeader", ".", "map", "(", "function", "(", "hash", ")", "{", "hash", "=", "hash", ".", "toLowerCase", "(", ")", ";", "try", "{", "return", "enums", ".", "write", "(", "enums", ".", "hash", ",", "hash", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "Error", "(", "'Unknown hash algorithm in armor header: '", "+", "hash", ")", ";", "}", "}", ")", ";", "hashAlgos", "=", "hashAlgos", ".", "concat", "(", "oneHeader", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Only \"Hash\" header allowed in cleartext signed message'", ")", ";", "}", "}", ")", ";", "if", "(", "!", "hashAlgos", ".", "length", "&&", "!", "checkHashAlgos", "(", "[", "enums", ".", "hash", ".", "md5", "]", ")", ")", "{", "throw", "new", "Error", "(", "'If no \"Hash\" header in cleartext signed message, then only MD5 signatures allowed'", ")", ";", "}", "else", "if", "(", "hashAlgos", ".", "length", "&&", "!", "checkHashAlgos", "(", "hashAlgos", ")", ")", "{", "throw", "new", "Error", "(", "'Hash algorithm mismatch in armor header and signature'", ")", ";", "}", "}" ]
Compare hash algorithm specified in the armor header with signatures @param {Array<String>} headers Armor headers @param {module:packet.List} packetlist The packetlist with signature packets @private
[ "Compare", "hash", "algorithm", "specified", "in", "the", "armor", "header", "with", "signatures" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/cleartext.js#L173-L211
7,450
openpgpjs/openpgpjs
src/message.js
createVerificationObject
async function createVerificationObject(signature, literalDataList, keys, date=new Date()) { let primaryKey = null; let signingKey = null; await Promise.all(keys.map(async function(key) { // Look for the unique key that matches issuerKeyId of signature const result = await key.getSigningKey(signature.issuerKeyId, null); if (result) { primaryKey = key; signingKey = result; } })); const signaturePacket = signature.correspondingSig || signature; const verifiedSig = { keyid: signature.issuerKeyId, verified: (async () => { if (!signingKey) { return null; } const verified = await signature.verify(signingKey.keyPacket, signature.signatureType, literalDataList[0]); const sig = await signaturePacket; if (sig.isExpired(date) || !( sig.created >= signingKey.getCreationTime() && sig.created < await (signingKey === primaryKey ? signingKey.getExpirationTime() : signingKey.getExpirationTime(primaryKey, date) ) )) { return null; } return verified; })(), signature: (async () => { const sig = await signaturePacket; const packetlist = new packet.List(); packetlist.push(sig); return new Signature(packetlist); })() }; // Mark potential promise rejections as "handled". This is needed because in // some cases, we reject them before the user has a reasonable chance to // handle them (e.g. `await readToEnd(result.data); await result.verified` and // the data stream errors). verifiedSig.signature.catch(() => {}); verifiedSig.verified.catch(() => {}); return verifiedSig; }
javascript
async function createVerificationObject(signature, literalDataList, keys, date=new Date()) { let primaryKey = null; let signingKey = null; await Promise.all(keys.map(async function(key) { // Look for the unique key that matches issuerKeyId of signature const result = await key.getSigningKey(signature.issuerKeyId, null); if (result) { primaryKey = key; signingKey = result; } })); const signaturePacket = signature.correspondingSig || signature; const verifiedSig = { keyid: signature.issuerKeyId, verified: (async () => { if (!signingKey) { return null; } const verified = await signature.verify(signingKey.keyPacket, signature.signatureType, literalDataList[0]); const sig = await signaturePacket; if (sig.isExpired(date) || !( sig.created >= signingKey.getCreationTime() && sig.created < await (signingKey === primaryKey ? signingKey.getExpirationTime() : signingKey.getExpirationTime(primaryKey, date) ) )) { return null; } return verified; })(), signature: (async () => { const sig = await signaturePacket; const packetlist = new packet.List(); packetlist.push(sig); return new Signature(packetlist); })() }; // Mark potential promise rejections as "handled". This is needed because in // some cases, we reject them before the user has a reasonable chance to // handle them (e.g. `await readToEnd(result.data); await result.verified` and // the data stream errors). verifiedSig.signature.catch(() => {}); verifiedSig.verified.catch(() => {}); return verifiedSig; }
[ "async", "function", "createVerificationObject", "(", "signature", ",", "literalDataList", ",", "keys", ",", "date", "=", "new", "Date", "(", ")", ")", "{", "let", "primaryKey", "=", "null", ";", "let", "signingKey", "=", "null", ";", "await", "Promise", ".", "all", "(", "keys", ".", "map", "(", "async", "function", "(", "key", ")", "{", "// Look for the unique key that matches issuerKeyId of signature", "const", "result", "=", "await", "key", ".", "getSigningKey", "(", "signature", ".", "issuerKeyId", ",", "null", ")", ";", "if", "(", "result", ")", "{", "primaryKey", "=", "key", ";", "signingKey", "=", "result", ";", "}", "}", ")", ")", ";", "const", "signaturePacket", "=", "signature", ".", "correspondingSig", "||", "signature", ";", "const", "verifiedSig", "=", "{", "keyid", ":", "signature", ".", "issuerKeyId", ",", "verified", ":", "(", "async", "(", ")", "=>", "{", "if", "(", "!", "signingKey", ")", "{", "return", "null", ";", "}", "const", "verified", "=", "await", "signature", ".", "verify", "(", "signingKey", ".", "keyPacket", ",", "signature", ".", "signatureType", ",", "literalDataList", "[", "0", "]", ")", ";", "const", "sig", "=", "await", "signaturePacket", ";", "if", "(", "sig", ".", "isExpired", "(", "date", ")", "||", "!", "(", "sig", ".", "created", ">=", "signingKey", ".", "getCreationTime", "(", ")", "&&", "sig", ".", "created", "<", "await", "(", "signingKey", "===", "primaryKey", "?", "signingKey", ".", "getExpirationTime", "(", ")", ":", "signingKey", ".", "getExpirationTime", "(", "primaryKey", ",", "date", ")", ")", ")", ")", "{", "return", "null", ";", "}", "return", "verified", ";", "}", ")", "(", ")", ",", "signature", ":", "(", "async", "(", ")", "=>", "{", "const", "sig", "=", "await", "signaturePacket", ";", "const", "packetlist", "=", "new", "packet", ".", "List", "(", ")", ";", "packetlist", ".", "push", "(", "sig", ")", ";", "return", "new", "Signature", "(", "packetlist", ")", ";", "}", ")", "(", ")", "}", ";", "// Mark potential promise rejections as \"handled\". This is needed because in", "// some cases, we reject them before the user has a reasonable chance to", "// handle them (e.g. `await readToEnd(result.data); await result.verified` and", "// the data stream errors).", "verifiedSig", ".", "signature", ".", "catch", "(", "(", ")", "=>", "{", "}", ")", ";", "verifiedSig", ".", "verified", ".", "catch", "(", "(", ")", "=>", "{", "}", ")", ";", "return", "verifiedSig", ";", "}" ]
Create object containing signer's keyid and validity of signature @param {module:packet.Signature} signature signature packets @param {Array<module:packet.Literal>} literalDataList array of literal data packets @param {Array<module:key.Key>} keys array of keys to verify signatures @param {Date} date Verify the signature against the given date, i.e. check signature creation time < date < expiration time @returns {Promise<Array<{keyid: module:type/keyid, valid: Boolean}>>} list of signer's keyid and validity of signature @async
[ "Create", "object", "containing", "signer", "s", "keyid", "and", "validity", "of", "signature" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/message.js#L635-L683
7,451
openpgpjs/openpgpjs
src/packet/secret_key.js
SecretKey
function SecretKey(date=new Date()) { publicKey.call(this, date); /** * Packet type * @type {module:enums.packet} */ this.tag = enums.packet.secretKey; /** * Encrypted secret-key data */ this.encrypted = null; /** * Indicator if secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. */ this.isEncrypted = null; }
javascript
function SecretKey(date=new Date()) { publicKey.call(this, date); /** * Packet type * @type {module:enums.packet} */ this.tag = enums.packet.secretKey; /** * Encrypted secret-key data */ this.encrypted = null; /** * Indicator if secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. */ this.isEncrypted = null; }
[ "function", "SecretKey", "(", "date", "=", "new", "Date", "(", ")", ")", "{", "publicKey", ".", "call", "(", "this", ",", "date", ")", ";", "/**\n * Packet type\n * @type {module:enums.packet}\n */", "this", ".", "tag", "=", "enums", ".", "packet", ".", "secretKey", ";", "/**\n * Encrypted secret-key data\n */", "this", ".", "encrypted", "=", "null", ";", "/**\n * Indicator if secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.\n */", "this", ".", "isEncrypted", "=", "null", ";", "}" ]
A Secret-Key packet contains all the information that is found in a Public-Key packet, including the public-key material, but also includes the secret-key material after all the public-key fields. @memberof module:packet @constructor @extends module:packet.PublicKey
[ "A", "Secret", "-", "Key", "packet", "contains", "all", "the", "information", "that", "is", "found", "in", "a", "Public", "-", "Key", "packet", "including", "the", "public", "-", "key", "material", "but", "also", "includes", "the", "secret", "-", "key", "material", "after", "all", "the", "public", "-", "key", "fields", "." ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/packet/secret_key.js#L42-L57
7,452
openpgpjs/openpgpjs
src/worker/async_proxy.js
AsyncProxy
function AsyncProxy({ path='openpgp.worker.js', n = 1, workers = [], config } = {}) { /** * Message handling */ const handleMessage = workerId => event => { const msg = event.data; switch (msg.event) { case 'loaded': this.workers[workerId].loadedResolve(true); break; case 'method-return': if (msg.err) { // fail const err = new Error(msg.err); // add worker stack err.workerStack = msg.stack; this.tasks[msg.id].reject(err); } else { // success this.tasks[msg.id].resolve(msg.data); } delete this.tasks[msg.id]; this.workers[workerId].requests--; break; case 'request-seed': this.seedRandom(workerId, msg.amount); break; default: throw new Error('Unknown Worker Event.'); } }; if (workers.length) { this.workers = workers; } else { this.workers = []; while (this.workers.length < n) { this.workers.push(new Worker(path)); } } let workerId = 0; this.workers.forEach(worker => { worker.loadedPromise = new Promise(resolve => { worker.loadedResolve = resolve; }); worker.requests = 0; worker.onmessage = handleMessage(workerId++); worker.onerror = e => { worker.loadedResolve(false); console.error('Unhandled error in openpgp worker: ' + e.message + ' (' + e.filename + ':' + e.lineno + ')'); return false; }; if (config) { worker.postMessage({ event:'configure', config }); } }); // Cannot rely on task order being maintained, use object keyed by request ID to track tasks this.tasks = {}; this.currentID = 0; }
javascript
function AsyncProxy({ path='openpgp.worker.js', n = 1, workers = [], config } = {}) { /** * Message handling */ const handleMessage = workerId => event => { const msg = event.data; switch (msg.event) { case 'loaded': this.workers[workerId].loadedResolve(true); break; case 'method-return': if (msg.err) { // fail const err = new Error(msg.err); // add worker stack err.workerStack = msg.stack; this.tasks[msg.id].reject(err); } else { // success this.tasks[msg.id].resolve(msg.data); } delete this.tasks[msg.id]; this.workers[workerId].requests--; break; case 'request-seed': this.seedRandom(workerId, msg.amount); break; default: throw new Error('Unknown Worker Event.'); } }; if (workers.length) { this.workers = workers; } else { this.workers = []; while (this.workers.length < n) { this.workers.push(new Worker(path)); } } let workerId = 0; this.workers.forEach(worker => { worker.loadedPromise = new Promise(resolve => { worker.loadedResolve = resolve; }); worker.requests = 0; worker.onmessage = handleMessage(workerId++); worker.onerror = e => { worker.loadedResolve(false); console.error('Unhandled error in openpgp worker: ' + e.message + ' (' + e.filename + ':' + e.lineno + ')'); return false; }; if (config) { worker.postMessage({ event:'configure', config }); } }); // Cannot rely on task order being maintained, use object keyed by request ID to track tasks this.tasks = {}; this.currentID = 0; }
[ "function", "AsyncProxy", "(", "{", "path", "=", "'openpgp.worker.js'", ",", "n", "=", "1", ",", "workers", "=", "[", "]", ",", "config", "}", "=", "{", "}", ")", "{", "/**\n * Message handling\n */", "const", "handleMessage", "=", "workerId", "=>", "event", "=>", "{", "const", "msg", "=", "event", ".", "data", ";", "switch", "(", "msg", ".", "event", ")", "{", "case", "'loaded'", ":", "this", ".", "workers", "[", "workerId", "]", ".", "loadedResolve", "(", "true", ")", ";", "break", ";", "case", "'method-return'", ":", "if", "(", "msg", ".", "err", ")", "{", "// fail", "const", "err", "=", "new", "Error", "(", "msg", ".", "err", ")", ";", "// add worker stack", "err", ".", "workerStack", "=", "msg", ".", "stack", ";", "this", ".", "tasks", "[", "msg", ".", "id", "]", ".", "reject", "(", "err", ")", ";", "}", "else", "{", "// success", "this", ".", "tasks", "[", "msg", ".", "id", "]", ".", "resolve", "(", "msg", ".", "data", ")", ";", "}", "delete", "this", ".", "tasks", "[", "msg", ".", "id", "]", ";", "this", ".", "workers", "[", "workerId", "]", ".", "requests", "--", ";", "break", ";", "case", "'request-seed'", ":", "this", ".", "seedRandom", "(", "workerId", ",", "msg", ".", "amount", ")", ";", "break", ";", "default", ":", "throw", "new", "Error", "(", "'Unknown Worker Event.'", ")", ";", "}", "}", ";", "if", "(", "workers", ".", "length", ")", "{", "this", ".", "workers", "=", "workers", ";", "}", "else", "{", "this", ".", "workers", "=", "[", "]", ";", "while", "(", "this", ".", "workers", ".", "length", "<", "n", ")", "{", "this", ".", "workers", ".", "push", "(", "new", "Worker", "(", "path", ")", ")", ";", "}", "}", "let", "workerId", "=", "0", ";", "this", ".", "workers", ".", "forEach", "(", "worker", "=>", "{", "worker", ".", "loadedPromise", "=", "new", "Promise", "(", "resolve", "=>", "{", "worker", ".", "loadedResolve", "=", "resolve", ";", "}", ")", ";", "worker", ".", "requests", "=", "0", ";", "worker", ".", "onmessage", "=", "handleMessage", "(", "workerId", "++", ")", ";", "worker", ".", "onerror", "=", "e", "=>", "{", "worker", ".", "loadedResolve", "(", "false", ")", ";", "console", ".", "error", "(", "'Unhandled error in openpgp worker: '", "+", "e", ".", "message", "+", "' ('", "+", "e", ".", "filename", "+", "':'", "+", "e", ".", "lineno", "+", "')'", ")", ";", "return", "false", ";", "}", ";", "if", "(", "config", ")", "{", "worker", ".", "postMessage", "(", "{", "event", ":", "'configure'", ",", "config", "}", ")", ";", "}", "}", ")", ";", "// Cannot rely on task order being maintained, use object keyed by request ID to track tasks", "this", ".", "tasks", "=", "{", "}", ";", "this", ".", "currentID", "=", "0", ";", "}" ]
Initializes a new proxy and loads the web worker @param {String} path The path to the worker or 'openpgp.worker.js' by default @param {Number} n number of workers to initialize if path given @param {Object} config config The worker configuration @param {Array<Object>} worker alternative to path parameter: web worker initialized with 'openpgp.worker.js' @constructor
[ "Initializes", "a", "new", "proxy", "and", "loads", "the", "web", "worker" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/worker/async_proxy.js#L45-L108
7,453
openpgpjs/openpgpjs
src/key.js
isDataRevoked
async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date=new Date()) { key = key || primaryKey; const normDate = util.normalizeDate(date); const revocationKeyIds = []; await Promise.all(revocations.map(async function(revocationSignature) { if ( // Note: a third-party revocation signature could legitimately revoke a // self-signature if the signature has an authorized revocation key. // However, we don't support passing authorized revocation keys, nor // verifying such revocation signatures. Instead, we indicate an error // when parsing a key with an authorized revocation key, and ignore // third-party revocation signatures here. (It could also be revoking a // third-party key certification, which should only affect // `verifyAllCertifications`.) (!signature || revocationSignature.issuerKeyId.equals(signature.issuerKeyId)) && !(config.revocations_expire && revocationSignature.isExpired(normDate)) && (revocationSignature.verified || await revocationSignature.verify(key, signatureType, dataToVerify)) ) { // TODO get an identifier of the revoked object instead revocationKeyIds.push(revocationSignature.issuerKeyId); return true; } return false; })); // TODO further verify that this is the signature that should be revoked if (signature) { signature.revoked = revocationKeyIds.some(keyId => keyId.equals(signature.issuerKeyId)) ? true : signature.revoked || false; return signature.revoked; } return revocationKeyIds.length > 0; }
javascript
async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date=new Date()) { key = key || primaryKey; const normDate = util.normalizeDate(date); const revocationKeyIds = []; await Promise.all(revocations.map(async function(revocationSignature) { if ( // Note: a third-party revocation signature could legitimately revoke a // self-signature if the signature has an authorized revocation key. // However, we don't support passing authorized revocation keys, nor // verifying such revocation signatures. Instead, we indicate an error // when parsing a key with an authorized revocation key, and ignore // third-party revocation signatures here. (It could also be revoking a // third-party key certification, which should only affect // `verifyAllCertifications`.) (!signature || revocationSignature.issuerKeyId.equals(signature.issuerKeyId)) && !(config.revocations_expire && revocationSignature.isExpired(normDate)) && (revocationSignature.verified || await revocationSignature.verify(key, signatureType, dataToVerify)) ) { // TODO get an identifier of the revoked object instead revocationKeyIds.push(revocationSignature.issuerKeyId); return true; } return false; })); // TODO further verify that this is the signature that should be revoked if (signature) { signature.revoked = revocationKeyIds.some(keyId => keyId.equals(signature.issuerKeyId)) ? true : signature.revoked || false; return signature.revoked; } return revocationKeyIds.length > 0; }
[ "async", "function", "isDataRevoked", "(", "primaryKey", ",", "signatureType", ",", "dataToVerify", ",", "revocations", ",", "signature", ",", "key", ",", "date", "=", "new", "Date", "(", ")", ")", "{", "key", "=", "key", "||", "primaryKey", ";", "const", "normDate", "=", "util", ".", "normalizeDate", "(", "date", ")", ";", "const", "revocationKeyIds", "=", "[", "]", ";", "await", "Promise", ".", "all", "(", "revocations", ".", "map", "(", "async", "function", "(", "revocationSignature", ")", "{", "if", "(", "// Note: a third-party revocation signature could legitimately revoke a", "// self-signature if the signature has an authorized revocation key.", "// However, we don't support passing authorized revocation keys, nor", "// verifying such revocation signatures. Instead, we indicate an error", "// when parsing a key with an authorized revocation key, and ignore", "// third-party revocation signatures here. (It could also be revoking a", "// third-party key certification, which should only affect", "// `verifyAllCertifications`.)", "(", "!", "signature", "||", "revocationSignature", ".", "issuerKeyId", ".", "equals", "(", "signature", ".", "issuerKeyId", ")", ")", "&&", "!", "(", "config", ".", "revocations_expire", "&&", "revocationSignature", ".", "isExpired", "(", "normDate", ")", ")", "&&", "(", "revocationSignature", ".", "verified", "||", "await", "revocationSignature", ".", "verify", "(", "key", ",", "signatureType", ",", "dataToVerify", ")", ")", ")", "{", "// TODO get an identifier of the revoked object instead", "revocationKeyIds", ".", "push", "(", "revocationSignature", ".", "issuerKeyId", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}", ")", ")", ";", "// TODO further verify that this is the signature that should be revoked", "if", "(", "signature", ")", "{", "signature", ".", "revoked", "=", "revocationKeyIds", ".", "some", "(", "keyId", "=>", "keyId", ".", "equals", "(", "signature", ".", "issuerKeyId", ")", ")", "?", "true", ":", "signature", ".", "revoked", "||", "false", ";", "return", "signature", ".", "revoked", ";", "}", "return", "revocationKeyIds", ".", "length", ">", "0", ";", "}" ]
Checks if a given certificate or binding signature is revoked @param {module:packet.SecretKey| module:packet.PublicKey} primaryKey The primary key packet @param {Object} dataToVerify The data to check @param {Array<module:packet.Signature>} revocations The revocation signatures to check @param {module:packet.Signature} signature The certificate or signature to check @param {module:packet.PublicSubkey| module:packet.SecretSubkey| module:packet.PublicKey| module:packet.SecretKey} key, optional The key packet to check the signature @param {Date} date Use the given date instead of the current time @returns {Promise<Boolean>} True if the signature revokes the data @async
[ "Checks", "if", "a", "given", "certificate", "or", "binding", "signature", "is", "revoked" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/key.js#L1611-L1642
7,454
openpgpjs/openpgpjs
src/crypto/public_key/prime.js
randomProbablePrime
async function randomProbablePrime(bits, e, k) { const min = new BN(1).shln(bits - 1); const thirty = new BN(30); /* * We can avoid any multiples of 3 and 5 by looking at n mod 30 * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 * the next possible prime is mod 30: * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1 */ const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2]; let n = await random.getRandomBN(min, min.shln(1)); let i = n.mod(thirty).toNumber(); do { n.iaddn(adds[i]); i = (i + adds[i]) % adds.length; // If reached the maximum, go back to the minimum. if (n.bitLength() > bits) { n = n.mod(min.shln(1)).iadd(min); i = n.mod(thirty).toNumber(); } } while (!await isProbablePrime(n, e, k)); return n; }
javascript
async function randomProbablePrime(bits, e, k) { const min = new BN(1).shln(bits - 1); const thirty = new BN(30); /* * We can avoid any multiples of 3 and 5 by looking at n mod 30 * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 * the next possible prime is mod 30: * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1 */ const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2]; let n = await random.getRandomBN(min, min.shln(1)); let i = n.mod(thirty).toNumber(); do { n.iaddn(adds[i]); i = (i + adds[i]) % adds.length; // If reached the maximum, go back to the minimum. if (n.bitLength() > bits) { n = n.mod(min.shln(1)).iadd(min); i = n.mod(thirty).toNumber(); } } while (!await isProbablePrime(n, e, k)); return n; }
[ "async", "function", "randomProbablePrime", "(", "bits", ",", "e", ",", "k", ")", "{", "const", "min", "=", "new", "BN", "(", "1", ")", ".", "shln", "(", "bits", "-", "1", ")", ";", "const", "thirty", "=", "new", "BN", "(", "30", ")", ";", "/*\n * We can avoid any multiples of 3 and 5 by looking at n mod 30\n * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29\n * the next possible prime is mod 30:\n * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1\n */", "const", "adds", "=", "[", "1", ",", "6", ",", "5", ",", "4", ",", "3", ",", "2", ",", "1", ",", "4", ",", "3", ",", "2", ",", "1", ",", "2", ",", "1", ",", "4", ",", "3", ",", "2", ",", "1", ",", "2", ",", "1", ",", "4", ",", "3", ",", "2", ",", "1", ",", "6", ",", "5", ",", "4", ",", "3", ",", "2", ",", "1", ",", "2", "]", ";", "let", "n", "=", "await", "random", ".", "getRandomBN", "(", "min", ",", "min", ".", "shln", "(", "1", ")", ")", ";", "let", "i", "=", "n", ".", "mod", "(", "thirty", ")", ".", "toNumber", "(", ")", ";", "do", "{", "n", ".", "iaddn", "(", "adds", "[", "i", "]", ")", ";", "i", "=", "(", "i", "+", "adds", "[", "i", "]", ")", "%", "adds", ".", "length", ";", "// If reached the maximum, go back to the minimum.", "if", "(", "n", ".", "bitLength", "(", ")", ">", "bits", ")", "{", "n", "=", "n", ".", "mod", "(", "min", ".", "shln", "(", "1", ")", ")", ".", "iadd", "(", "min", ")", ";", "i", "=", "n", ".", "mod", "(", "thirty", ")", ".", "toNumber", "(", ")", ";", "}", "}", "while", "(", "!", "await", "isProbablePrime", "(", "n", ",", "e", ",", "k", ")", ")", ";", "return", "n", ";", "}" ]
Probabilistic random number generator @param {Integer} bits Bit length of the prime @param {BN} e Optional RSA exponent to check against the prime @param {Integer} k Optional number of iterations of Miller-Rabin test @returns BN @async
[ "Probabilistic", "random", "number", "generator" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/crypto/public_key/prime.js#L40-L64
7,455
openpgpjs/openpgpjs
src/crypto/public_key/prime.js
isProbablePrime
async function isProbablePrime(n, e, k) { if (e && !n.subn(1).gcd(e).eqn(1)) { return false; } if (!divisionTest(n)) { return false; } if (!fermat(n)) { return false; } if (!await millerRabin(n, k)) { return false; } // TODO implement the Lucas test // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf return true; }
javascript
async function isProbablePrime(n, e, k) { if (e && !n.subn(1).gcd(e).eqn(1)) { return false; } if (!divisionTest(n)) { return false; } if (!fermat(n)) { return false; } if (!await millerRabin(n, k)) { return false; } // TODO implement the Lucas test // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf return true; }
[ "async", "function", "isProbablePrime", "(", "n", ",", "e", ",", "k", ")", "{", "if", "(", "e", "&&", "!", "n", ".", "subn", "(", "1", ")", ".", "gcd", "(", "e", ")", ".", "eqn", "(", "1", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "divisionTest", "(", "n", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "fermat", "(", "n", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "await", "millerRabin", "(", "n", ",", "k", ")", ")", "{", "return", "false", ";", "}", "// TODO implement the Lucas test", "// See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf", "return", "true", ";", "}" ]
Probabilistic primality testing @param {BN} n Number to test @param {BN} e Optional RSA exponent to check against the prime @param {Integer} k Optional number of iterations of Miller-Rabin test @returns {boolean} @async
[ "Probabilistic", "primality", "testing" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/crypto/public_key/prime.js#L74-L90
7,456
openpgpjs/openpgpjs
src/encoding/armor.js
getType
function getType(text) { const reHeader = /^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m; const header = text.match(reHeader); if (!header) { throw new Error('Unknown ASCII armor type'); } // BEGIN PGP MESSAGE, PART X/Y // Used for multi-part messages, where the armor is split amongst Y // parts, and this is the Xth part out of Y. if (/MESSAGE, PART \d+\/\d+/.test(header[1])) { return enums.armor.multipart_section; } else // BEGIN PGP MESSAGE, PART X // Used for multi-part messages, where this is the Xth part of an // unspecified number of parts. Requires the MESSAGE-ID Armor // Header to be used. if (/MESSAGE, PART \d+/.test(header[1])) { return enums.armor.multipart_last; } else // BEGIN PGP SIGNED MESSAGE if (/SIGNED MESSAGE/.test(header[1])) { return enums.armor.signed; } else // BEGIN PGP MESSAGE // Used for signed, encrypted, or compressed files. if (/MESSAGE/.test(header[1])) { return enums.armor.message; } else // BEGIN PGP PUBLIC KEY BLOCK // Used for armoring public keys. if (/PUBLIC KEY BLOCK/.test(header[1])) { return enums.armor.public_key; } else // BEGIN PGP PRIVATE KEY BLOCK // Used for armoring private keys. if (/PRIVATE KEY BLOCK/.test(header[1])) { return enums.armor.private_key; } else // BEGIN PGP SIGNATURE // Used for detached signatures, OpenPGP/MIME signatures, and // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE // for detached signatures. if (/SIGNATURE/.test(header[1])) { return enums.armor.signature; } }
javascript
function getType(text) { const reHeader = /^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m; const header = text.match(reHeader); if (!header) { throw new Error('Unknown ASCII armor type'); } // BEGIN PGP MESSAGE, PART X/Y // Used for multi-part messages, where the armor is split amongst Y // parts, and this is the Xth part out of Y. if (/MESSAGE, PART \d+\/\d+/.test(header[1])) { return enums.armor.multipart_section; } else // BEGIN PGP MESSAGE, PART X // Used for multi-part messages, where this is the Xth part of an // unspecified number of parts. Requires the MESSAGE-ID Armor // Header to be used. if (/MESSAGE, PART \d+/.test(header[1])) { return enums.armor.multipart_last; } else // BEGIN PGP SIGNED MESSAGE if (/SIGNED MESSAGE/.test(header[1])) { return enums.armor.signed; } else // BEGIN PGP MESSAGE // Used for signed, encrypted, or compressed files. if (/MESSAGE/.test(header[1])) { return enums.armor.message; } else // BEGIN PGP PUBLIC KEY BLOCK // Used for armoring public keys. if (/PUBLIC KEY BLOCK/.test(header[1])) { return enums.armor.public_key; } else // BEGIN PGP PRIVATE KEY BLOCK // Used for armoring private keys. if (/PRIVATE KEY BLOCK/.test(header[1])) { return enums.armor.private_key; } else // BEGIN PGP SIGNATURE // Used for detached signatures, OpenPGP/MIME signatures, and // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE // for detached signatures. if (/SIGNATURE/.test(header[1])) { return enums.armor.signature; } }
[ "function", "getType", "(", "text", ")", "{", "const", "reHeader", "=", "/", "^-----BEGIN PGP (MESSAGE, PART \\d+\\/\\d+|MESSAGE, PART \\d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$", "/", "m", ";", "const", "header", "=", "text", ".", "match", "(", "reHeader", ")", ";", "if", "(", "!", "header", ")", "{", "throw", "new", "Error", "(", "'Unknown ASCII armor type'", ")", ";", "}", "// BEGIN PGP MESSAGE, PART X/Y", "// Used for multi-part messages, where the armor is split amongst Y", "// parts, and this is the Xth part out of Y.", "if", "(", "/", "MESSAGE, PART \\d+\\/\\d+", "/", ".", "test", "(", "header", "[", "1", "]", ")", ")", "{", "return", "enums", ".", "armor", ".", "multipart_section", ";", "}", "else", "// BEGIN PGP MESSAGE, PART X", "// Used for multi-part messages, where this is the Xth part of an", "// unspecified number of parts. Requires the MESSAGE-ID Armor", "// Header to be used.", "if", "(", "/", "MESSAGE, PART \\d+", "/", ".", "test", "(", "header", "[", "1", "]", ")", ")", "{", "return", "enums", ".", "armor", ".", "multipart_last", ";", "}", "else", "// BEGIN PGP SIGNED MESSAGE", "if", "(", "/", "SIGNED MESSAGE", "/", ".", "test", "(", "header", "[", "1", "]", ")", ")", "{", "return", "enums", ".", "armor", ".", "signed", ";", "}", "else", "// BEGIN PGP MESSAGE", "// Used for signed, encrypted, or compressed files.", "if", "(", "/", "MESSAGE", "/", ".", "test", "(", "header", "[", "1", "]", ")", ")", "{", "return", "enums", ".", "armor", ".", "message", ";", "}", "else", "// BEGIN PGP PUBLIC KEY BLOCK", "// Used for armoring public keys.", "if", "(", "/", "PUBLIC KEY BLOCK", "/", ".", "test", "(", "header", "[", "1", "]", ")", ")", "{", "return", "enums", ".", "armor", ".", "public_key", ";", "}", "else", "// BEGIN PGP PRIVATE KEY BLOCK", "// Used for armoring private keys.", "if", "(", "/", "PRIVATE KEY BLOCK", "/", ".", "test", "(", "header", "[", "1", "]", ")", ")", "{", "return", "enums", ".", "armor", ".", "private_key", ";", "}", "else", "// BEGIN PGP SIGNATURE", "// Used for detached signatures, OpenPGP/MIME signatures, and", "// cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE", "// for detached signatures.", "if", "(", "/", "SIGNATURE", "/", ".", "test", "(", "header", "[", "1", "]", ")", ")", "{", "return", "enums", ".", "armor", ".", "signature", ";", "}", "}" ]
Finds out which Ascii Armoring type is used. Throws error if unknown type. @private @param {String} text [String] ascii armored text @returns {Integer} 0 = MESSAGE PART n of m 1 = MESSAGE PART n 2 = SIGNED MESSAGE 3 = PGP MESSAGE 4 = PUBLIC KEY BLOCK 5 = PRIVATE KEY BLOCK 6 = SIGNATURE
[ "Finds", "out", "which", "Ascii", "Armoring", "type", "is", "used", ".", "Throws", "error", "if", "unknown", "type", "." ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/encoding/armor.js#L45-L93
7,457
openpgpjs/openpgpjs
src/encoding/armor.js
addheader
function addheader(customComment) { let result = ""; if (config.show_version) { result += "Version: " + config.versionstring + '\r\n'; } if (config.show_comment) { result += "Comment: " + config.commentstring + '\r\n'; } if (customComment) { result += "Comment: " + customComment + '\r\n'; } result += '\r\n'; return result; }
javascript
function addheader(customComment) { let result = ""; if (config.show_version) { result += "Version: " + config.versionstring + '\r\n'; } if (config.show_comment) { result += "Comment: " + config.commentstring + '\r\n'; } if (customComment) { result += "Comment: " + customComment + '\r\n'; } result += '\r\n'; return result; }
[ "function", "addheader", "(", "customComment", ")", "{", "let", "result", "=", "\"\"", ";", "if", "(", "config", ".", "show_version", ")", "{", "result", "+=", "\"Version: \"", "+", "config", ".", "versionstring", "+", "'\\r\\n'", ";", "}", "if", "(", "config", ".", "show_comment", ")", "{", "result", "+=", "\"Comment: \"", "+", "config", ".", "commentstring", "+", "'\\r\\n'", ";", "}", "if", "(", "customComment", ")", "{", "result", "+=", "\"Comment: \"", "+", "customComment", "+", "'\\r\\n'", ";", "}", "result", "+=", "'\\r\\n'", ";", "return", "result", ";", "}" ]
Add additional information to the armor version of an OpenPGP binary packet block. @author Alex @version 2011-12-16 @param {String} customComment (optional) additional comment to add to the armored string @returns {String} The header information
[ "Add", "additional", "information", "to", "the", "armor", "version", "of", "an", "OpenPGP", "binary", "packet", "block", "." ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/encoding/armor.js#L103-L116
7,458
openpgpjs/openpgpjs
src/encoding/armor.js
splitChecksum
function splitChecksum(text) { let body = text; let checksum = ""; const lastEquals = text.lastIndexOf("="); if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum body = text.slice(0, lastEquals); checksum = text.slice(lastEquals + 1).substr(0, 4); } return { body: body, checksum: checksum }; }
javascript
function splitChecksum(text) { let body = text; let checksum = ""; const lastEquals = text.lastIndexOf("="); if (lastEquals >= 0 && lastEquals !== text.length - 1) { // '=' as the last char means no checksum body = text.slice(0, lastEquals); checksum = text.slice(lastEquals + 1).substr(0, 4); } return { body: body, checksum: checksum }; }
[ "function", "splitChecksum", "(", "text", ")", "{", "let", "body", "=", "text", ";", "let", "checksum", "=", "\"\"", ";", "const", "lastEquals", "=", "text", ".", "lastIndexOf", "(", "\"=\"", ")", ";", "if", "(", "lastEquals", ">=", "0", "&&", "lastEquals", "!==", "text", ".", "length", "-", "1", ")", "{", "// '=' as the last char means no checksum", "body", "=", "text", ".", "slice", "(", "0", ",", "lastEquals", ")", ";", "checksum", "=", "text", ".", "slice", "(", "lastEquals", "+", "1", ")", ".", "substr", "(", "0", ",", "4", ")", ";", "}", "return", "{", "body", ":", "body", ",", "checksum", ":", "checksum", "}", ";", "}" ]
Splits a message into two parts, the body and the checksum. This is an internal function @param {String} text OpenPGP armored message part @returns {Object} An object with attribute "body" containing the body and an attribute "checksum" containing the checksum.
[ "Splits", "a", "message", "into", "two", "parts", "the", "body", "and", "the", "checksum", ".", "This", "is", "an", "internal", "function" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/encoding/armor.js#L201-L213
7,459
openpgpjs/openpgpjs
src/encoding/armor.js
armor
function armor(messagetype, body, partindex, parttotal, customComment) { let text; let hash; if (messagetype === enums.armor.signed) { text = body.text; hash = body.hash; body = body.data; } const bodyClone = stream.passiveClone(body); const result = []; switch (messagetype) { case enums.armor.multipart_section: result.push("-----BEGIN PGP MESSAGE, PART " + partindex + "/" + parttotal + "-----\r\n"); result.push(addheader(customComment)); result.push(base64.encode(body)); result.push("\r\n=", getCheckSum(bodyClone), "\r\n"); result.push("-----END PGP MESSAGE, PART " + partindex + "/" + parttotal + "-----\r\n"); break; case enums.armor.multipart_last: result.push("-----BEGIN PGP MESSAGE, PART " + partindex + "-----\r\n"); result.push(addheader(customComment)); result.push(base64.encode(body)); result.push("\r\n=", getCheckSum(bodyClone), "\r\n"); result.push("-----END PGP MESSAGE, PART " + partindex + "-----\r\n"); break; case enums.armor.signed: result.push("\r\n-----BEGIN PGP SIGNED MESSAGE-----\r\n"); result.push("Hash: " + hash + "\r\n\r\n"); result.push(text.replace(/^-/mg, "- -")); result.push("\r\n-----BEGIN PGP SIGNATURE-----\r\n"); result.push(addheader(customComment)); result.push(base64.encode(body)); result.push("\r\n=", getCheckSum(bodyClone), "\r\n"); result.push("-----END PGP SIGNATURE-----\r\n"); break; case enums.armor.message: result.push("-----BEGIN PGP MESSAGE-----\r\n"); result.push(addheader(customComment)); result.push(base64.encode(body)); result.push("\r\n=", getCheckSum(bodyClone), "\r\n"); result.push("-----END PGP MESSAGE-----\r\n"); break; case enums.armor.public_key: result.push("-----BEGIN PGP PUBLIC KEY BLOCK-----\r\n"); result.push(addheader(customComment)); result.push(base64.encode(body)); result.push("\r\n=", getCheckSum(bodyClone), "\r\n"); result.push("-----END PGP PUBLIC KEY BLOCK-----\r\n"); break; case enums.armor.private_key: result.push("-----BEGIN PGP PRIVATE KEY BLOCK-----\r\n"); result.push(addheader(customComment)); result.push(base64.encode(body)); result.push("\r\n=", getCheckSum(bodyClone), "\r\n"); result.push("-----END PGP PRIVATE KEY BLOCK-----\r\n"); break; case enums.armor.signature: result.push("-----BEGIN PGP SIGNATURE-----\r\n"); result.push(addheader(customComment)); result.push(base64.encode(body)); result.push("\r\n=", getCheckSum(bodyClone), "\r\n"); result.push("-----END PGP SIGNATURE-----\r\n"); break; } return util.concat(result); }
javascript
function armor(messagetype, body, partindex, parttotal, customComment) { let text; let hash; if (messagetype === enums.armor.signed) { text = body.text; hash = body.hash; body = body.data; } const bodyClone = stream.passiveClone(body); const result = []; switch (messagetype) { case enums.armor.multipart_section: result.push("-----BEGIN PGP MESSAGE, PART " + partindex + "/" + parttotal + "-----\r\n"); result.push(addheader(customComment)); result.push(base64.encode(body)); result.push("\r\n=", getCheckSum(bodyClone), "\r\n"); result.push("-----END PGP MESSAGE, PART " + partindex + "/" + parttotal + "-----\r\n"); break; case enums.armor.multipart_last: result.push("-----BEGIN PGP MESSAGE, PART " + partindex + "-----\r\n"); result.push(addheader(customComment)); result.push(base64.encode(body)); result.push("\r\n=", getCheckSum(bodyClone), "\r\n"); result.push("-----END PGP MESSAGE, PART " + partindex + "-----\r\n"); break; case enums.armor.signed: result.push("\r\n-----BEGIN PGP SIGNED MESSAGE-----\r\n"); result.push("Hash: " + hash + "\r\n\r\n"); result.push(text.replace(/^-/mg, "- -")); result.push("\r\n-----BEGIN PGP SIGNATURE-----\r\n"); result.push(addheader(customComment)); result.push(base64.encode(body)); result.push("\r\n=", getCheckSum(bodyClone), "\r\n"); result.push("-----END PGP SIGNATURE-----\r\n"); break; case enums.armor.message: result.push("-----BEGIN PGP MESSAGE-----\r\n"); result.push(addheader(customComment)); result.push(base64.encode(body)); result.push("\r\n=", getCheckSum(bodyClone), "\r\n"); result.push("-----END PGP MESSAGE-----\r\n"); break; case enums.armor.public_key: result.push("-----BEGIN PGP PUBLIC KEY BLOCK-----\r\n"); result.push(addheader(customComment)); result.push(base64.encode(body)); result.push("\r\n=", getCheckSum(bodyClone), "\r\n"); result.push("-----END PGP PUBLIC KEY BLOCK-----\r\n"); break; case enums.armor.private_key: result.push("-----BEGIN PGP PRIVATE KEY BLOCK-----\r\n"); result.push(addheader(customComment)); result.push(base64.encode(body)); result.push("\r\n=", getCheckSum(bodyClone), "\r\n"); result.push("-----END PGP PRIVATE KEY BLOCK-----\r\n"); break; case enums.armor.signature: result.push("-----BEGIN PGP SIGNATURE-----\r\n"); result.push(addheader(customComment)); result.push(base64.encode(body)); result.push("\r\n=", getCheckSum(bodyClone), "\r\n"); result.push("-----END PGP SIGNATURE-----\r\n"); break; } return util.concat(result); }
[ "function", "armor", "(", "messagetype", ",", "body", ",", "partindex", ",", "parttotal", ",", "customComment", ")", "{", "let", "text", ";", "let", "hash", ";", "if", "(", "messagetype", "===", "enums", ".", "armor", ".", "signed", ")", "{", "text", "=", "body", ".", "text", ";", "hash", "=", "body", ".", "hash", ";", "body", "=", "body", ".", "data", ";", "}", "const", "bodyClone", "=", "stream", ".", "passiveClone", "(", "body", ")", ";", "const", "result", "=", "[", "]", ";", "switch", "(", "messagetype", ")", "{", "case", "enums", ".", "armor", ".", "multipart_section", ":", "result", ".", "push", "(", "\"-----BEGIN PGP MESSAGE, PART \"", "+", "partindex", "+", "\"/\"", "+", "parttotal", "+", "\"-----\\r\\n\"", ")", ";", "result", ".", "push", "(", "addheader", "(", "customComment", ")", ")", ";", "result", ".", "push", "(", "base64", ".", "encode", "(", "body", ")", ")", ";", "result", ".", "push", "(", "\"\\r\\n=\"", ",", "getCheckSum", "(", "bodyClone", ")", ",", "\"\\r\\n\"", ")", ";", "result", ".", "push", "(", "\"-----END PGP MESSAGE, PART \"", "+", "partindex", "+", "\"/\"", "+", "parttotal", "+", "\"-----\\r\\n\"", ")", ";", "break", ";", "case", "enums", ".", "armor", ".", "multipart_last", ":", "result", ".", "push", "(", "\"-----BEGIN PGP MESSAGE, PART \"", "+", "partindex", "+", "\"-----\\r\\n\"", ")", ";", "result", ".", "push", "(", "addheader", "(", "customComment", ")", ")", ";", "result", ".", "push", "(", "base64", ".", "encode", "(", "body", ")", ")", ";", "result", ".", "push", "(", "\"\\r\\n=\"", ",", "getCheckSum", "(", "bodyClone", ")", ",", "\"\\r\\n\"", ")", ";", "result", ".", "push", "(", "\"-----END PGP MESSAGE, PART \"", "+", "partindex", "+", "\"-----\\r\\n\"", ")", ";", "break", ";", "case", "enums", ".", "armor", ".", "signed", ":", "result", ".", "push", "(", "\"\\r\\n-----BEGIN PGP SIGNED MESSAGE-----\\r\\n\"", ")", ";", "result", ".", "push", "(", "\"Hash: \"", "+", "hash", "+", "\"\\r\\n\\r\\n\"", ")", ";", "result", ".", "push", "(", "text", ".", "replace", "(", "/", "^-", "/", "mg", ",", "\"- -\"", ")", ")", ";", "result", ".", "push", "(", "\"\\r\\n-----BEGIN PGP SIGNATURE-----\\r\\n\"", ")", ";", "result", ".", "push", "(", "addheader", "(", "customComment", ")", ")", ";", "result", ".", "push", "(", "base64", ".", "encode", "(", "body", ")", ")", ";", "result", ".", "push", "(", "\"\\r\\n=\"", ",", "getCheckSum", "(", "bodyClone", ")", ",", "\"\\r\\n\"", ")", ";", "result", ".", "push", "(", "\"-----END PGP SIGNATURE-----\\r\\n\"", ")", ";", "break", ";", "case", "enums", ".", "armor", ".", "message", ":", "result", ".", "push", "(", "\"-----BEGIN PGP MESSAGE-----\\r\\n\"", ")", ";", "result", ".", "push", "(", "addheader", "(", "customComment", ")", ")", ";", "result", ".", "push", "(", "base64", ".", "encode", "(", "body", ")", ")", ";", "result", ".", "push", "(", "\"\\r\\n=\"", ",", "getCheckSum", "(", "bodyClone", ")", ",", "\"\\r\\n\"", ")", ";", "result", ".", "push", "(", "\"-----END PGP MESSAGE-----\\r\\n\"", ")", ";", "break", ";", "case", "enums", ".", "armor", ".", "public_key", ":", "result", ".", "push", "(", "\"-----BEGIN PGP PUBLIC KEY BLOCK-----\\r\\n\"", ")", ";", "result", ".", "push", "(", "addheader", "(", "customComment", ")", ")", ";", "result", ".", "push", "(", "base64", ".", "encode", "(", "body", ")", ")", ";", "result", ".", "push", "(", "\"\\r\\n=\"", ",", "getCheckSum", "(", "bodyClone", ")", ",", "\"\\r\\n\"", ")", ";", "result", ".", "push", "(", "\"-----END PGP PUBLIC KEY BLOCK-----\\r\\n\"", ")", ";", "break", ";", "case", "enums", ".", "armor", ".", "private_key", ":", "result", ".", "push", "(", "\"-----BEGIN PGP PRIVATE KEY BLOCK-----\\r\\n\"", ")", ";", "result", ".", "push", "(", "addheader", "(", "customComment", ")", ")", ";", "result", ".", "push", "(", "base64", ".", "encode", "(", "body", ")", ")", ";", "result", ".", "push", "(", "\"\\r\\n=\"", ",", "getCheckSum", "(", "bodyClone", ")", ",", "\"\\r\\n\"", ")", ";", "result", ".", "push", "(", "\"-----END PGP PRIVATE KEY BLOCK-----\\r\\n\"", ")", ";", "break", ";", "case", "enums", ".", "armor", ".", "signature", ":", "result", ".", "push", "(", "\"-----BEGIN PGP SIGNATURE-----\\r\\n\"", ")", ";", "result", ".", "push", "(", "addheader", "(", "customComment", ")", ")", ";", "result", ".", "push", "(", "base64", ".", "encode", "(", "body", ")", ")", ";", "result", ".", "push", "(", "\"\\r\\n=\"", ",", "getCheckSum", "(", "bodyClone", ")", ",", "\"\\r\\n\"", ")", ";", "result", ".", "push", "(", "\"-----END PGP SIGNATURE-----\\r\\n\"", ")", ";", "break", ";", "}", "return", "util", ".", "concat", "(", "result", ")", ";", "}" ]
Armor an OpenPGP binary packet block @param {Integer} messagetype type of the message @param body @param {Integer} partindex @param {Integer} parttotal @param {String} customComment (optional) additional comment to add to the armored string @returns {String | ReadableStream<String>} Armored text @static
[ "Armor", "an", "OpenPGP", "binary", "packet", "block" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/encoding/armor.js#L349-L415
7,460
openpgpjs/openpgpjs
src/crypto/hash/index.js
function(algo, data) { switch (algo) { case 1: // - MD5 [HAC] return this.md5(data); case 2: // - SHA-1 [FIPS180] return this.sha1(data); case 3: // - RIPE-MD/160 [HAC] return this.ripemd(data); case 8: // - SHA256 [FIPS180] return this.sha256(data); case 9: // - SHA384 [FIPS180] return this.sha384(data); case 10: // - SHA512 [FIPS180] return this.sha512(data); case 11: // - SHA224 [FIPS180] return this.sha224(data); default: throw new Error('Invalid hash function.'); } }
javascript
function(algo, data) { switch (algo) { case 1: // - MD5 [HAC] return this.md5(data); case 2: // - SHA-1 [FIPS180] return this.sha1(data); case 3: // - RIPE-MD/160 [HAC] return this.ripemd(data); case 8: // - SHA256 [FIPS180] return this.sha256(data); case 9: // - SHA384 [FIPS180] return this.sha384(data); case 10: // - SHA512 [FIPS180] return this.sha512(data); case 11: // - SHA224 [FIPS180] return this.sha224(data); default: throw new Error('Invalid hash function.'); } }
[ "function", "(", "algo", ",", "data", ")", "{", "switch", "(", "algo", ")", "{", "case", "1", ":", "// - MD5 [HAC]", "return", "this", ".", "md5", "(", "data", ")", ";", "case", "2", ":", "// - SHA-1 [FIPS180]", "return", "this", ".", "sha1", "(", "data", ")", ";", "case", "3", ":", "// - RIPE-MD/160 [HAC]", "return", "this", ".", "ripemd", "(", "data", ")", ";", "case", "8", ":", "// - SHA256 [FIPS180]", "return", "this", ".", "sha256", "(", "data", ")", ";", "case", "9", ":", "// - SHA384 [FIPS180]", "return", "this", ".", "sha384", "(", "data", ")", ";", "case", "10", ":", "// - SHA512 [FIPS180]", "return", "this", ".", "sha512", "(", "data", ")", ";", "case", "11", ":", "// - SHA224 [FIPS180]", "return", "this", ".", "sha224", "(", "data", ")", ";", "default", ":", "throw", "new", "Error", "(", "'Invalid hash function.'", ")", ";", "}", "}" ]
Create a hash on the specified data using the specified algorithm @param {module:enums.hash} algo Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) @param {Uint8Array} data Data to be hashed @returns {Promise<Uint8Array>} hash value
[ "Create", "a", "hash", "on", "the", "specified", "data", "using", "the", "specified", "algorithm" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/crypto/hash/index.js#L111-L137
7,461
openpgpjs/openpgpjs
src/encoding/base64.js
s2r
function s2r(t, u = false) { // TODO check btoa alternative const b64 = u ? b64u : b64s; let a; let c; let l = 0; let s = 0; return stream.transform(t, value => { const r = []; const tl = value.length; for (let n = 0; n < tl; n++) { if (l && (l % 60) === 0 && !u) { r.push("\r\n"); } c = value[n]; if (s === 0) { r.push(b64.charAt((c >> 2) & 63)); a = (c & 3) << 4; } else if (s === 1) { r.push(b64.charAt(a | ((c >> 4) & 15))); a = (c & 15) << 2; } else if (s === 2) { r.push(b64.charAt(a | ((c >> 6) & 3))); l += 1; if ((l % 60) === 0 && !u) { r.push("\r\n"); } r.push(b64.charAt(c & 63)); } l += 1; s += 1; if (s === 3) { s = 0; } } return r.join(''); }, () => { const r = []; if (s > 0) { r.push(b64.charAt(a)); l += 1; if ((l % 60) === 0 && !u) { r.push("\r\n"); } if (!u) { r.push('='); l += 1; } } if (s === 1 && !u) { if ((l % 60) === 0 && !u) { r.push("\r\n"); } r.push('='); } return r.join(''); }); }
javascript
function s2r(t, u = false) { // TODO check btoa alternative const b64 = u ? b64u : b64s; let a; let c; let l = 0; let s = 0; return stream.transform(t, value => { const r = []; const tl = value.length; for (let n = 0; n < tl; n++) { if (l && (l % 60) === 0 && !u) { r.push("\r\n"); } c = value[n]; if (s === 0) { r.push(b64.charAt((c >> 2) & 63)); a = (c & 3) << 4; } else if (s === 1) { r.push(b64.charAt(a | ((c >> 4) & 15))); a = (c & 15) << 2; } else if (s === 2) { r.push(b64.charAt(a | ((c >> 6) & 3))); l += 1; if ((l % 60) === 0 && !u) { r.push("\r\n"); } r.push(b64.charAt(c & 63)); } l += 1; s += 1; if (s === 3) { s = 0; } } return r.join(''); }, () => { const r = []; if (s > 0) { r.push(b64.charAt(a)); l += 1; if ((l % 60) === 0 && !u) { r.push("\r\n"); } if (!u) { r.push('='); l += 1; } } if (s === 1 && !u) { if ((l % 60) === 0 && !u) { r.push("\r\n"); } r.push('='); } return r.join(''); }); }
[ "function", "s2r", "(", "t", ",", "u", "=", "false", ")", "{", "// TODO check btoa alternative", "const", "b64", "=", "u", "?", "b64u", ":", "b64s", ";", "let", "a", ";", "let", "c", ";", "let", "l", "=", "0", ";", "let", "s", "=", "0", ";", "return", "stream", ".", "transform", "(", "t", ",", "value", "=>", "{", "const", "r", "=", "[", "]", ";", "const", "tl", "=", "value", ".", "length", ";", "for", "(", "let", "n", "=", "0", ";", "n", "<", "tl", ";", "n", "++", ")", "{", "if", "(", "l", "&&", "(", "l", "%", "60", ")", "===", "0", "&&", "!", "u", ")", "{", "r", ".", "push", "(", "\"\\r\\n\"", ")", ";", "}", "c", "=", "value", "[", "n", "]", ";", "if", "(", "s", "===", "0", ")", "{", "r", ".", "push", "(", "b64", ".", "charAt", "(", "(", "c", ">>", "2", ")", "&", "63", ")", ")", ";", "a", "=", "(", "c", "&", "3", ")", "<<", "4", ";", "}", "else", "if", "(", "s", "===", "1", ")", "{", "r", ".", "push", "(", "b64", ".", "charAt", "(", "a", "|", "(", "(", "c", ">>", "4", ")", "&", "15", ")", ")", ")", ";", "a", "=", "(", "c", "&", "15", ")", "<<", "2", ";", "}", "else", "if", "(", "s", "===", "2", ")", "{", "r", ".", "push", "(", "b64", ".", "charAt", "(", "a", "|", "(", "(", "c", ">>", "6", ")", "&", "3", ")", ")", ")", ";", "l", "+=", "1", ";", "if", "(", "(", "l", "%", "60", ")", "===", "0", "&&", "!", "u", ")", "{", "r", ".", "push", "(", "\"\\r\\n\"", ")", ";", "}", "r", ".", "push", "(", "b64", ".", "charAt", "(", "c", "&", "63", ")", ")", ";", "}", "l", "+=", "1", ";", "s", "+=", "1", ";", "if", "(", "s", "===", "3", ")", "{", "s", "=", "0", ";", "}", "}", "return", "r", ".", "join", "(", "''", ")", ";", "}", ",", "(", ")", "=>", "{", "const", "r", "=", "[", "]", ";", "if", "(", "s", ">", "0", ")", "{", "r", ".", "push", "(", "b64", ".", "charAt", "(", "a", ")", ")", ";", "l", "+=", "1", ";", "if", "(", "(", "l", "%", "60", ")", "===", "0", "&&", "!", "u", ")", "{", "r", ".", "push", "(", "\"\\r\\n\"", ")", ";", "}", "if", "(", "!", "u", ")", "{", "r", ".", "push", "(", "'='", ")", ";", "l", "+=", "1", ";", "}", "}", "if", "(", "s", "===", "1", "&&", "!", "u", ")", "{", "if", "(", "(", "l", "%", "60", ")", "===", "0", "&&", "!", "u", ")", "{", "r", ".", "push", "(", "\"\\r\\n\"", ")", ";", "}", "r", ".", "push", "(", "'='", ")", ";", "}", "return", "r", ".", "join", "(", "''", ")", ";", "}", ")", ";", "}" ]
Convert binary array to radix-64 @param {Uint8Array | ReadableStream<Uint8Array>} t Uint8Array to convert @param {bool} u if true, output is URL-safe @returns {String | ReadableStream<String>} radix-64 version of input string @static
[ "Convert", "binary", "array", "to", "radix", "-", "64" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/encoding/base64.js#L38-L97
7,462
openpgpjs/openpgpjs
src/encoding/base64.js
r2s
function r2s(t, u) { // TODO check atob alternative let c; let s = 0; let a = 0; return stream.transform(t, value => { const tl = value.length; const r = new Uint8Array(Math.ceil(0.75 * tl)); let index = 0; for (let n = 0; n < tl; n++) { c = b64toByte[value.charCodeAt(n)]; if (c >= 0) { if (s) { r[index++] = a | ((c >> (6 - s)) & 255); } s = (s + 2) & 7; a = (c << s) & 255; } } return r.subarray(0, index); }); }
javascript
function r2s(t, u) { // TODO check atob alternative let c; let s = 0; let a = 0; return stream.transform(t, value => { const tl = value.length; const r = new Uint8Array(Math.ceil(0.75 * tl)); let index = 0; for (let n = 0; n < tl; n++) { c = b64toByte[value.charCodeAt(n)]; if (c >= 0) { if (s) { r[index++] = a | ((c >> (6 - s)) & 255); } s = (s + 2) & 7; a = (c << s) & 255; } } return r.subarray(0, index); }); }
[ "function", "r2s", "(", "t", ",", "u", ")", "{", "// TODO check atob alternative", "let", "c", ";", "let", "s", "=", "0", ";", "let", "a", "=", "0", ";", "return", "stream", ".", "transform", "(", "t", ",", "value", "=>", "{", "const", "tl", "=", "value", ".", "length", ";", "const", "r", "=", "new", "Uint8Array", "(", "Math", ".", "ceil", "(", "0.75", "*", "tl", ")", ")", ";", "let", "index", "=", "0", ";", "for", "(", "let", "n", "=", "0", ";", "n", "<", "tl", ";", "n", "++", ")", "{", "c", "=", "b64toByte", "[", "value", ".", "charCodeAt", "(", "n", ")", "]", ";", "if", "(", "c", ">=", "0", ")", "{", "if", "(", "s", ")", "{", "r", "[", "index", "++", "]", "=", "a", "|", "(", "(", "c", ">>", "(", "6", "-", "s", ")", ")", "&", "255", ")", ";", "}", "s", "=", "(", "s", "+", "2", ")", "&", "7", ";", "a", "=", "(", "c", "<<", "s", ")", "&", "255", ";", "}", "}", "return", "r", ".", "subarray", "(", "0", ",", "index", ")", ";", "}", ")", ";", "}" ]
Convert radix-64 to binary array @param {String | ReadableStream<String>} t radix-64 string to convert @param {bool} u if true, input is interpreted as URL-safe @returns {Uint8Array | ReadableStream<Uint8Array>} binary array version of input string @static
[ "Convert", "radix", "-", "64", "to", "binary", "array" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/encoding/base64.js#L106-L129
7,463
openpgpjs/openpgpjs
src/crypto/public_key/elliptic/ecdh.js
genPublicEphemeralKey
async function genPublicEphemeralKey(curve, Q) { if (curve.name === 'curve25519') { const { secretKey: d } = nacl.box.keyPair(); const { secretKey, sharedKey } = await genPrivateEphemeralKey(curve, Q, d); let { publicKey } = nacl.box.keyPair.fromSecretKey(secretKey); publicKey = util.concatUint8Array([new Uint8Array([0x40]), publicKey]); return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below } const v = await curve.genKeyPair(); Q = curve.keyFromPublic(Q); const publicKey = new Uint8Array(v.getPublic()); const S = v.derive(Q); const len = curve.curve.curve.p.byteLength(); const sharedKey = S.toArrayLike(Uint8Array, 'be', len); return { publicKey, sharedKey }; }
javascript
async function genPublicEphemeralKey(curve, Q) { if (curve.name === 'curve25519') { const { secretKey: d } = nacl.box.keyPair(); const { secretKey, sharedKey } = await genPrivateEphemeralKey(curve, Q, d); let { publicKey } = nacl.box.keyPair.fromSecretKey(secretKey); publicKey = util.concatUint8Array([new Uint8Array([0x40]), publicKey]); return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below } const v = await curve.genKeyPair(); Q = curve.keyFromPublic(Q); const publicKey = new Uint8Array(v.getPublic()); const S = v.derive(Q); const len = curve.curve.curve.p.byteLength(); const sharedKey = S.toArrayLike(Uint8Array, 'be', len); return { publicKey, sharedKey }; }
[ "async", "function", "genPublicEphemeralKey", "(", "curve", ",", "Q", ")", "{", "if", "(", "curve", ".", "name", "===", "'curve25519'", ")", "{", "const", "{", "secretKey", ":", "d", "}", "=", "nacl", ".", "box", ".", "keyPair", "(", ")", ";", "const", "{", "secretKey", ",", "sharedKey", "}", "=", "await", "genPrivateEphemeralKey", "(", "curve", ",", "Q", ",", "d", ")", ";", "let", "{", "publicKey", "}", "=", "nacl", ".", "box", ".", "keyPair", ".", "fromSecretKey", "(", "secretKey", ")", ";", "publicKey", "=", "util", ".", "concatUint8Array", "(", "[", "new", "Uint8Array", "(", "[", "0x40", "]", ")", ",", "publicKey", "]", ")", ";", "return", "{", "publicKey", ",", "sharedKey", "}", ";", "// Note: sharedKey is little-endian here, unlike below", "}", "const", "v", "=", "await", "curve", ".", "genKeyPair", "(", ")", ";", "Q", "=", "curve", ".", "keyFromPublic", "(", "Q", ")", ";", "const", "publicKey", "=", "new", "Uint8Array", "(", "v", ".", "getPublic", "(", ")", ")", ";", "const", "S", "=", "v", ".", "derive", "(", "Q", ")", ";", "const", "len", "=", "curve", ".", "curve", ".", "curve", ".", "p", ".", "byteLength", "(", ")", ";", "const", "sharedKey", "=", "S", ".", "toArrayLike", "(", "Uint8Array", ",", "'be'", ",", "len", ")", ";", "return", "{", "publicKey", ",", "sharedKey", "}", ";", "}" ]
Generate ECDHE ephemeral key and secret from public key @param {Curve} curve Elliptic curve object @param {Uint8Array} Q Recipient public key @returns {Promise<{V: Uint8Array, S: BN}>} Returns public part of ephemeral key and generated ephemeral secret @async
[ "Generate", "ECDHE", "ephemeral", "key", "and", "secret", "from", "public", "key" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/crypto/public_key/elliptic/ecdh.js#L86-L101
7,464
openpgpjs/openpgpjs
src/crypto/public_key/elliptic/ecdh.js
encrypt
async function encrypt(oid, cipher_algo, hash_algo, m, Q, fingerprint) { const curve = new Curve(oid); const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q); const param = buildEcdhParam(enums.publicKey.ecdh, oid, cipher_algo, hash_algo, fingerprint); cipher_algo = enums.read(enums.symmetric, cipher_algo); const Z = await kdf(hash_algo, sharedKey, cipher[cipher_algo].keySize, param); const wrappedKey = aes_kw.wrap(Z, m.toString()); return { publicKey, wrappedKey }; }
javascript
async function encrypt(oid, cipher_algo, hash_algo, m, Q, fingerprint) { const curve = new Curve(oid); const { publicKey, sharedKey } = await genPublicEphemeralKey(curve, Q); const param = buildEcdhParam(enums.publicKey.ecdh, oid, cipher_algo, hash_algo, fingerprint); cipher_algo = enums.read(enums.symmetric, cipher_algo); const Z = await kdf(hash_algo, sharedKey, cipher[cipher_algo].keySize, param); const wrappedKey = aes_kw.wrap(Z, m.toString()); return { publicKey, wrappedKey }; }
[ "async", "function", "encrypt", "(", "oid", ",", "cipher_algo", ",", "hash_algo", ",", "m", ",", "Q", ",", "fingerprint", ")", "{", "const", "curve", "=", "new", "Curve", "(", "oid", ")", ";", "const", "{", "publicKey", ",", "sharedKey", "}", "=", "await", "genPublicEphemeralKey", "(", "curve", ",", "Q", ")", ";", "const", "param", "=", "buildEcdhParam", "(", "enums", ".", "publicKey", ".", "ecdh", ",", "oid", ",", "cipher_algo", ",", "hash_algo", ",", "fingerprint", ")", ";", "cipher_algo", "=", "enums", ".", "read", "(", "enums", ".", "symmetric", ",", "cipher_algo", ")", ";", "const", "Z", "=", "await", "kdf", "(", "hash_algo", ",", "sharedKey", ",", "cipher", "[", "cipher_algo", "]", ".", "keySize", ",", "param", ")", ";", "const", "wrappedKey", "=", "aes_kw", ".", "wrap", "(", "Z", ",", "m", ".", "toString", "(", ")", ")", ";", "return", "{", "publicKey", ",", "wrappedKey", "}", ";", "}" ]
Encrypt and wrap a session key @param {module:type/oid} oid Elliptic curve object identifier @param {module:enums.symmetric} cipher_algo Symmetric cipher to use @param {module:enums.hash} hash_algo Hash algorithm to use @param {module:type/mpi} m Value derived from session key (RFC 6637) @param {Uint8Array} Q Recipient public key @param {String} fingerprint Recipient fingerprint @returns {Promise<{V: BN, C: BN}>} Returns public part of ephemeral key and encoded session key @async
[ "Encrypt", "and", "wrap", "a", "session", "key" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/crypto/public_key/elliptic/ecdh.js#L115-L123
7,465
openpgpjs/openpgpjs
src/crypto/public_key/elliptic/ecdh.js
genPrivateEphemeralKey
async function genPrivateEphemeralKey(curve, V, d) { if (curve.name === 'curve25519') { const one = new BN(1); const mask = one.ushln(255 - 3).sub(one).ushln(3); let secretKey = new BN(d); secretKey = secretKey.or(one.ushln(255 - 1)); secretKey = secretKey.and(mask); secretKey = secretKey.toArrayLike(Uint8Array, 'le', 32); const sharedKey = nacl.scalarMult(secretKey, V.subarray(1)); return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below } V = curve.keyFromPublic(V); d = curve.keyFromPrivate(d); const secretKey = new Uint8Array(d.getPrivate()); const S = d.derive(V); const len = curve.curve.curve.p.byteLength(); const sharedKey = S.toArrayLike(Uint8Array, 'be', len); return { secretKey, sharedKey }; }
javascript
async function genPrivateEphemeralKey(curve, V, d) { if (curve.name === 'curve25519') { const one = new BN(1); const mask = one.ushln(255 - 3).sub(one).ushln(3); let secretKey = new BN(d); secretKey = secretKey.or(one.ushln(255 - 1)); secretKey = secretKey.and(mask); secretKey = secretKey.toArrayLike(Uint8Array, 'le', 32); const sharedKey = nacl.scalarMult(secretKey, V.subarray(1)); return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below } V = curve.keyFromPublic(V); d = curve.keyFromPrivate(d); const secretKey = new Uint8Array(d.getPrivate()); const S = d.derive(V); const len = curve.curve.curve.p.byteLength(); const sharedKey = S.toArrayLike(Uint8Array, 'be', len); return { secretKey, sharedKey }; }
[ "async", "function", "genPrivateEphemeralKey", "(", "curve", ",", "V", ",", "d", ")", "{", "if", "(", "curve", ".", "name", "===", "'curve25519'", ")", "{", "const", "one", "=", "new", "BN", "(", "1", ")", ";", "const", "mask", "=", "one", ".", "ushln", "(", "255", "-", "3", ")", ".", "sub", "(", "one", ")", ".", "ushln", "(", "3", ")", ";", "let", "secretKey", "=", "new", "BN", "(", "d", ")", ";", "secretKey", "=", "secretKey", ".", "or", "(", "one", ".", "ushln", "(", "255", "-", "1", ")", ")", ";", "secretKey", "=", "secretKey", ".", "and", "(", "mask", ")", ";", "secretKey", "=", "secretKey", ".", "toArrayLike", "(", "Uint8Array", ",", "'le'", ",", "32", ")", ";", "const", "sharedKey", "=", "nacl", ".", "scalarMult", "(", "secretKey", ",", "V", ".", "subarray", "(", "1", ")", ")", ";", "return", "{", "secretKey", ",", "sharedKey", "}", ";", "// Note: sharedKey is little-endian here, unlike below", "}", "V", "=", "curve", ".", "keyFromPublic", "(", "V", ")", ";", "d", "=", "curve", ".", "keyFromPrivate", "(", "d", ")", ";", "const", "secretKey", "=", "new", "Uint8Array", "(", "d", ".", "getPrivate", "(", ")", ")", ";", "const", "S", "=", "d", ".", "derive", "(", "V", ")", ";", "const", "len", "=", "curve", ".", "curve", ".", "curve", ".", "p", ".", "byteLength", "(", ")", ";", "const", "sharedKey", "=", "S", ".", "toArrayLike", "(", "Uint8Array", ",", "'be'", ",", "len", ")", ";", "return", "{", "secretKey", ",", "sharedKey", "}", ";", "}" ]
Generate ECDHE secret from private key and public part of ephemeral key @param {Curve} curve Elliptic curve object @param {Uint8Array} V Public part of ephemeral key @param {Uint8Array} d Recipient private key @returns {Promise<BN>} Generated ephemeral secret @async
[ "Generate", "ECDHE", "secret", "from", "private", "key", "and", "public", "part", "of", "ephemeral", "key" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/crypto/public_key/elliptic/ecdh.js#L134-L152
7,466
openpgpjs/openpgpjs
src/crypto/public_key/elliptic/ecdh.js
decrypt
async function decrypt(oid, cipher_algo, hash_algo, V, C, d, fingerprint) { const curve = new Curve(oid); const { sharedKey } = await genPrivateEphemeralKey(curve, V, d); const param = buildEcdhParam(enums.publicKey.ecdh, oid, cipher_algo, hash_algo, fingerprint); cipher_algo = enums.read(enums.symmetric, cipher_algo); let err; for (let i = 0; i < 3; i++) { try { // Work around old go crypto bug and old OpenPGP.js bug, respectively. const Z = await kdf(hash_algo, sharedKey, cipher[cipher_algo].keySize, param, i === 1, i === 2); return new BN(aes_kw.unwrap(Z, C)); } catch (e) { err = e; } } throw err; }
javascript
async function decrypt(oid, cipher_algo, hash_algo, V, C, d, fingerprint) { const curve = new Curve(oid); const { sharedKey } = await genPrivateEphemeralKey(curve, V, d); const param = buildEcdhParam(enums.publicKey.ecdh, oid, cipher_algo, hash_algo, fingerprint); cipher_algo = enums.read(enums.symmetric, cipher_algo); let err; for (let i = 0; i < 3; i++) { try { // Work around old go crypto bug and old OpenPGP.js bug, respectively. const Z = await kdf(hash_algo, sharedKey, cipher[cipher_algo].keySize, param, i === 1, i === 2); return new BN(aes_kw.unwrap(Z, C)); } catch (e) { err = e; } } throw err; }
[ "async", "function", "decrypt", "(", "oid", ",", "cipher_algo", ",", "hash_algo", ",", "V", ",", "C", ",", "d", ",", "fingerprint", ")", "{", "const", "curve", "=", "new", "Curve", "(", "oid", ")", ";", "const", "{", "sharedKey", "}", "=", "await", "genPrivateEphemeralKey", "(", "curve", ",", "V", ",", "d", ")", ";", "const", "param", "=", "buildEcdhParam", "(", "enums", ".", "publicKey", ".", "ecdh", ",", "oid", ",", "cipher_algo", ",", "hash_algo", ",", "fingerprint", ")", ";", "cipher_algo", "=", "enums", ".", "read", "(", "enums", ".", "symmetric", ",", "cipher_algo", ")", ";", "let", "err", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "3", ";", "i", "++", ")", "{", "try", "{", "// Work around old go crypto bug and old OpenPGP.js bug, respectively.", "const", "Z", "=", "await", "kdf", "(", "hash_algo", ",", "sharedKey", ",", "cipher", "[", "cipher_algo", "]", ".", "keySize", ",", "param", ",", "i", "===", "1", ",", "i", "===", "2", ")", ";", "return", "new", "BN", "(", "aes_kw", ".", "unwrap", "(", "Z", ",", "C", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "err", "=", "e", ";", "}", "}", "throw", "err", ";", "}" ]
Decrypt and unwrap the value derived from session key @param {module:type/oid} oid Elliptic curve object identifier @param {module:enums.symmetric} cipher_algo Symmetric cipher to use @param {module:enums.hash} hash_algo Hash algorithm to use @param {Uint8Array} V Public part of ephemeral key @param {Uint8Array} C Encrypted and wrapped value derived from session key @param {Uint8Array} d Recipient private key @param {String} fingerprint Recipient fingerprint @returns {Promise<BN>} Value derived from session @async
[ "Decrypt", "and", "unwrap", "the", "value", "derived", "from", "session", "key" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/crypto/public_key/elliptic/ecdh.js#L167-L183
7,467
openpgpjs/openpgpjs
src/keyring/keyring.js
emailCheck
function emailCheck(email, key) { email = email.toLowerCase(); // escape email before using in regular expression const emailEsc = email.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const emailRegex = new RegExp('<' + emailEsc + '>'); const userIds = key.getUserIds(); for (let i = 0; i < userIds.length; i++) { const userId = userIds[i].toLowerCase(); if (email === userId || emailRegex.test(userId)) { return true; } } return false; }
javascript
function emailCheck(email, key) { email = email.toLowerCase(); // escape email before using in regular expression const emailEsc = email.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const emailRegex = new RegExp('<' + emailEsc + '>'); const userIds = key.getUserIds(); for (let i = 0; i < userIds.length; i++) { const userId = userIds[i].toLowerCase(); if (email === userId || emailRegex.test(userId)) { return true; } } return false; }
[ "function", "emailCheck", "(", "email", ",", "key", ")", "{", "email", "=", "email", ".", "toLowerCase", "(", ")", ";", "// escape email before using in regular expression", "const", "emailEsc", "=", "email", ".", "replace", "(", "/", "[.*+?^${}()|[\\]\\\\]", "/", "g", ",", "\"\\\\$&\"", ")", ";", "const", "emailRegex", "=", "new", "RegExp", "(", "'<'", "+", "emailEsc", "+", "'>'", ")", ";", "const", "userIds", "=", "key", ".", "getUserIds", "(", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "userIds", ".", "length", ";", "i", "++", ")", "{", "const", "userId", "=", "userIds", "[", "i", "]", ".", "toLowerCase", "(", ")", ";", "if", "(", "email", "===", "userId", "||", "emailRegex", ".", "test", "(", "userId", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks a key to see if it matches the specified email address @private @param {String} email email address to search for @param {module:key.Key} key The key to be checked. @returns {Boolean} True if the email address is defined in the specified key
[ "Checks", "a", "key", "to", "see", "if", "it", "matches", "the", "specified", "email", "address" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/keyring/keyring.js#L130-L143
7,468
openpgpjs/openpgpjs
src/keyring/keyring.js
keyIdCheck
function keyIdCheck(keyId, key) { if (keyId.length === 16) { return keyId === key.getKeyId().toHex(); } return keyId === key.getFingerprint(); }
javascript
function keyIdCheck(keyId, key) { if (keyId.length === 16) { return keyId === key.getKeyId().toHex(); } return keyId === key.getFingerprint(); }
[ "function", "keyIdCheck", "(", "keyId", ",", "key", ")", "{", "if", "(", "keyId", ".", "length", "===", "16", ")", "{", "return", "keyId", "===", "key", ".", "getKeyId", "(", ")", ".", "toHex", "(", ")", ";", "}", "return", "keyId", "===", "key", ".", "getFingerprint", "(", ")", ";", "}" ]
Checks a key to see if it matches the specified keyid @private @param {String} keyId provided as string of lowercase hex number withouth 0x prefix (can be 16-character key ID or fingerprint) @param {module:key.Key|module:key.SubKey} key The key to be checked @returns {Boolean} True if key has the specified keyid
[ "Checks", "a", "key", "to", "see", "if", "it", "matches", "the", "specified", "keyid" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/keyring/keyring.js#L153-L158
7,469
openpgpjs/openpgpjs
src/packet/signature.js
write_sub_packet
function write_sub_packet(type, data) { const arr = []; arr.push(packet.writeSimpleLength(data.length + 1)); arr.push(new Uint8Array([type])); arr.push(data); return util.concat(arr); }
javascript
function write_sub_packet(type, data) { const arr = []; arr.push(packet.writeSimpleLength(data.length + 1)); arr.push(new Uint8Array([type])); arr.push(data); return util.concat(arr); }
[ "function", "write_sub_packet", "(", "type", ",", "data", ")", "{", "const", "arr", "=", "[", "]", ";", "arr", ".", "push", "(", "packet", ".", "writeSimpleLength", "(", "data", ".", "length", "+", "1", ")", ")", ";", "arr", ".", "push", "(", "new", "Uint8Array", "(", "[", "type", "]", ")", ")", ";", "arr", ".", "push", "(", "data", ")", ";", "return", "util", ".", "concat", "(", "arr", ")", ";", "}" ]
Creates a string representation of a sub signature packet @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1} @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2} @param {Integer} type subpacket signature type. @param {String} data data to be included @returns {String} a string-representation of a sub signature packet @private
[ "Creates", "a", "string", "representation", "of", "a", "sub", "signature", "packet" ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/packet/signature.js#L337-L343
7,470
openpgpjs/openpgpjs
src/crypto/cipher/cast5.js
f1
function f1(d, m, r) { const t = m + d; const I = (t << r) | (t >>> (32 - r)); return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255]; }
javascript
function f1(d, m, r) { const t = m + d; const I = (t << r) | (t >>> (32 - r)); return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255]; }
[ "function", "f1", "(", "d", ",", "m", ",", "r", ")", "{", "const", "t", "=", "m", "+", "d", ";", "const", "I", "=", "(", "t", "<<", "r", ")", "|", "(", "t", ">>>", "(", "32", "-", "r", ")", ")", ";", "return", "(", "(", "sBox", "[", "0", "]", "[", "I", ">>>", "24", "]", "^", "sBox", "[", "1", "]", "[", "(", "I", ">>>", "16", ")", "&", "255", "]", ")", "-", "sBox", "[", "2", "]", "[", "(", "I", ">>>", "8", ")", "&", "255", "]", ")", "+", "sBox", "[", "3", "]", "[", "I", "&", "255", "]", ";", "}" ]
These are the three 'f' functions. See RFC 2144, section 2.2.
[ "These", "are", "the", "three", "f", "functions", ".", "See", "RFC", "2144", "section", "2", ".", "2", "." ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/crypto/cipher/cast5.js#L298-L302
7,471
openpgpjs/openpgpjs
src/crypto/pkcs5.js
decode
function decode(msg) { const len = msg.length; if (len > 0) { const c = msg.charCodeAt(len - 1); if (c >= 1 && c <= 8) { const provided = msg.substr(len - c); const computed = String.fromCharCode(c).repeat(c); if (provided === computed) { return msg.substr(0, len - c); } } } throw new Error('Invalid padding'); }
javascript
function decode(msg) { const len = msg.length; if (len > 0) { const c = msg.charCodeAt(len - 1); if (c >= 1 && c <= 8) { const provided = msg.substr(len - c); const computed = String.fromCharCode(c).repeat(c); if (provided === computed) { return msg.substr(0, len - c); } } } throw new Error('Invalid padding'); }
[ "function", "decode", "(", "msg", ")", "{", "const", "len", "=", "msg", ".", "length", ";", "if", "(", "len", ">", "0", ")", "{", "const", "c", "=", "msg", ".", "charCodeAt", "(", "len", "-", "1", ")", ";", "if", "(", "c", ">=", "1", "&&", "c", "<=", "8", ")", "{", "const", "provided", "=", "msg", ".", "substr", "(", "len", "-", "c", ")", ";", "const", "computed", "=", "String", ".", "fromCharCode", "(", "c", ")", ".", "repeat", "(", "c", ")", ";", "if", "(", "provided", "===", "computed", ")", "{", "return", "msg", ".", "substr", "(", "0", ",", "len", "-", "c", ")", ";", "}", "}", "}", "throw", "new", "Error", "(", "'Invalid padding'", ")", ";", "}" ]
Remove pkcs5 padding from a string. @param {String} msg Text to remove padding from @returns {String} Text with padding removed
[ "Remove", "pkcs5", "padding", "from", "a", "string", "." ]
54f3eb5870e4e0611965003e276af786ec419470
https://github.com/openpgpjs/openpgpjs/blob/54f3eb5870e4e0611965003e276af786ec419470/src/crypto/pkcs5.js#L40-L53
7,472
balderdashy/waterline
lib/waterline/utils/query/get-query-modifier-methods.js
function(batchSizeOrIteratee, iteratee) { assert(this._wlQueryInfo.method === 'stream', 'Cannot chain `.eachBatch()` onto the `.'+this._wlQueryInfo.method+'()` method. The `.eachBatch()` method is only chainable to `.stream()`. (In fact, this shouldn\'t even be possible! So the fact that you are seeing this message at all is, itself, likely due to a bug in Waterline.)'); if (arguments.length > 2) { throw new Error('Invalid usage for `.eachBatch()` -- no more than 2 arguments should be passed in.'); }//• if (iteratee === undefined) { this._wlQueryInfo.eachBatchFn = batchSizeOrIteratee; } else { this._wlQueryInfo.eachBatchFn = iteratee; // Apply custom batch size: // > If meta already exists, merge on top of it. // > (this is important for when this method is combined with .meta()/.usingConnection()/etc) if (this._wlQueryInfo.meta) { _.extend(this._wlQueryInfo.meta, { batchSize: batchSizeOrIteratee }); } else { this._wlQueryInfo.meta = { batchSize: batchSizeOrIteratee }; } } return this; }
javascript
function(batchSizeOrIteratee, iteratee) { assert(this._wlQueryInfo.method === 'stream', 'Cannot chain `.eachBatch()` onto the `.'+this._wlQueryInfo.method+'()` method. The `.eachBatch()` method is only chainable to `.stream()`. (In fact, this shouldn\'t even be possible! So the fact that you are seeing this message at all is, itself, likely due to a bug in Waterline.)'); if (arguments.length > 2) { throw new Error('Invalid usage for `.eachBatch()` -- no more than 2 arguments should be passed in.'); }//• if (iteratee === undefined) { this._wlQueryInfo.eachBatchFn = batchSizeOrIteratee; } else { this._wlQueryInfo.eachBatchFn = iteratee; // Apply custom batch size: // > If meta already exists, merge on top of it. // > (this is important for when this method is combined with .meta()/.usingConnection()/etc) if (this._wlQueryInfo.meta) { _.extend(this._wlQueryInfo.meta, { batchSize: batchSizeOrIteratee }); } else { this._wlQueryInfo.meta = { batchSize: batchSizeOrIteratee }; } } return this; }
[ "function", "(", "batchSizeOrIteratee", ",", "iteratee", ")", "{", "assert", "(", "this", ".", "_wlQueryInfo", ".", "method", "===", "'stream'", ",", "'Cannot chain `.eachBatch()` onto the `.'", "+", "this", ".", "_wlQueryInfo", ".", "method", "+", "'()` method. The `.eachBatch()` method is only chainable to `.stream()`. (In fact, this shouldn\\'t even be possible! So the fact that you are seeing this message at all is, itself, likely due to a bug in Waterline.)'", ")", ";", "if", "(", "arguments", ".", "length", ">", "2", ")", "{", "throw", "new", "Error", "(", "'Invalid usage for `.eachBatch()` -- no more than 2 arguments should be passed in.'", ")", ";", "}", "//•", "if", "(", "iteratee", "===", "undefined", ")", "{", "this", ".", "_wlQueryInfo", ".", "eachBatchFn", "=", "batchSizeOrIteratee", ";", "}", "else", "{", "this", ".", "_wlQueryInfo", ".", "eachBatchFn", "=", "iteratee", ";", "// Apply custom batch size:", "// > If meta already exists, merge on top of it.", "// > (this is important for when this method is combined with .meta()/.usingConnection()/etc)", "if", "(", "this", ".", "_wlQueryInfo", ".", "meta", ")", "{", "_", ".", "extend", "(", "this", ".", "_wlQueryInfo", ".", "meta", ",", "{", "batchSize", ":", "batchSizeOrIteratee", "}", ")", ";", "}", "else", "{", "this", ".", "_wlQueryInfo", ".", "meta", "=", "{", "batchSize", ":", "batchSizeOrIteratee", "}", ";", "}", "}", "return", "this", ";", "}" ]
Add an iteratee to the query @param {Number|Function} batchSizeOrIteratee @param {Function} iteratee @returns {Query}
[ "Add", "an", "iteratee", "to", "the", "query" ]
1d5a3dc6e65fe69c061a72249019adfcf3c52cb6
https://github.com/balderdashy/waterline/blob/1d5a3dc6e65fe69c061a72249019adfcf3c52cb6/lib/waterline/utils/query/get-query-modifier-methods.js#L83-L107
7,473
balderdashy/waterline
lib/waterline/utils/query/get-query-modifier-methods.js
function(values) { if (this._wlQueryInfo.method === 'create') { console.warn( 'Deprecation warning: In future versions of Waterline, the use of .set() with .create()\n'+ 'will no longer be supported. In the past, you could use .set() to provide the initial\n'+ 'skeleton of a new record to create (like `.create().set({})`)-- but really .set() should\n'+ 'only be used with .update(). So instead, please change this code so that it just passes in\n'+ 'the initial new record as the first argument to `.create().`' ); this._wlQueryInfo.newRecord = values; } else if (this._wlQueryInfo.method === 'createEach') { console.warn( 'Deprecation warning: In future versions of Waterline, the use of .set() with .createEach()\n'+ 'will no longer be supported. In the past, you could use .set() to provide an array of\n'+ 'new records to create (like `.createEach().set([{}, {}])`)-- but really .set() was designed\n'+ 'to be used with .update() only. So instead, please change this code so that it just\n'+ 'passes in the initial new record as the first argument to `.createEach().`' ); this._wlQueryInfo.newRecords = values; } else { this._wlQueryInfo.valuesToSet = values; } return this; }
javascript
function(values) { if (this._wlQueryInfo.method === 'create') { console.warn( 'Deprecation warning: In future versions of Waterline, the use of .set() with .create()\n'+ 'will no longer be supported. In the past, you could use .set() to provide the initial\n'+ 'skeleton of a new record to create (like `.create().set({})`)-- but really .set() should\n'+ 'only be used with .update(). So instead, please change this code so that it just passes in\n'+ 'the initial new record as the first argument to `.create().`' ); this._wlQueryInfo.newRecord = values; } else if (this._wlQueryInfo.method === 'createEach') { console.warn( 'Deprecation warning: In future versions of Waterline, the use of .set() with .createEach()\n'+ 'will no longer be supported. In the past, you could use .set() to provide an array of\n'+ 'new records to create (like `.createEach().set([{}, {}])`)-- but really .set() was designed\n'+ 'to be used with .update() only. So instead, please change this code so that it just\n'+ 'passes in the initial new record as the first argument to `.createEach().`' ); this._wlQueryInfo.newRecords = values; } else { this._wlQueryInfo.valuesToSet = values; } return this; }
[ "function", "(", "values", ")", "{", "if", "(", "this", ".", "_wlQueryInfo", ".", "method", "===", "'create'", ")", "{", "console", ".", "warn", "(", "'Deprecation warning: In future versions of Waterline, the use of .set() with .create()\\n'", "+", "'will no longer be supported. In the past, you could use .set() to provide the initial\\n'", "+", "'skeleton of a new record to create (like `.create().set({})`)-- but really .set() should\\n'", "+", "'only be used with .update(). So instead, please change this code so that it just passes in\\n'", "+", "'the initial new record as the first argument to `.create().`'", ")", ";", "this", ".", "_wlQueryInfo", ".", "newRecord", "=", "values", ";", "}", "else", "if", "(", "this", ".", "_wlQueryInfo", ".", "method", "===", "'createEach'", ")", "{", "console", ".", "warn", "(", "'Deprecation warning: In future versions of Waterline, the use of .set() with .createEach()\\n'", "+", "'will no longer be supported. In the past, you could use .set() to provide an array of\\n'", "+", "'new records to create (like `.createEach().set([{}, {}])`)-- but really .set() was designed\\n'", "+", "'to be used with .update() only. So instead, please change this code so that it just\\n'", "+", "'passes in the initial new record as the first argument to `.createEach().`'", ")", ";", "this", ".", "_wlQueryInfo", ".", "newRecords", "=", "values", ";", "}", "else", "{", "this", ".", "_wlQueryInfo", ".", "valuesToSet", "=", "values", ";", "}", "return", "this", ";", "}" ]
Add values to be used in update or create query @param {Dictionary} values @returns {Query}
[ "Add", "values", "to", "be", "used", "in", "update", "or", "create", "query" ]
1d5a3dc6e65fe69c061a72249019adfcf3c52cb6
https://github.com/balderdashy/waterline/blob/1d5a3dc6e65fe69c061a72249019adfcf3c52cb6/lib/waterline/utils/query/get-query-modifier-methods.js#L120-L148
7,474
balderdashy/waterline
lib/waterline/utils/query/get-query-modifier-methods.js
function(limit) { if (!this._alreadyInitiallyExpandedCriteria) { this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria); this._alreadyInitiallyExpandedCriteria = true; }//>- this._wlQueryInfo.criteria.limit = limit; return this; }
javascript
function(limit) { if (!this._alreadyInitiallyExpandedCriteria) { this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria); this._alreadyInitiallyExpandedCriteria = true; }//>- this._wlQueryInfo.criteria.limit = limit; return this; }
[ "function", "(", "limit", ")", "{", "if", "(", "!", "this", ".", "_alreadyInitiallyExpandedCriteria", ")", "{", "this", ".", "_wlQueryInfo", ".", "criteria", "=", "expandWhereShorthand", "(", "this", ".", "_wlQueryInfo", ".", "criteria", ")", ";", "this", ".", "_alreadyInitiallyExpandedCriteria", "=", "true", ";", "}", "//>-", "this", ".", "_wlQueryInfo", ".", "criteria", ".", "limit", "=", "limit", ";", "return", "this", ";", "}" ]
Add a `limit` clause to the query's criteria. @param {Number} number to limit @returns {Query}
[ "Add", "a", "limit", "clause", "to", "the", "query", "s", "criteria", "." ]
1d5a3dc6e65fe69c061a72249019adfcf3c52cb6
https://github.com/balderdashy/waterline/blob/1d5a3dc6e65fe69c061a72249019adfcf3c52cb6/lib/waterline/utils/query/get-query-modifier-methods.js#L274-L284
7,475
balderdashy/waterline
lib/waterline/utils/query/get-query-modifier-methods.js
function(skip) { if (!this._alreadyInitiallyExpandedCriteria) { this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria); this._alreadyInitiallyExpandedCriteria = true; }//>- this._wlQueryInfo.criteria.skip = skip; return this; }
javascript
function(skip) { if (!this._alreadyInitiallyExpandedCriteria) { this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria); this._alreadyInitiallyExpandedCriteria = true; }//>- this._wlQueryInfo.criteria.skip = skip; return this; }
[ "function", "(", "skip", ")", "{", "if", "(", "!", "this", ".", "_alreadyInitiallyExpandedCriteria", ")", "{", "this", ".", "_wlQueryInfo", ".", "criteria", "=", "expandWhereShorthand", "(", "this", ".", "_wlQueryInfo", ".", "criteria", ")", ";", "this", ".", "_alreadyInitiallyExpandedCriteria", "=", "true", ";", "}", "//>-", "this", ".", "_wlQueryInfo", ".", "criteria", ".", "skip", "=", "skip", ";", "return", "this", ";", "}" ]
Add a `skip` clause to the query's criteria. @param {Number} number to skip @returns {Query}
[ "Add", "a", "skip", "clause", "to", "the", "query", "s", "criteria", "." ]
1d5a3dc6e65fe69c061a72249019adfcf3c52cb6
https://github.com/balderdashy/waterline/blob/1d5a3dc6e65fe69c061a72249019adfcf3c52cb6/lib/waterline/utils/query/get-query-modifier-methods.js#L293-L303
7,476
balderdashy/waterline
lib/waterline/utils/query/get-query-modifier-methods.js
function(sortClause) { if (!this._alreadyInitiallyExpandedCriteria) { this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria); this._alreadyInitiallyExpandedCriteria = true; }//>- this._wlQueryInfo.criteria.sort = sortClause; return this; }
javascript
function(sortClause) { if (!this._alreadyInitiallyExpandedCriteria) { this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria); this._alreadyInitiallyExpandedCriteria = true; }//>- this._wlQueryInfo.criteria.sort = sortClause; return this; }
[ "function", "(", "sortClause", ")", "{", "if", "(", "!", "this", ".", "_alreadyInitiallyExpandedCriteria", ")", "{", "this", ".", "_wlQueryInfo", ".", "criteria", "=", "expandWhereShorthand", "(", "this", ".", "_wlQueryInfo", ".", "criteria", ")", ";", "this", ".", "_alreadyInitiallyExpandedCriteria", "=", "true", ";", "}", "//>-", "this", ".", "_wlQueryInfo", ".", "criteria", ".", "sort", "=", "sortClause", ";", "return", "this", ";", "}" ]
Add a `sort` clause to the criteria object @param {Ref} sortClause @returns {Query}
[ "Add", "a", "sort", "clause", "to", "the", "criteria", "object" ]
1d5a3dc6e65fe69c061a72249019adfcf3c52cb6
https://github.com/balderdashy/waterline/blob/1d5a3dc6e65fe69c061a72249019adfcf3c52cb6/lib/waterline/utils/query/get-query-modifier-methods.js#L432-L442
7,477
balderdashy/waterline
lib/waterline/utils/query/get-query-modifier-methods.js
function(selectAttributes) { if (!this._alreadyInitiallyExpandedCriteria) { this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria); this._alreadyInitiallyExpandedCriteria = true; }//>- this._wlQueryInfo.criteria.select = selectAttributes; return this; }
javascript
function(selectAttributes) { if (!this._alreadyInitiallyExpandedCriteria) { this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria); this._alreadyInitiallyExpandedCriteria = true; }//>- this._wlQueryInfo.criteria.select = selectAttributes; return this; }
[ "function", "(", "selectAttributes", ")", "{", "if", "(", "!", "this", ".", "_alreadyInitiallyExpandedCriteria", ")", "{", "this", ".", "_wlQueryInfo", ".", "criteria", "=", "expandWhereShorthand", "(", "this", ".", "_wlQueryInfo", ".", "criteria", ")", ";", "this", ".", "_alreadyInitiallyExpandedCriteria", "=", "true", ";", "}", "//>-", "this", ".", "_wlQueryInfo", ".", "criteria", ".", "select", "=", "selectAttributes", ";", "return", "this", ";", "}" ]
Add projections to the query. @param {Array} attributes to select @returns {Query}
[ "Add", "projections", "to", "the", "query", "." ]
1d5a3dc6e65fe69c061a72249019adfcf3c52cb6
https://github.com/balderdashy/waterline/blob/1d5a3dc6e65fe69c061a72249019adfcf3c52cb6/lib/waterline/utils/query/get-query-modifier-methods.js#L457-L467
7,478
balderdashy/waterline
lib/waterline/utils/query/get-query-modifier-methods.js
function(omitAttributes) { if (!this._alreadyInitiallyExpandedCriteria) { this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria); this._alreadyInitiallyExpandedCriteria = true; }//>- this._wlQueryInfo.criteria.omit = omitAttributes; return this; }
javascript
function(omitAttributes) { if (!this._alreadyInitiallyExpandedCriteria) { this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria); this._alreadyInitiallyExpandedCriteria = true; }//>- this._wlQueryInfo.criteria.omit = omitAttributes; return this; }
[ "function", "(", "omitAttributes", ")", "{", "if", "(", "!", "this", ".", "_alreadyInitiallyExpandedCriteria", ")", "{", "this", ".", "_wlQueryInfo", ".", "criteria", "=", "expandWhereShorthand", "(", "this", ".", "_wlQueryInfo", ".", "criteria", ")", ";", "this", ".", "_alreadyInitiallyExpandedCriteria", "=", "true", ";", "}", "//>-", "this", ".", "_wlQueryInfo", ".", "criteria", ".", "omit", "=", "omitAttributes", ";", "return", "this", ";", "}" ]
Add an omit clause to the query's criteria. @param {Array} attributes to select @returns {Query}
[ "Add", "an", "omit", "clause", "to", "the", "query", "s", "criteria", "." ]
1d5a3dc6e65fe69c061a72249019adfcf3c52cb6
https://github.com/balderdashy/waterline/blob/1d5a3dc6e65fe69c061a72249019adfcf3c52cb6/lib/waterline/utils/query/get-query-modifier-methods.js#L475-L485
7,479
balderdashy/waterline
lib/waterline/utils/query/get-query-modifier-methods.js
function(whereCriteria) { if (!this._alreadyInitiallyExpandedCriteria) { this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria); this._alreadyInitiallyExpandedCriteria = true; }//>- this._wlQueryInfo.criteria.where = whereCriteria; return this; }
javascript
function(whereCriteria) { if (!this._alreadyInitiallyExpandedCriteria) { this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria); this._alreadyInitiallyExpandedCriteria = true; }//>- this._wlQueryInfo.criteria.where = whereCriteria; return this; }
[ "function", "(", "whereCriteria", ")", "{", "if", "(", "!", "this", ".", "_alreadyInitiallyExpandedCriteria", ")", "{", "this", ".", "_wlQueryInfo", ".", "criteria", "=", "expandWhereShorthand", "(", "this", ".", "_wlQueryInfo", ".", "criteria", ")", ";", "this", ".", "_alreadyInitiallyExpandedCriteria", "=", "true", ";", "}", "//>-", "this", ".", "_wlQueryInfo", ".", "criteria", ".", "where", "=", "whereCriteria", ";", "return", "this", ";", "}" ]
Add a `where` clause to the query's criteria. @param {Dictionary} criteria to append @returns {Query}
[ "Add", "a", "where", "clause", "to", "the", "query", "s", "criteria", "." ]
1d5a3dc6e65fe69c061a72249019adfcf3c52cb6
https://github.com/balderdashy/waterline/blob/1d5a3dc6e65fe69c061a72249019adfcf3c52cb6/lib/waterline/utils/query/get-query-modifier-methods.js#L501-L511
7,480
ampproject/worker-dom
demo/preact-dbmon/dbmon.js
extend
function extend(obj, props) { for (var i in props) { obj[i] = props[i]; } return obj; }
javascript
function extend(obj, props) { for (var i in props) { obj[i] = props[i]; } return obj; }
[ "function", "extend", "(", "obj", ",", "props", ")", "{", "for", "(", "var", "i", "in", "props", ")", "{", "obj", "[", "i", "]", "=", "props", "[", "i", "]", ";", "}", "return", "obj", ";", "}" ]
Copy all properties from `props` onto `obj`. @param {Object} obj Object onto which properties should be copied. @param {Object} props Object from which to copy properties. @return obj @private
[ "Copy", "all", "properties", "from", "props", "onto", "obj", "." ]
d1c7bee8c2259c61e25eb4d27606ff70e2f02fd4
https://github.com/ampproject/worker-dom/blob/d1c7bee8c2259c61e25eb4d27606ff70e2f02fd4/demo/preact-dbmon/dbmon.js#L136-L141
7,481
ampproject/worker-dom
demo/preact-dbmon/dbmon.js
isNamedNode
function isNamedNode(node, nodeName) { return node.normalizedNodeName === nodeName || node.nodeName.toLowerCase() === nodeName.toLowerCase(); }
javascript
function isNamedNode(node, nodeName) { return node.normalizedNodeName === nodeName || node.nodeName.toLowerCase() === nodeName.toLowerCase(); }
[ "function", "isNamedNode", "(", "node", ",", "nodeName", ")", "{", "return", "node", ".", "normalizedNodeName", "===", "nodeName", "||", "node", ".", "nodeName", ".", "toLowerCase", "(", ")", "===", "nodeName", ".", "toLowerCase", "(", ")", ";", "}" ]
Check if an Element has a given nodeName, case-insensitively. @param {Element} node A DOM Element to inspect the name of. @param {String} nodeName Unnormalized name to compare against.
[ "Check", "if", "an", "Element", "has", "a", "given", "nodeName", "case", "-", "insensitively", "." ]
d1c7bee8c2259c61e25eb4d27606ff70e2f02fd4
https://github.com/ampproject/worker-dom/blob/d1c7bee8c2259c61e25eb4d27606ff70e2f02fd4/demo/preact-dbmon/dbmon.js#L198-L200
7,482
ampproject/worker-dom
demo/preact-dbmon/dbmon.js
createNode
function createNode(nodeName, isSvg) { var node = isSvg ? document.createElementNS('http://www.w3.org/2000/svg', nodeName) : document.createElement(nodeName); node.normalizedNodeName = nodeName; return node; }
javascript
function createNode(nodeName, isSvg) { var node = isSvg ? document.createElementNS('http://www.w3.org/2000/svg', nodeName) : document.createElement(nodeName); node.normalizedNodeName = nodeName; return node; }
[ "function", "createNode", "(", "nodeName", ",", "isSvg", ")", "{", "var", "node", "=", "isSvg", "?", "document", ".", "createElementNS", "(", "'http://www.w3.org/2000/svg'", ",", "nodeName", ")", ":", "document", ".", "createElement", "(", "nodeName", ")", ";", "node", ".", "normalizedNodeName", "=", "nodeName", ";", "return", "node", ";", "}" ]
Create an element with the given nodeName. @param {String} nodeName @param {Boolean} [isSvg=false] If `true`, creates an element within the SVG namespace. @return {Element} node
[ "Create", "an", "element", "with", "the", "given", "nodeName", "." ]
d1c7bee8c2259c61e25eb4d27606ff70e2f02fd4
https://github.com/ampproject/worker-dom/blob/d1c7bee8c2259c61e25eb4d27606ff70e2f02fd4/demo/preact-dbmon/dbmon.js#L231-L235
7,483
ampproject/worker-dom
demo/preact-dbmon/dbmon.js
eventProxy
function eventProxy(e) { return this._listeners[e.type]((options.event && options.event(e)) || e); }
javascript
function eventProxy(e) { return this._listeners[e.type]((options.event && options.event(e)) || e); }
[ "function", "eventProxy", "(", "e", ")", "{", "return", "this", ".", "_listeners", "[", "e", ".", "type", "]", "(", "(", "options", ".", "event", "&&", "options", ".", "event", "(", "e", ")", ")", "||", "e", ")", ";", "}" ]
Proxy an event to hooked event handlers @private
[ "Proxy", "an", "event", "to", "hooked", "event", "handlers" ]
d1c7bee8c2259c61e25eb4d27606ff70e2f02fd4
https://github.com/ampproject/worker-dom/blob/d1c7bee8c2259c61e25eb4d27606ff70e2f02fd4/demo/preact-dbmon/dbmon.js#L316-L318
7,484
ampproject/worker-dom
demo/preact-dbmon/dbmon.js
collectComponent
function collectComponent(component) { var name = component.constructor.name; (components[name] || (components[name] = [])).push(component); }
javascript
function collectComponent(component) { var name = component.constructor.name; (components[name] || (components[name] = [])).push(component); }
[ "function", "collectComponent", "(", "component", ")", "{", "var", "name", "=", "component", ".", "constructor", ".", "name", ";", "(", "components", "[", "name", "]", "||", "(", "components", "[", "name", "]", "=", "[", "]", ")", ")", ".", "push", "(", "component", ")", ";", "}" ]
Reclaim a component for later re-use by the recycler.
[ "Reclaim", "a", "component", "for", "later", "re", "-", "use", "by", "the", "recycler", "." ]
d1c7bee8c2259c61e25eb4d27606ff70e2f02fd4
https://github.com/ampproject/worker-dom/blob/d1c7bee8c2259c61e25eb4d27606ff70e2f02fd4/demo/preact-dbmon/dbmon.js#L629-L632
7,485
ampproject/worker-dom
demo/preact-dbmon/dbmon.js
createComponent
function createComponent(Ctor, props, context) { var list = components[Ctor.name], inst; if (Ctor.prototype && Ctor.prototype.render) { inst = new Ctor(props, context); Component.call(inst, props, context); } else { inst = new Component(props, context); inst.constructor = Ctor; inst.render = doRender; } if (list) { for (var i = list.length; i--; ) { if (list[i].constructor === Ctor) { inst.nextBase = list[i].nextBase; list.splice(i, 1); break; } } } return inst; }
javascript
function createComponent(Ctor, props, context) { var list = components[Ctor.name], inst; if (Ctor.prototype && Ctor.prototype.render) { inst = new Ctor(props, context); Component.call(inst, props, context); } else { inst = new Component(props, context); inst.constructor = Ctor; inst.render = doRender; } if (list) { for (var i = list.length; i--; ) { if (list[i].constructor === Ctor) { inst.nextBase = list[i].nextBase; list.splice(i, 1); break; } } } return inst; }
[ "function", "createComponent", "(", "Ctor", ",", "props", ",", "context", ")", "{", "var", "list", "=", "components", "[", "Ctor", ".", "name", "]", ",", "inst", ";", "if", "(", "Ctor", ".", "prototype", "&&", "Ctor", ".", "prototype", ".", "render", ")", "{", "inst", "=", "new", "Ctor", "(", "props", ",", "context", ")", ";", "Component", ".", "call", "(", "inst", ",", "props", ",", "context", ")", ";", "}", "else", "{", "inst", "=", "new", "Component", "(", "props", ",", "context", ")", ";", "inst", ".", "constructor", "=", "Ctor", ";", "inst", ".", "render", "=", "doRender", ";", "}", "if", "(", "list", ")", "{", "for", "(", "var", "i", "=", "list", ".", "length", ";", "i", "--", ";", ")", "{", "if", "(", "list", "[", "i", "]", ".", "constructor", "===", "Ctor", ")", "{", "inst", ".", "nextBase", "=", "list", "[", "i", "]", ".", "nextBase", ";", "list", ".", "splice", "(", "i", ",", "1", ")", ";", "break", ";", "}", "}", "}", "return", "inst", ";", "}" ]
Create a component. Normalizes differences between PFC's and classful Components.
[ "Create", "a", "component", ".", "Normalizes", "differences", "between", "PFC", "s", "and", "classful", "Components", "." ]
d1c7bee8c2259c61e25eb4d27606ff70e2f02fd4
https://github.com/ampproject/worker-dom/blob/d1c7bee8c2259c61e25eb4d27606ff70e2f02fd4/demo/preact-dbmon/dbmon.js#L635-L658
7,486
ampproject/worker-dom
demo/preact-dbmon/dbmon.js
buildComponentFromVNode
function buildComponentFromVNode(dom, vnode, context, mountAll) { var c = dom && dom._component, originalComponent = c, oldDom = dom, isDirectOwner = c && dom._componentConstructor === vnode.nodeName, isOwner = isDirectOwner, props = getNodeProps(vnode); while (c && !isOwner && (c = c._parentComponent)) { isOwner = c.constructor === vnode.nodeName; } if (c && isOwner && (!mountAll || c._component)) { setComponentProps(c, props, 3, context, mountAll); dom = c.base; } else { if (originalComponent && !isDirectOwner) { unmountComponent(originalComponent); dom = oldDom = null; } c = createComponent(vnode.nodeName, props, context); if (dom && !c.nextBase) { c.nextBase = dom; // passing dom/oldDom as nextBase will recycle it if unused, so bypass recycling on L229: oldDom = null; } setComponentProps(c, props, 1, context, mountAll); dom = c.base; if (oldDom && dom !== oldDom) { oldDom._component = null; recollectNodeTree(oldDom, false); } } return dom; }
javascript
function buildComponentFromVNode(dom, vnode, context, mountAll) { var c = dom && dom._component, originalComponent = c, oldDom = dom, isDirectOwner = c && dom._componentConstructor === vnode.nodeName, isOwner = isDirectOwner, props = getNodeProps(vnode); while (c && !isOwner && (c = c._parentComponent)) { isOwner = c.constructor === vnode.nodeName; } if (c && isOwner && (!mountAll || c._component)) { setComponentProps(c, props, 3, context, mountAll); dom = c.base; } else { if (originalComponent && !isDirectOwner) { unmountComponent(originalComponent); dom = oldDom = null; } c = createComponent(vnode.nodeName, props, context); if (dom && !c.nextBase) { c.nextBase = dom; // passing dom/oldDom as nextBase will recycle it if unused, so bypass recycling on L229: oldDom = null; } setComponentProps(c, props, 1, context, mountAll); dom = c.base; if (oldDom && dom !== oldDom) { oldDom._component = null; recollectNodeTree(oldDom, false); } } return dom; }
[ "function", "buildComponentFromVNode", "(", "dom", ",", "vnode", ",", "context", ",", "mountAll", ")", "{", "var", "c", "=", "dom", "&&", "dom", ".", "_component", ",", "originalComponent", "=", "c", ",", "oldDom", "=", "dom", ",", "isDirectOwner", "=", "c", "&&", "dom", ".", "_componentConstructor", "===", "vnode", ".", "nodeName", ",", "isOwner", "=", "isDirectOwner", ",", "props", "=", "getNodeProps", "(", "vnode", ")", ";", "while", "(", "c", "&&", "!", "isOwner", "&&", "(", "c", "=", "c", ".", "_parentComponent", ")", ")", "{", "isOwner", "=", "c", ".", "constructor", "===", "vnode", ".", "nodeName", ";", "}", "if", "(", "c", "&&", "isOwner", "&&", "(", "!", "mountAll", "||", "c", ".", "_component", ")", ")", "{", "setComponentProps", "(", "c", ",", "props", ",", "3", ",", "context", ",", "mountAll", ")", ";", "dom", "=", "c", ".", "base", ";", "}", "else", "{", "if", "(", "originalComponent", "&&", "!", "isDirectOwner", ")", "{", "unmountComponent", "(", "originalComponent", ")", ";", "dom", "=", "oldDom", "=", "null", ";", "}", "c", "=", "createComponent", "(", "vnode", ".", "nodeName", ",", "props", ",", "context", ")", ";", "if", "(", "dom", "&&", "!", "c", ".", "nextBase", ")", "{", "c", ".", "nextBase", "=", "dom", ";", "// passing dom/oldDom as nextBase will recycle it if unused, so bypass recycling on L229:", "oldDom", "=", "null", ";", "}", "setComponentProps", "(", "c", ",", "props", ",", "1", ",", "context", ",", "mountAll", ")", ";", "dom", "=", "c", ".", "base", ";", "if", "(", "oldDom", "&&", "dom", "!==", "oldDom", ")", "{", "oldDom", ".", "_component", "=", "null", ";", "recollectNodeTree", "(", "oldDom", ",", "false", ")", ";", "}", "}", "return", "dom", ";", "}" ]
Apply the Component referenced by a VNode to the DOM. @param {Element} dom The DOM node to mutate @param {VNode} vnode A Component-referencing VNode @return {Element} dom The created/mutated element @private
[ "Apply", "the", "Component", "referenced", "by", "a", "VNode", "to", "the", "DOM", "." ]
d1c7bee8c2259c61e25eb4d27606ff70e2f02fd4
https://github.com/ampproject/worker-dom/blob/d1c7bee8c2259c61e25eb4d27606ff70e2f02fd4/demo/preact-dbmon/dbmon.js#L850-L886
7,487
ampproject/worker-dom
demo/preact-dbmon/dbmon.js
unmountComponent
function unmountComponent(component) { if (options.beforeUnmount) options.beforeUnmount(component); var base = component.base; component._disable = true; if (component.componentWillUnmount) component.componentWillUnmount(); component.base = null; // recursively tear down & recollect high-order component children: var inner = component._component; if (inner) { unmountComponent(inner); } else if (base) { if (base['__preactattr_'] && base['__preactattr_'].ref) base['__preactattr_'].ref(null); component.nextBase = base; removeNode(base); collectComponent(component); removeChildren(base); } if (component.__ref) component.__ref(null); }
javascript
function unmountComponent(component) { if (options.beforeUnmount) options.beforeUnmount(component); var base = component.base; component._disable = true; if (component.componentWillUnmount) component.componentWillUnmount(); component.base = null; // recursively tear down & recollect high-order component children: var inner = component._component; if (inner) { unmountComponent(inner); } else if (base) { if (base['__preactattr_'] && base['__preactattr_'].ref) base['__preactattr_'].ref(null); component.nextBase = base; removeNode(base); collectComponent(component); removeChildren(base); } if (component.__ref) component.__ref(null); }
[ "function", "unmountComponent", "(", "component", ")", "{", "if", "(", "options", ".", "beforeUnmount", ")", "options", ".", "beforeUnmount", "(", "component", ")", ";", "var", "base", "=", "component", ".", "base", ";", "component", ".", "_disable", "=", "true", ";", "if", "(", "component", ".", "componentWillUnmount", ")", "component", ".", "componentWillUnmount", "(", ")", ";", "component", ".", "base", "=", "null", ";", "// recursively tear down & recollect high-order component children:", "var", "inner", "=", "component", ".", "_component", ";", "if", "(", "inner", ")", "{", "unmountComponent", "(", "inner", ")", ";", "}", "else", "if", "(", "base", ")", "{", "if", "(", "base", "[", "'__preactattr_'", "]", "&&", "base", "[", "'__preactattr_'", "]", ".", "ref", ")", "base", "[", "'__preactattr_'", "]", ".", "ref", "(", "null", ")", ";", "component", ".", "nextBase", "=", "base", ";", "removeNode", "(", "base", ")", ";", "collectComponent", "(", "component", ")", ";", "removeChildren", "(", "base", ")", ";", "}", "if", "(", "component", ".", "__ref", ")", "component", ".", "__ref", "(", "null", ")", ";", "}" ]
Remove a component from the DOM and recycle it. @param {Component} component The Component instance to unmount @private
[ "Remove", "a", "component", "from", "the", "DOM", "and", "recycle", "it", "." ]
d1c7bee8c2259c61e25eb4d27606ff70e2f02fd4
https://github.com/ampproject/worker-dom/blob/d1c7bee8c2259c61e25eb4d27606ff70e2f02fd4/demo/preact-dbmon/dbmon.js#L892-L919
7,488
ampproject/worker-dom
demo/preact-dbmon/dbmon.js
setState
function setState(state, callback) { var s = this.state; if (!this.prevState) this.prevState = extend({}, s); extend(s, typeof state === 'function' ? state(s, this.props) : state); if (callback) (this._renderCallbacks = this._renderCallbacks || []).push(callback); enqueueRender(this); }
javascript
function setState(state, callback) { var s = this.state; if (!this.prevState) this.prevState = extend({}, s); extend(s, typeof state === 'function' ? state(s, this.props) : state); if (callback) (this._renderCallbacks = this._renderCallbacks || []).push(callback); enqueueRender(this); }
[ "function", "setState", "(", "state", ",", "callback", ")", "{", "var", "s", "=", "this", ".", "state", ";", "if", "(", "!", "this", ".", "prevState", ")", "this", ".", "prevState", "=", "extend", "(", "{", "}", ",", "s", ")", ";", "extend", "(", "s", ",", "typeof", "state", "===", "'function'", "?", "state", "(", "s", ",", "this", ".", "props", ")", ":", "state", ")", ";", "if", "(", "callback", ")", "(", "this", ".", "_renderCallbacks", "=", "this", ".", "_renderCallbacks", "||", "[", "]", ")", ".", "push", "(", "callback", ")", ";", "enqueueRender", "(", "this", ")", ";", "}" ]
Returns a `boolean` indicating if the component should re-render when receiving the given `props` and `state`. @param {object} nextProps @param {object} nextState @param {object} nextContext @return {Boolean} should the component re-render @name shouldComponentUpdate @function Update component state by copying properties from `state` to `this.state`. @param {object} state A hash of state properties to update with new values @param {function} callback A function to be called once component state is updated
[ "Returns", "a", "boolean", "indicating", "if", "the", "component", "should", "re", "-", "render", "when", "receiving", "the", "given", "props", "and", "state", "." ]
d1c7bee8c2259c61e25eb4d27606ff70e2f02fd4
https://github.com/ampproject/worker-dom/blob/d1c7bee8c2259c61e25eb4d27606ff70e2f02fd4/demo/preact-dbmon/dbmon.js#L965-L971
7,489
ampproject/worker-dom
demo/preact-todomvc/app.js
linkState
function linkState(component, key, eventPath) { var path = key.split('.'), cache = component.__lsc || (component.__lsc = {}); return ( cache[key + eventPath] || (cache[key + eventPath] = function(e) { var t = (e && e.target) || this, state = {}, obj = state, v = typeof eventPath === 'string' ? dlv(e, eventPath) : t.nodeName ? (t.type.match(/^che|rad/) ? t.checked : t.value) : e, i = 0; for (; i < path.length - 1; i++) { obj = obj[path[i]] || (obj[path[i]] = (!i && component.state[path[i]]) || {}); } obj[path[i]] = v; component.setState(state); }) ); }
javascript
function linkState(component, key, eventPath) { var path = key.split('.'), cache = component.__lsc || (component.__lsc = {}); return ( cache[key + eventPath] || (cache[key + eventPath] = function(e) { var t = (e && e.target) || this, state = {}, obj = state, v = typeof eventPath === 'string' ? dlv(e, eventPath) : t.nodeName ? (t.type.match(/^che|rad/) ? t.checked : t.value) : e, i = 0; for (; i < path.length - 1; i++) { obj = obj[path[i]] || (obj[path[i]] = (!i && component.state[path[i]]) || {}); } obj[path[i]] = v; component.setState(state); }) ); }
[ "function", "linkState", "(", "component", ",", "key", ",", "eventPath", ")", "{", "var", "path", "=", "key", ".", "split", "(", "'.'", ")", ",", "cache", "=", "component", ".", "__lsc", "||", "(", "component", ".", "__lsc", "=", "{", "}", ")", ";", "return", "(", "cache", "[", "key", "+", "eventPath", "]", "||", "(", "cache", "[", "key", "+", "eventPath", "]", "=", "function", "(", "e", ")", "{", "var", "t", "=", "(", "e", "&&", "e", ".", "target", ")", "||", "this", ",", "state", "=", "{", "}", ",", "obj", "=", "state", ",", "v", "=", "typeof", "eventPath", "===", "'string'", "?", "dlv", "(", "e", ",", "eventPath", ")", ":", "t", ".", "nodeName", "?", "(", "t", ".", "type", ".", "match", "(", "/", "^che|rad", "/", ")", "?", "t", ".", "checked", ":", "t", ".", "value", ")", ":", "e", ",", "i", "=", "0", ";", "for", "(", ";", "i", "<", "path", ".", "length", "-", "1", ";", "i", "++", ")", "{", "obj", "=", "obj", "[", "path", "[", "i", "]", "]", "||", "(", "obj", "[", "path", "[", "i", "]", "]", "=", "(", "!", "i", "&&", "component", ".", "state", "[", "path", "[", "i", "]", "]", ")", "||", "{", "}", ")", ";", "}", "obj", "[", "path", "[", "i", "]", "]", "=", "v", ";", "component", ".", "setState", "(", "state", ")", ";", "}", ")", ")", ";", "}" ]
Create an Event handler function that sets a given state property. @param {Component} component The component whose state should be updated @param {string} key A dot-notated key path to update in the component's state @param {string} eventPath A dot-notated key path to the value that should be retrieved from the Event or component @returns {function} linkedStateHandler
[ "Create", "an", "Event", "handler", "function", "that", "sets", "a", "given", "state", "property", "." ]
d1c7bee8c2259c61e25eb4d27606ff70e2f02fd4
https://github.com/ampproject/worker-dom/blob/d1c7bee8c2259c61e25eb4d27606ff70e2f02fd4/demo/preact-todomvc/app.js#L1052-L1072
7,490
xaksis/vue-good-table
dist/vue-good-table.cjs.js
pagesCount
function pagesCount() { var quotient = Math.floor(this.total / this.currentPerPage); var remainder = this.total % this.currentPerPage; return remainder === 0 ? quotient : quotient + 1; }
javascript
function pagesCount() { var quotient = Math.floor(this.total / this.currentPerPage); var remainder = this.total % this.currentPerPage; return remainder === 0 ? quotient : quotient + 1; }
[ "function", "pagesCount", "(", ")", "{", "var", "quotient", "=", "Math", ".", "floor", "(", "this", ".", "total", "/", "this", ".", "currentPerPage", ")", ";", "var", "remainder", "=", "this", ".", "total", "%", "this", ".", "currentPerPage", ";", "return", "remainder", "===", "0", "?", "quotient", ":", "quotient", "+", "1", ";", "}" ]
Number of pages
[ "Number", "of", "pages" ]
bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6
https://github.com/xaksis/vue-good-table/blob/bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6/dist/vue-good-table.cjs.js#L372-L376
7,491
xaksis/vue-good-table
dist/vue-good-table.cjs.js
paginatedInfo
function paginatedInfo() { var first = (this.currentPage - 1) * this.currentPerPage + 1; var last = Math.min(this.total, this.currentPage * this.currentPerPage); if (last === 0) { first = 0; } return "".concat(first, " - ").concat(last, " ").concat(this.ofText, " ").concat(this.total); }
javascript
function paginatedInfo() { var first = (this.currentPage - 1) * this.currentPerPage + 1; var last = Math.min(this.total, this.currentPage * this.currentPerPage); if (last === 0) { first = 0; } return "".concat(first, " - ").concat(last, " ").concat(this.ofText, " ").concat(this.total); }
[ "function", "paginatedInfo", "(", ")", "{", "var", "first", "=", "(", "this", ".", "currentPage", "-", "1", ")", "*", "this", ".", "currentPerPage", "+", "1", ";", "var", "last", "=", "Math", ".", "min", "(", "this", ".", "total", ",", "this", ".", "currentPage", "*", "this", ".", "currentPerPage", ")", ";", "if", "(", "last", "===", "0", ")", "{", "first", "=", "0", ";", "}", "return", "\"\"", ".", "concat", "(", "first", ",", "\" - \"", ")", ".", "concat", "(", "last", ",", "\" \"", ")", ".", "concat", "(", "this", ".", "ofText", ",", "\" \"", ")", ".", "concat", "(", "this", ".", "total", ")", ";", "}" ]
Current displayed items
[ "Current", "displayed", "items" ]
bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6
https://github.com/xaksis/vue-good-table/blob/bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6/dist/vue-good-table.cjs.js#L378-L387
7,492
xaksis/vue-good-table
dist/vue-good-table.cjs.js
changePage
function changePage(pageNumber) { var emit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; if (pageNumber > 0 && this.total > this.currentPerPage * (pageNumber - 1)) { this.prevPage = this.currentPage; this.currentPage = pageNumber; if (emit) this.pageChanged(); } }
javascript
function changePage(pageNumber) { var emit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; if (pageNumber > 0 && this.total > this.currentPerPage * (pageNumber - 1)) { this.prevPage = this.currentPage; this.currentPage = pageNumber; if (emit) this.pageChanged(); } }
[ "function", "changePage", "(", "pageNumber", ")", "{", "var", "emit", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "true", ";", "if", "(", "pageNumber", ">", "0", "&&", "this", ".", "total", ">", "this", ".", "currentPerPage", "*", "(", "pageNumber", "-", "1", ")", ")", "{", "this", ".", "prevPage", "=", "this", ".", "currentPage", ";", "this", ".", "currentPage", "=", "pageNumber", ";", "if", "(", "emit", ")", "this", ".", "pageChanged", "(", ")", ";", "}", "}" ]
Change current page
[ "Change", "current", "page" ]
bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6
https://github.com/xaksis/vue-good-table/blob/bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6/dist/vue-good-table.cjs.js#L399-L407
7,493
xaksis/vue-good-table
dist/vue-good-table.cjs.js
handlePerPage
function handlePerPage() { //* if there's a custom dropdown then we use that if (this.customRowsPerPageDropdown !== null && Array.isArray(this.customRowsPerPageDropdown) && this.customRowsPerPageDropdown.length !== 0) { this.rowsPerPageOptions = this.customRowsPerPageDropdown; } else { //* otherwise we use the default rows per page dropdown this.rowsPerPageOptions = cloneDeep(DEFAULT_ROWS_PER_PAGE_DROPDOWN); } if (this.perPage) { this.currentPerPage = this.perPage; // if perPage doesn't already exist, we add it var found = false; for (var i = 0; i < this.rowsPerPageOptions.length; i++) { if (this.rowsPerPageOptions[i] === this.perPage) { found = true; } } if (!found && this.perPage !== -1) { this.rowsPerPageOptions.unshift(this.perPage); } } else { // reset to default this.currentPerPage = 10; } }
javascript
function handlePerPage() { //* if there's a custom dropdown then we use that if (this.customRowsPerPageDropdown !== null && Array.isArray(this.customRowsPerPageDropdown) && this.customRowsPerPageDropdown.length !== 0) { this.rowsPerPageOptions = this.customRowsPerPageDropdown; } else { //* otherwise we use the default rows per page dropdown this.rowsPerPageOptions = cloneDeep(DEFAULT_ROWS_PER_PAGE_DROPDOWN); } if (this.perPage) { this.currentPerPage = this.perPage; // if perPage doesn't already exist, we add it var found = false; for (var i = 0; i < this.rowsPerPageOptions.length; i++) { if (this.rowsPerPageOptions[i] === this.perPage) { found = true; } } if (!found && this.perPage !== -1) { this.rowsPerPageOptions.unshift(this.perPage); } } else { // reset to default this.currentPerPage = 10; } }
[ "function", "handlePerPage", "(", ")", "{", "//* if there's a custom dropdown then we use that", "if", "(", "this", ".", "customRowsPerPageDropdown", "!==", "null", "&&", "Array", ".", "isArray", "(", "this", ".", "customRowsPerPageDropdown", ")", "&&", "this", ".", "customRowsPerPageDropdown", ".", "length", "!==", "0", ")", "{", "this", ".", "rowsPerPageOptions", "=", "this", ".", "customRowsPerPageDropdown", ";", "}", "else", "{", "//* otherwise we use the default rows per page dropdown", "this", ".", "rowsPerPageOptions", "=", "cloneDeep", "(", "DEFAULT_ROWS_PER_PAGE_DROPDOWN", ")", ";", "}", "if", "(", "this", ".", "perPage", ")", "{", "this", ".", "currentPerPage", "=", "this", ".", "perPage", ";", "// if perPage doesn't already exist, we add it", "var", "found", "=", "false", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "rowsPerPageOptions", ".", "length", ";", "i", "++", ")", "{", "if", "(", "this", ".", "rowsPerPageOptions", "[", "i", "]", "===", "this", ".", "perPage", ")", "{", "found", "=", "true", ";", "}", "}", "if", "(", "!", "found", "&&", "this", ".", "perPage", "!==", "-", "1", ")", "{", "this", ".", "rowsPerPageOptions", ".", "unshift", "(", "this", ".", "perPage", ")", ";", "}", "}", "else", "{", "// reset to default", "this", ".", "currentPerPage", "=", "10", ";", "}", "}" ]
Handle per page changing
[ "Handle", "per", "page", "changing" ]
bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6
https://github.com/xaksis/vue-good-table/blob/bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6/dist/vue-good-table.cjs.js#L440-L467
7,494
xaksis/vue-good-table
dist/vue-good-table.cjs.js
hasFilterRow
function hasFilterRow() { // if (this.mode === 'remote' || !this.globalSearchEnabled) { for (var i = 0; i < this.columns.length; i++) { var col = this.columns[i]; if (col.filterOptions && col.filterOptions.enabled) { return true; } } // } return false; }
javascript
function hasFilterRow() { // if (this.mode === 'remote' || !this.globalSearchEnabled) { for (var i = 0; i < this.columns.length; i++) { var col = this.columns[i]; if (col.filterOptions && col.filterOptions.enabled) { return true; } } // } return false; }
[ "function", "hasFilterRow", "(", ")", "{", "// if (this.mode === 'remote' || !this.globalSearchEnabled) {", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "columns", ".", "length", ";", "i", "++", ")", "{", "var", "col", "=", "this", ".", "columns", "[", "i", "]", ";", "if", "(", "col", ".", "filterOptions", "&&", "col", ".", "filterOptions", ".", "enabled", ")", "{", "return", "true", ";", "}", "}", "// }", "return", "false", ";", "}" ]
to create a filter row, we need to make sure that there is atleast 1 column that requires filtering
[ "to", "create", "a", "filter", "row", "we", "need", "to", "make", "sure", "that", "there", "is", "atleast", "1", "column", "that", "requires", "filtering" ]
bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6
https://github.com/xaksis/vue-good-table/blob/bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6/dist/vue-good-table.cjs.js#L609-L621
7,495
xaksis/vue-good-table
dist/vue-good-table.cjs.js
getPlaceholder
function getPlaceholder(column) { var placeholder = this.isFilterable(column) && column.filterOptions.placeholder || "Filter ".concat(column.label); return placeholder; }
javascript
function getPlaceholder(column) { var placeholder = this.isFilterable(column) && column.filterOptions.placeholder || "Filter ".concat(column.label); return placeholder; }
[ "function", "getPlaceholder", "(", "column", ")", "{", "var", "placeholder", "=", "this", ".", "isFilterable", "(", "column", ")", "&&", "column", ".", "filterOptions", ".", "placeholder", "||", "\"Filter \"", ".", "concat", "(", "column", ".", "label", ")", ";", "return", "placeholder", ";", "}" ]
get column's defined placeholder or default one
[ "get", "column", "s", "defined", "placeholder", "or", "default", "one" ]
bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6
https://github.com/xaksis/vue-good-table/blob/bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6/dist/vue-good-table.cjs.js#L645-L648
7,496
xaksis/vue-good-table
dist/vue-good-table.cjs.js
updateFilters
function updateFilters(column, value) { var _this = this; if (this.timer) clearTimeout(this.timer); this.timer = setTimeout(function () { _this.updateFiltersImmediately(column, value); }, 400); }
javascript
function updateFilters(column, value) { var _this = this; if (this.timer) clearTimeout(this.timer); this.timer = setTimeout(function () { _this.updateFiltersImmediately(column, value); }, 400); }
[ "function", "updateFilters", "(", "column", ",", "value", ")", "{", "var", "_this", "=", "this", ";", "if", "(", "this", ".", "timer", ")", "clearTimeout", "(", "this", ".", "timer", ")", ";", "this", ".", "timer", "=", "setTimeout", "(", "function", "(", ")", "{", "_this", ".", "updateFiltersImmediately", "(", "column", ",", "value", ")", ";", "}", ",", "400", ")", ";", "}" ]
since vue doesn't detect property addition and deletion, we need to create helper function to set property etc
[ "since", "vue", "doesn", "t", "detect", "property", "addition", "and", "deletion", "we", "need", "to", "create", "helper", "function", "to", "set", "property", "etc" ]
bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6
https://github.com/xaksis/vue-good-table/blob/bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6/dist/vue-good-table.cjs.js#L660-L667
7,497
xaksis/vue-good-table
dist/vue-good-table.cjs.js
onCheckboxClicked
function onCheckboxClicked(row, index$$1, event) { this.$set(row, 'vgtSelected', !row.vgtSelected); this.$emit('on-row-click', { row: row, pageIndex: index$$1, selected: !!row.vgtSelected, event: event }); }
javascript
function onCheckboxClicked(row, index$$1, event) { this.$set(row, 'vgtSelected', !row.vgtSelected); this.$emit('on-row-click', { row: row, pageIndex: index$$1, selected: !!row.vgtSelected, event: event }); }
[ "function", "onCheckboxClicked", "(", "row", ",", "index$$1", ",", "event", ")", "{", "this", ".", "$set", "(", "row", ",", "'vgtSelected'", ",", "!", "row", ".", "vgtSelected", ")", ";", "this", ".", "$emit", "(", "'on-row-click'", ",", "{", "row", ":", "row", ",", "pageIndex", ":", "index$$1", ",", "selected", ":", "!", "!", "row", ".", "vgtSelected", ",", "event", ":", "event", "}", ")", ";", "}" ]
checkbox click should always do the following
[ "checkbox", "click", "should", "always", "do", "the", "following" ]
bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6
https://github.com/xaksis/vue-good-table/blob/bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6/dist/vue-good-table.cjs.js#L1864-L1872
7,498
xaksis/vue-good-table
dist/vue-good-table.cjs.js
dig
function dig(obj, selector) { var result = obj; var splitter = selector.split('.'); for (var i = 0; i < splitter.length; i++) { if (typeof result === 'undefined' || result === null) { return undefined; } result = result[splitter[i]]; } return result; }
javascript
function dig(obj, selector) { var result = obj; var splitter = selector.split('.'); for (var i = 0; i < splitter.length; i++) { if (typeof result === 'undefined' || result === null) { return undefined; } result = result[splitter[i]]; } return result; }
[ "function", "dig", "(", "obj", ",", "selector", ")", "{", "var", "result", "=", "obj", ";", "var", "splitter", "=", "selector", ".", "split", "(", "'.'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "splitter", ".", "length", ";", "i", "++", ")", "{", "if", "(", "typeof", "result", "===", "'undefined'", "||", "result", "===", "null", ")", "{", "return", "undefined", ";", "}", "result", "=", "result", "[", "splitter", "[", "i", "]", "]", ";", "}", "return", "result", ";", "}" ]
utility function to get nested property
[ "utility", "function", "to", "get", "nested", "property" ]
bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6
https://github.com/xaksis/vue-good-table/blob/bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6/dist/vue-good-table.cjs.js#L1947-L1960
7,499
xaksis/vue-good-table
dist/vue-good-table.cjs.js
isSortableColumn
function isSortableColumn(index$$1) { var sortable = this.columns[index$$1].sortable; var isSortable = typeof sortable === 'boolean' ? sortable : this.sortable; return isSortable; }
javascript
function isSortableColumn(index$$1) { var sortable = this.columns[index$$1].sortable; var isSortable = typeof sortable === 'boolean' ? sortable : this.sortable; return isSortable; }
[ "function", "isSortableColumn", "(", "index$$1", ")", "{", "var", "sortable", "=", "this", ".", "columns", "[", "index$$1", "]", ".", "sortable", ";", "var", "isSortable", "=", "typeof", "sortable", "===", "'boolean'", "?", "sortable", ":", "this", ".", "sortable", ";", "return", "isSortable", ";", "}" ]
Check if a column is sortable.
[ "Check", "if", "a", "column", "is", "sortable", "." ]
bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6
https://github.com/xaksis/vue-good-table/blob/bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6/dist/vue-good-table.cjs.js#L2009-L2013