id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
13,900
kentcdodds/match-sorter
src/index.js
getClosenessRanking
function getClosenessRanking(testString, stringToRank) { let charNumber = 0 function findMatchingCharacter(matchChar, string, index) { for (let j = index; j < string.length; j++) { const stringChar = string[j] if (stringChar === matchChar) { return j + 1 } } return -1 } function getRanking(spread) { const matching = spread - stringToRank.length + 1 const ranking = rankings.MATCHES + 1 / matching return ranking } const firstIndex = findMatchingCharacter(stringToRank[0], testString, 0) if (firstIndex < 0) { return rankings.NO_MATCH } charNumber = firstIndex for (let i = 1; i < stringToRank.length; i++) { const matchChar = stringToRank[i] charNumber = findMatchingCharacter(matchChar, testString, charNumber) const found = charNumber > -1 if (!found) { return rankings.NO_MATCH } } const spread = charNumber - firstIndex return getRanking(spread) }
javascript
function getClosenessRanking(testString, stringToRank) { let charNumber = 0 function findMatchingCharacter(matchChar, string, index) { for (let j = index; j < string.length; j++) { const stringChar = string[j] if (stringChar === matchChar) { return j + 1 } } return -1 } function getRanking(spread) { const matching = spread - stringToRank.length + 1 const ranking = rankings.MATCHES + 1 / matching return ranking } const firstIndex = findMatchingCharacter(stringToRank[0], testString, 0) if (firstIndex < 0) { return rankings.NO_MATCH } charNumber = firstIndex for (let i = 1; i < stringToRank.length; i++) { const matchChar = stringToRank[i] charNumber = findMatchingCharacter(matchChar, testString, charNumber) const found = charNumber > -1 if (!found) { return rankings.NO_MATCH } } const spread = charNumber - firstIndex return getRanking(spread) }
[ "function", "getClosenessRanking", "(", "testString", ",", "stringToRank", ")", "{", "let", "charNumber", "=", "0", "function", "findMatchingCharacter", "(", "matchChar", ",", "string", ",", "index", ")", "{", "for", "(", "let", "j", "=", "index", ";", "j", "<", "string", ".", "length", ";", "j", "++", ")", "{", "const", "stringChar", "=", "string", "[", "j", "]", "if", "(", "stringChar", "===", "matchChar", ")", "{", "return", "j", "+", "1", "}", "}", "return", "-", "1", "}", "function", "getRanking", "(", "spread", ")", "{", "const", "matching", "=", "spread", "-", "stringToRank", ".", "length", "+", "1", "const", "ranking", "=", "rankings", ".", "MATCHES", "+", "1", "/", "matching", "return", "ranking", "}", "const", "firstIndex", "=", "findMatchingCharacter", "(", "stringToRank", "[", "0", "]", ",", "testString", ",", "0", ")", "if", "(", "firstIndex", "<", "0", ")", "{", "return", "rankings", ".", "NO_MATCH", "}", "charNumber", "=", "firstIndex", "for", "(", "let", "i", "=", "1", ";", "i", "<", "stringToRank", ".", "length", ";", "i", "++", ")", "{", "const", "matchChar", "=", "stringToRank", "[", "i", "]", "charNumber", "=", "findMatchingCharacter", "(", "matchChar", ",", "testString", ",", "charNumber", ")", "const", "found", "=", "charNumber", ">", "-", "1", "if", "(", "!", "found", ")", "{", "return", "rankings", ".", "NO_MATCH", "}", "}", "const", "spread", "=", "charNumber", "-", "firstIndex", "return", "getRanking", "(", "spread", ")", "}" ]
Returns a score based on how spread apart the characters from the stringToRank are within the testString. A number close to rankings.MATCHES represents a loose match. A number close to rankings.MATCHES + 1 represents a loose match. @param {String} testString - the string to test against @param {String} stringToRank - the string to rank @returns {Number} the number between rankings.MATCHES and rankings.MATCHES + 1 for how well stringToRank matches testString
[ "Returns", "a", "score", "based", "on", "how", "spread", "apart", "the", "characters", "from", "the", "stringToRank", "are", "within", "the", "testString", ".", "A", "number", "close", "to", "rankings", ".", "MATCHES", "represents", "a", "loose", "match", ".", "A", "number", "close", "to", "rankings", ".", "MATCHES", "+", "1", "represents", "a", "loose", "match", "." ]
fa454c568c6b5f117a85855806e4754daf5961a0
https://github.com/kentcdodds/match-sorter/blob/fa454c568c6b5f117a85855806e4754daf5961a0/src/index.js#L302-L334
13,901
kentcdodds/match-sorter
src/index.js
sortRankedItems
function sortRankedItems(a, b) { const aFirst = -1 const bFirst = 1 const {rank: aRank, index: aIndex, keyIndex: aKeyIndex} = a const {rank: bRank, index: bIndex, keyIndex: bKeyIndex} = b const same = aRank === bRank if (same) { if (aKeyIndex === bKeyIndex) { return aIndex < bIndex ? aFirst : bFirst } else { return aKeyIndex < bKeyIndex ? aFirst : bFirst } } else { return aRank > bRank ? aFirst : bFirst } }
javascript
function sortRankedItems(a, b) { const aFirst = -1 const bFirst = 1 const {rank: aRank, index: aIndex, keyIndex: aKeyIndex} = a const {rank: bRank, index: bIndex, keyIndex: bKeyIndex} = b const same = aRank === bRank if (same) { if (aKeyIndex === bKeyIndex) { return aIndex < bIndex ? aFirst : bFirst } else { return aKeyIndex < bKeyIndex ? aFirst : bFirst } } else { return aRank > bRank ? aFirst : bFirst } }
[ "function", "sortRankedItems", "(", "a", ",", "b", ")", "{", "const", "aFirst", "=", "-", "1", "const", "bFirst", "=", "1", "const", "{", "rank", ":", "aRank", ",", "index", ":", "aIndex", ",", "keyIndex", ":", "aKeyIndex", "}", "=", "a", "const", "{", "rank", ":", "bRank", ",", "index", ":", "bIndex", ",", "keyIndex", ":", "bKeyIndex", "}", "=", "b", "const", "same", "=", "aRank", "===", "bRank", "if", "(", "same", ")", "{", "if", "(", "aKeyIndex", "===", "bKeyIndex", ")", "{", "return", "aIndex", "<", "bIndex", "?", "aFirst", ":", "bFirst", "}", "else", "{", "return", "aKeyIndex", "<", "bKeyIndex", "?", "aFirst", ":", "bFirst", "}", "}", "else", "{", "return", "aRank", ">", "bRank", "?", "aFirst", ":", "bFirst", "}", "}" ]
Sorts items that have a rank, index, and keyIndex @param {Object} a - the first item to sort @param {Object} b - the second item to sort @return {Number} -1 if a should come first, 1 if b should come first Note: will never return 0
[ "Sorts", "items", "that", "have", "a", "rank", "index", "and", "keyIndex" ]
fa454c568c6b5f117a85855806e4754daf5961a0
https://github.com/kentcdodds/match-sorter/blob/fa454c568c6b5f117a85855806e4754daf5961a0/src/index.js#L343-L358
13,902
kentcdodds/match-sorter
src/index.js
getItemValues
function getItemValues(item, key) { if (typeof key === 'object') { key = key.key } let value if (typeof key === 'function') { value = key(item) // eslint-disable-next-line no-negated-condition } else if (key.indexOf('.') !== -1) { // handle nested keys value = key .split('.') .reduce( (itemObj, nestedKey) => (itemObj ? itemObj[nestedKey] : null), item, ) } else { value = item[key] } // concat because `value` can be a string or an array // eslint-disable-next-line return value != null ? [].concat(value) : null }
javascript
function getItemValues(item, key) { if (typeof key === 'object') { key = key.key } let value if (typeof key === 'function') { value = key(item) // eslint-disable-next-line no-negated-condition } else if (key.indexOf('.') !== -1) { // handle nested keys value = key .split('.') .reduce( (itemObj, nestedKey) => (itemObj ? itemObj[nestedKey] : null), item, ) } else { value = item[key] } // concat because `value` can be a string or an array // eslint-disable-next-line return value != null ? [].concat(value) : null }
[ "function", "getItemValues", "(", "item", ",", "key", ")", "{", "if", "(", "typeof", "key", "===", "'object'", ")", "{", "key", "=", "key", ".", "key", "}", "let", "value", "if", "(", "typeof", "key", "===", "'function'", ")", "{", "value", "=", "key", "(", "item", ")", "// eslint-disable-next-line no-negated-condition", "}", "else", "if", "(", "key", ".", "indexOf", "(", "'.'", ")", "!==", "-", "1", ")", "{", "// handle nested keys", "value", "=", "key", ".", "split", "(", "'.'", ")", ".", "reduce", "(", "(", "itemObj", ",", "nestedKey", ")", "=>", "(", "itemObj", "?", "itemObj", "[", "nestedKey", "]", ":", "null", ")", ",", "item", ",", ")", "}", "else", "{", "value", "=", "item", "[", "key", "]", "}", "// concat because `value` can be a string or an array", "// eslint-disable-next-line", "return", "value", "!=", "null", "?", "[", "]", ".", "concat", "(", "value", ")", ":", "null", "}" ]
Gets value for key in item at arbitrarily nested keypath @param {Object} item - the item @param {Object|Function} key - the potentially nested keypath or property callback @return {Array} - an array containing the value(s) at the nested keypath
[ "Gets", "value", "for", "key", "in", "item", "at", "arbitrarily", "nested", "keypath" ]
fa454c568c6b5f117a85855806e4754daf5961a0
https://github.com/kentcdodds/match-sorter/blob/fa454c568c6b5f117a85855806e4754daf5961a0/src/index.js#L380-L402
13,903
kentcdodds/match-sorter
src/index.js
getAllValuesToRank
function getAllValuesToRank(item, keys) { return keys.reduce((allVals, key) => { const values = getItemValues(item, key) if (values) { values.forEach(itemValue => { allVals.push({ itemValue, attributes: getKeyAttributes(key), }) }) } return allVals }, []) }
javascript
function getAllValuesToRank(item, keys) { return keys.reduce((allVals, key) => { const values = getItemValues(item, key) if (values) { values.forEach(itemValue => { allVals.push({ itemValue, attributes: getKeyAttributes(key), }) }) } return allVals }, []) }
[ "function", "getAllValuesToRank", "(", "item", ",", "keys", ")", "{", "return", "keys", ".", "reduce", "(", "(", "allVals", ",", "key", ")", "=>", "{", "const", "values", "=", "getItemValues", "(", "item", ",", "key", ")", "if", "(", "values", ")", "{", "values", ".", "forEach", "(", "itemValue", "=>", "{", "allVals", ".", "push", "(", "{", "itemValue", ",", "attributes", ":", "getKeyAttributes", "(", "key", ")", ",", "}", ")", "}", ")", "}", "return", "allVals", "}", ",", "[", "]", ")", "}" ]
Gets all the values for the given keys in the given item and returns an array of those values @param {Object} item - the item from which the values will be retrieved @param {Array} keys - the keys to use to retrieve the values @return {Array} objects with {itemValue, attributes}
[ "Gets", "all", "the", "values", "for", "the", "given", "keys", "in", "the", "given", "item", "and", "returns", "an", "array", "of", "those", "values" ]
fa454c568c6b5f117a85855806e4754daf5961a0
https://github.com/kentcdodds/match-sorter/blob/fa454c568c6b5f117a85855806e4754daf5961a0/src/index.js#L410-L423
13,904
kentcdodds/match-sorter
src/index.js
getKeyAttributes
function getKeyAttributes(key) { if (typeof key === 'string') { key = {key} } return { maxRanking: Infinity, minRanking: -Infinity, ...key, } }
javascript
function getKeyAttributes(key) { if (typeof key === 'string') { key = {key} } return { maxRanking: Infinity, minRanking: -Infinity, ...key, } }
[ "function", "getKeyAttributes", "(", "key", ")", "{", "if", "(", "typeof", "key", "===", "'string'", ")", "{", "key", "=", "{", "key", "}", "}", "return", "{", "maxRanking", ":", "Infinity", ",", "minRanking", ":", "-", "Infinity", ",", "...", "key", ",", "}", "}" ]
Gets all the attributes for the given key @param {Object|String} key - the key from which the attributes will be retrieved @return {Object} object containing the key's attributes
[ "Gets", "all", "the", "attributes", "for", "the", "given", "key" ]
fa454c568c6b5f117a85855806e4754daf5961a0
https://github.com/kentcdodds/match-sorter/blob/fa454c568c6b5f117a85855806e4754daf5961a0/src/index.js#L430-L439
13,905
mapbox/concaveman
index.js
sqSegBoxDist
function sqSegBoxDist(a, b, bbox) { if (inside(a, bbox) || inside(b, bbox)) return 0; var d1 = sqSegSegDist(a[0], a[1], b[0], b[1], bbox.minX, bbox.minY, bbox.maxX, bbox.minY); if (d1 === 0) return 0; var d2 = sqSegSegDist(a[0], a[1], b[0], b[1], bbox.minX, bbox.minY, bbox.minX, bbox.maxY); if (d2 === 0) return 0; var d3 = sqSegSegDist(a[0], a[1], b[0], b[1], bbox.maxX, bbox.minY, bbox.maxX, bbox.maxY); if (d3 === 0) return 0; var d4 = sqSegSegDist(a[0], a[1], b[0], b[1], bbox.minX, bbox.maxY, bbox.maxX, bbox.maxY); if (d4 === 0) return 0; return Math.min(d1, d2, d3, d4); }
javascript
function sqSegBoxDist(a, b, bbox) { if (inside(a, bbox) || inside(b, bbox)) return 0; var d1 = sqSegSegDist(a[0], a[1], b[0], b[1], bbox.minX, bbox.minY, bbox.maxX, bbox.minY); if (d1 === 0) return 0; var d2 = sqSegSegDist(a[0], a[1], b[0], b[1], bbox.minX, bbox.minY, bbox.minX, bbox.maxY); if (d2 === 0) return 0; var d3 = sqSegSegDist(a[0], a[1], b[0], b[1], bbox.maxX, bbox.minY, bbox.maxX, bbox.maxY); if (d3 === 0) return 0; var d4 = sqSegSegDist(a[0], a[1], b[0], b[1], bbox.minX, bbox.maxY, bbox.maxX, bbox.maxY); if (d4 === 0) return 0; return Math.min(d1, d2, d3, d4); }
[ "function", "sqSegBoxDist", "(", "a", ",", "b", ",", "bbox", ")", "{", "if", "(", "inside", "(", "a", ",", "bbox", ")", "||", "inside", "(", "b", ",", "bbox", ")", ")", "return", "0", ";", "var", "d1", "=", "sqSegSegDist", "(", "a", "[", "0", "]", ",", "a", "[", "1", "]", ",", "b", "[", "0", "]", ",", "b", "[", "1", "]", ",", "bbox", ".", "minX", ",", "bbox", ".", "minY", ",", "bbox", ".", "maxX", ",", "bbox", ".", "minY", ")", ";", "if", "(", "d1", "===", "0", ")", "return", "0", ";", "var", "d2", "=", "sqSegSegDist", "(", "a", "[", "0", "]", ",", "a", "[", "1", "]", ",", "b", "[", "0", "]", ",", "b", "[", "1", "]", ",", "bbox", ".", "minX", ",", "bbox", ".", "minY", ",", "bbox", ".", "minX", ",", "bbox", ".", "maxY", ")", ";", "if", "(", "d2", "===", "0", ")", "return", "0", ";", "var", "d3", "=", "sqSegSegDist", "(", "a", "[", "0", "]", ",", "a", "[", "1", "]", ",", "b", "[", "0", "]", ",", "b", "[", "1", "]", ",", "bbox", ".", "maxX", ",", "bbox", ".", "minY", ",", "bbox", ".", "maxX", ",", "bbox", ".", "maxY", ")", ";", "if", "(", "d3", "===", "0", ")", "return", "0", ";", "var", "d4", "=", "sqSegSegDist", "(", "a", "[", "0", "]", ",", "a", "[", "1", "]", ",", "b", "[", "0", "]", ",", "b", "[", "1", "]", ",", "bbox", ".", "minX", ",", "bbox", ".", "maxY", ",", "bbox", ".", "maxX", ",", "bbox", ".", "maxY", ")", ";", "if", "(", "d4", "===", "0", ")", "return", "0", ";", "return", "Math", ".", "min", "(", "d1", ",", "d2", ",", "d3", ",", "d4", ")", ";", "}" ]
square distance from a segment bounding box to the given one
[ "square", "distance", "from", "a", "segment", "bounding", "box", "to", "the", "given", "one" ]
30b83eca5801fe87a5b72f9a1e1818c38ff8fb50
https://github.com/mapbox/concaveman/blob/30b83eca5801fe87a5b72f9a1e1818c38ff8fb50/index.js#L127-L138
13,906
mapbox/concaveman
index.js
updateBBox
function updateBBox(node) { var p1 = node.p; var p2 = node.next.p; node.minX = Math.min(p1[0], p2[0]); node.minY = Math.min(p1[1], p2[1]); node.maxX = Math.max(p1[0], p2[0]); node.maxY = Math.max(p1[1], p2[1]); return node; }
javascript
function updateBBox(node) { var p1 = node.p; var p2 = node.next.p; node.minX = Math.min(p1[0], p2[0]); node.minY = Math.min(p1[1], p2[1]); node.maxX = Math.max(p1[0], p2[0]); node.maxY = Math.max(p1[1], p2[1]); return node; }
[ "function", "updateBBox", "(", "node", ")", "{", "var", "p1", "=", "node", ".", "p", ";", "var", "p2", "=", "node", ".", "next", ".", "p", ";", "node", ".", "minX", "=", "Math", ".", "min", "(", "p1", "[", "0", "]", ",", "p2", "[", "0", "]", ")", ";", "node", ".", "minY", "=", "Math", ".", "min", "(", "p1", "[", "1", "]", ",", "p2", "[", "1", "]", ")", ";", "node", ".", "maxX", "=", "Math", ".", "max", "(", "p1", "[", "0", "]", ",", "p2", "[", "0", "]", ")", ";", "node", ".", "maxY", "=", "Math", ".", "max", "(", "p1", "[", "1", "]", ",", "p2", "[", "1", "]", ")", ";", "return", "node", ";", "}" ]
update the bounding box of a node's edge
[ "update", "the", "bounding", "box", "of", "a", "node", "s", "edge" ]
30b83eca5801fe87a5b72f9a1e1818c38ff8fb50
https://github.com/mapbox/concaveman/blob/30b83eca5801fe87a5b72f9a1e1818c38ff8fb50/index.js#L169-L177
13,907
mapbox/concaveman
index.js
fastConvexHull
function fastConvexHull(points) { var left = points[0]; var top = points[0]; var right = points[0]; var bottom = points[0]; // find the leftmost, rightmost, topmost and bottommost points for (var i = 0; i < points.length; i++) { var p = points[i]; if (p[0] < left[0]) left = p; if (p[0] > right[0]) right = p; if (p[1] < top[1]) top = p; if (p[1] > bottom[1]) bottom = p; } // filter out points that are inside the resulting quadrilateral var cull = [left, top, right, bottom]; var filtered = cull.slice(); for (i = 0; i < points.length; i++) { if (!pointInPolygon(points[i], cull)) filtered.push(points[i]); } // get convex hull around the filtered points var indices = convexHull(filtered); // return the hull as array of points (rather than indices) var hull = []; for (i = 0; i < indices.length; i++) hull.push(filtered[indices[i]]); return hull; }
javascript
function fastConvexHull(points) { var left = points[0]; var top = points[0]; var right = points[0]; var bottom = points[0]; // find the leftmost, rightmost, topmost and bottommost points for (var i = 0; i < points.length; i++) { var p = points[i]; if (p[0] < left[0]) left = p; if (p[0] > right[0]) right = p; if (p[1] < top[1]) top = p; if (p[1] > bottom[1]) bottom = p; } // filter out points that are inside the resulting quadrilateral var cull = [left, top, right, bottom]; var filtered = cull.slice(); for (i = 0; i < points.length; i++) { if (!pointInPolygon(points[i], cull)) filtered.push(points[i]); } // get convex hull around the filtered points var indices = convexHull(filtered); // return the hull as array of points (rather than indices) var hull = []; for (i = 0; i < indices.length; i++) hull.push(filtered[indices[i]]); return hull; }
[ "function", "fastConvexHull", "(", "points", ")", "{", "var", "left", "=", "points", "[", "0", "]", ";", "var", "top", "=", "points", "[", "0", "]", ";", "var", "right", "=", "points", "[", "0", "]", ";", "var", "bottom", "=", "points", "[", "0", "]", ";", "// find the leftmost, rightmost, topmost and bottommost points", "for", "(", "var", "i", "=", "0", ";", "i", "<", "points", ".", "length", ";", "i", "++", ")", "{", "var", "p", "=", "points", "[", "i", "]", ";", "if", "(", "p", "[", "0", "]", "<", "left", "[", "0", "]", ")", "left", "=", "p", ";", "if", "(", "p", "[", "0", "]", ">", "right", "[", "0", "]", ")", "right", "=", "p", ";", "if", "(", "p", "[", "1", "]", "<", "top", "[", "1", "]", ")", "top", "=", "p", ";", "if", "(", "p", "[", "1", "]", ">", "bottom", "[", "1", "]", ")", "bottom", "=", "p", ";", "}", "// filter out points that are inside the resulting quadrilateral", "var", "cull", "=", "[", "left", ",", "top", ",", "right", ",", "bottom", "]", ";", "var", "filtered", "=", "cull", ".", "slice", "(", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "points", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "pointInPolygon", "(", "points", "[", "i", "]", ",", "cull", ")", ")", "filtered", ".", "push", "(", "points", "[", "i", "]", ")", ";", "}", "// get convex hull around the filtered points", "var", "indices", "=", "convexHull", "(", "filtered", ")", ";", "// return the hull as array of points (rather than indices)", "var", "hull", "=", "[", "]", ";", "for", "(", "i", "=", "0", ";", "i", "<", "indices", ".", "length", ";", "i", "++", ")", "hull", ".", "push", "(", "filtered", "[", "indices", "[", "i", "]", "]", ")", ";", "return", "hull", ";", "}" ]
speed up convex hull by filtering out points inside quadrilateral formed by 4 extreme points
[ "speed", "up", "convex", "hull", "by", "filtering", "out", "points", "inside", "quadrilateral", "formed", "by", "4", "extreme", "points" ]
30b83eca5801fe87a5b72f9a1e1818c38ff8fb50
https://github.com/mapbox/concaveman/blob/30b83eca5801fe87a5b72f9a1e1818c38ff8fb50/index.js#L180-L209
13,908
mapbox/concaveman
index.js
insertNode
function insertNode(p, prev) { var node = { p: p, prev: null, next: null, minX: 0, minY: 0, maxX: 0, maxY: 0 }; if (!prev) { node.prev = node; node.next = node; } else { node.next = prev.next; node.prev = prev; prev.next.prev = node; prev.next = node; } return node; }
javascript
function insertNode(p, prev) { var node = { p: p, prev: null, next: null, minX: 0, minY: 0, maxX: 0, maxY: 0 }; if (!prev) { node.prev = node; node.next = node; } else { node.next = prev.next; node.prev = prev; prev.next.prev = node; prev.next = node; } return node; }
[ "function", "insertNode", "(", "p", ",", "prev", ")", "{", "var", "node", "=", "{", "p", ":", "p", ",", "prev", ":", "null", ",", "next", ":", "null", ",", "minX", ":", "0", ",", "minY", ":", "0", ",", "maxX", ":", "0", ",", "maxY", ":", "0", "}", ";", "if", "(", "!", "prev", ")", "{", "node", ".", "prev", "=", "node", ";", "node", ".", "next", "=", "node", ";", "}", "else", "{", "node", ".", "next", "=", "prev", ".", "next", ";", "node", ".", "prev", "=", "prev", ";", "prev", ".", "next", ".", "prev", "=", "node", ";", "prev", ".", "next", "=", "node", ";", "}", "return", "node", ";", "}" ]
create a new node in a doubly linked list
[ "create", "a", "new", "node", "in", "a", "doubly", "linked", "list" ]
30b83eca5801fe87a5b72f9a1e1818c38ff8fb50
https://github.com/mapbox/concaveman/blob/30b83eca5801fe87a5b72f9a1e1818c38ff8fb50/index.js#L212-L234
13,909
mapbox/concaveman
index.js
getSqDist
function getSqDist(p1, p2) { var dx = p1[0] - p2[0], dy = p1[1] - p2[1]; return dx * dx + dy * dy; }
javascript
function getSqDist(p1, p2) { var dx = p1[0] - p2[0], dy = p1[1] - p2[1]; return dx * dx + dy * dy; }
[ "function", "getSqDist", "(", "p1", ",", "p2", ")", "{", "var", "dx", "=", "p1", "[", "0", "]", "-", "p2", "[", "0", "]", ",", "dy", "=", "p1", "[", "1", "]", "-", "p2", "[", "1", "]", ";", "return", "dx", "*", "dx", "+", "dy", "*", "dy", ";", "}" ]
square distance between 2 points
[ "square", "distance", "between", "2", "points" ]
30b83eca5801fe87a5b72f9a1e1818c38ff8fb50
https://github.com/mapbox/concaveman/blob/30b83eca5801fe87a5b72f9a1e1818c38ff8fb50/index.js#L237-L243
13,910
adrai/node-eventstore
lib/snapshot.js
Snapshot
function Snapshot (id, obj) { if (!id) { var errIdMsg = 'id not injected!'; debug(errIdMsg); throw new Error(errIdMsg); } if (!obj) { var errObjMsg = 'object not injected!'; debug(errObjMsg); throw new Error(errObjMsg); } if (!obj.aggregateId) { var errAggIdMsg = 'object.aggregateId not injected!'; debug(errAggIdMsg); throw new Error(errAggIdMsg); } if (!obj.data) { var errDataMsg = 'object.data not injected!'; debug(errDataMsg); throw new Error(errDataMsg); } this.id = id; this.streamId = obj.aggregateId; this.aggregateId = obj.aggregateId; this.aggregate = obj.aggregate || null; this.context = obj.context || null; this.commitStamp = null; this.revision = obj.revision; this.version = obj.version; this.data = obj.data; }
javascript
function Snapshot (id, obj) { if (!id) { var errIdMsg = 'id not injected!'; debug(errIdMsg); throw new Error(errIdMsg); } if (!obj) { var errObjMsg = 'object not injected!'; debug(errObjMsg); throw new Error(errObjMsg); } if (!obj.aggregateId) { var errAggIdMsg = 'object.aggregateId not injected!'; debug(errAggIdMsg); throw new Error(errAggIdMsg); } if (!obj.data) { var errDataMsg = 'object.data not injected!'; debug(errDataMsg); throw new Error(errDataMsg); } this.id = id; this.streamId = obj.aggregateId; this.aggregateId = obj.aggregateId; this.aggregate = obj.aggregate || null; this.context = obj.context || null; this.commitStamp = null; this.revision = obj.revision; this.version = obj.version; this.data = obj.data; }
[ "function", "Snapshot", "(", "id", ",", "obj", ")", "{", "if", "(", "!", "id", ")", "{", "var", "errIdMsg", "=", "'id not injected!'", ";", "debug", "(", "errIdMsg", ")", ";", "throw", "new", "Error", "(", "errIdMsg", ")", ";", "}", "if", "(", "!", "obj", ")", "{", "var", "errObjMsg", "=", "'object not injected!'", ";", "debug", "(", "errObjMsg", ")", ";", "throw", "new", "Error", "(", "errObjMsg", ")", ";", "}", "if", "(", "!", "obj", ".", "aggregateId", ")", "{", "var", "errAggIdMsg", "=", "'object.aggregateId not injected!'", ";", "debug", "(", "errAggIdMsg", ")", ";", "throw", "new", "Error", "(", "errAggIdMsg", ")", ";", "}", "if", "(", "!", "obj", ".", "data", ")", "{", "var", "errDataMsg", "=", "'object.data not injected!'", ";", "debug", "(", "errDataMsg", ")", ";", "throw", "new", "Error", "(", "errDataMsg", ")", ";", "}", "this", ".", "id", "=", "id", ";", "this", ".", "streamId", "=", "obj", ".", "aggregateId", ";", "this", ".", "aggregateId", "=", "obj", ".", "aggregateId", ";", "this", ".", "aggregate", "=", "obj", ".", "aggregate", "||", "null", ";", "this", ".", "context", "=", "obj", ".", "context", "||", "null", ";", "this", ".", "commitStamp", "=", "null", ";", "this", ".", "revision", "=", "obj", ".", "revision", ";", "this", ".", "version", "=", "obj", ".", "version", ";", "this", ".", "data", "=", "obj", ".", "data", ";", "}" ]
Snapshot constructor The snapshot object will be persisted to the store. @param {String} id the id of the snapshot @param {Object} obj the snapshot object infos @constructor
[ "Snapshot", "constructor", "The", "snapshot", "object", "will", "be", "persisted", "to", "the", "store", "." ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/snapshot.js#L10-L44
13,911
adrai/node-eventstore
lib/eventStream.js
EventStream
function EventStream (eventstore, query, events) { if (!eventstore) { var errESMsg = 'eventstore not injected!'; debug(errESMsg); throw new Error(errESMsg); } if (typeof eventstore.commit !== 'function') { var errESfnMsg = 'eventstore.commit not injected!'; debug(errESfnMsg); throw new Error(errESfnMsg); } if (!query) { var errQryMsg = 'query not injected!'; debug(errQryMsg); throw new Error(errQryMsg); } if (!query.aggregateId) { var errAggIdMsg = 'query.aggregateId not injected!'; debug(errAggIdMsg); throw new Error(errAggIdMsg); } if (events) { if (!_.isArray(events)) { var errEvtsArrMsg = 'events should be an array!'; debug(errEvtsArrMsg); throw new Error(errEvtsArrMsg); } for (var i = 0, len = events.length; i < len; i++) { var evt = events[i]; if (evt.streamRevision === undefined || evt.streamRevision === null) { var errEvtMsg = 'The events passed should all have a streamRevision!'; debug(errEvtMsg); throw new Error(errEvtMsg); } } } this.eventstore = eventstore; this.streamId = query.aggregateId; this.aggregateId = query.aggregateId; this.aggregate = query.aggregate; this.context = query.context; this.events = events || []; this.uncommittedEvents = []; this.lastRevision = -1; this.events = _.sortBy(this.events, 'streamRevision'); // to update lastRevision... this.currentRevision(); }
javascript
function EventStream (eventstore, query, events) { if (!eventstore) { var errESMsg = 'eventstore not injected!'; debug(errESMsg); throw new Error(errESMsg); } if (typeof eventstore.commit !== 'function') { var errESfnMsg = 'eventstore.commit not injected!'; debug(errESfnMsg); throw new Error(errESfnMsg); } if (!query) { var errQryMsg = 'query not injected!'; debug(errQryMsg); throw new Error(errQryMsg); } if (!query.aggregateId) { var errAggIdMsg = 'query.aggregateId not injected!'; debug(errAggIdMsg); throw new Error(errAggIdMsg); } if (events) { if (!_.isArray(events)) { var errEvtsArrMsg = 'events should be an array!'; debug(errEvtsArrMsg); throw new Error(errEvtsArrMsg); } for (var i = 0, len = events.length; i < len; i++) { var evt = events[i]; if (evt.streamRevision === undefined || evt.streamRevision === null) { var errEvtMsg = 'The events passed should all have a streamRevision!'; debug(errEvtMsg); throw new Error(errEvtMsg); } } } this.eventstore = eventstore; this.streamId = query.aggregateId; this.aggregateId = query.aggregateId; this.aggregate = query.aggregate; this.context = query.context; this.events = events || []; this.uncommittedEvents = []; this.lastRevision = -1; this.events = _.sortBy(this.events, 'streamRevision'); // to update lastRevision... this.currentRevision(); }
[ "function", "EventStream", "(", "eventstore", ",", "query", ",", "events", ")", "{", "if", "(", "!", "eventstore", ")", "{", "var", "errESMsg", "=", "'eventstore not injected!'", ";", "debug", "(", "errESMsg", ")", ";", "throw", "new", "Error", "(", "errESMsg", ")", ";", "}", "if", "(", "typeof", "eventstore", ".", "commit", "!==", "'function'", ")", "{", "var", "errESfnMsg", "=", "'eventstore.commit not injected!'", ";", "debug", "(", "errESfnMsg", ")", ";", "throw", "new", "Error", "(", "errESfnMsg", ")", ";", "}", "if", "(", "!", "query", ")", "{", "var", "errQryMsg", "=", "'query not injected!'", ";", "debug", "(", "errQryMsg", ")", ";", "throw", "new", "Error", "(", "errQryMsg", ")", ";", "}", "if", "(", "!", "query", ".", "aggregateId", ")", "{", "var", "errAggIdMsg", "=", "'query.aggregateId not injected!'", ";", "debug", "(", "errAggIdMsg", ")", ";", "throw", "new", "Error", "(", "errAggIdMsg", ")", ";", "}", "if", "(", "events", ")", "{", "if", "(", "!", "_", ".", "isArray", "(", "events", ")", ")", "{", "var", "errEvtsArrMsg", "=", "'events should be an array!'", ";", "debug", "(", "errEvtsArrMsg", ")", ";", "throw", "new", "Error", "(", "errEvtsArrMsg", ")", ";", "}", "for", "(", "var", "i", "=", "0", ",", "len", "=", "events", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "evt", "=", "events", "[", "i", "]", ";", "if", "(", "evt", ".", "streamRevision", "===", "undefined", "||", "evt", ".", "streamRevision", "===", "null", ")", "{", "var", "errEvtMsg", "=", "'The events passed should all have a streamRevision!'", ";", "debug", "(", "errEvtMsg", ")", ";", "throw", "new", "Error", "(", "errEvtMsg", ")", ";", "}", "}", "}", "this", ".", "eventstore", "=", "eventstore", ";", "this", ".", "streamId", "=", "query", ".", "aggregateId", ";", "this", ".", "aggregateId", "=", "query", ".", "aggregateId", ";", "this", ".", "aggregate", "=", "query", ".", "aggregate", ";", "this", ".", "context", "=", "query", ".", "context", ";", "this", ".", "events", "=", "events", "||", "[", "]", ";", "this", ".", "uncommittedEvents", "=", "[", "]", ";", "this", ".", "lastRevision", "=", "-", "1", ";", "this", ".", "events", "=", "_", ".", "sortBy", "(", "this", ".", "events", ",", "'streamRevision'", ")", ";", "// to update lastRevision...", "this", ".", "currentRevision", "(", ")", ";", "}" ]
EventStream constructor The eventstream is one of the main objects to interagate with the eventstore. @param {Object} eventstore the eventstore that should be injected @param {Object} query the query object @param {Array} events the events (from store) @constructor
[ "EventStream", "constructor", "The", "eventstream", "is", "one", "of", "the", "main", "objects", "to", "interagate", "with", "the", "eventstore", "." ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventStream.js#L13-L68
13,912
adrai/node-eventstore
lib/eventStream.js
function() { for (var i = 0, len = this.events.length; i < len; i++) { if (this.events[i].streamRevision > this.lastRevision) { this.lastRevision = this.events[i].streamRevision; } } return this.lastRevision; }
javascript
function() { for (var i = 0, len = this.events.length; i < len; i++) { if (this.events[i].streamRevision > this.lastRevision) { this.lastRevision = this.events[i].streamRevision; } } return this.lastRevision; }
[ "function", "(", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "this", ".", "events", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "this", ".", "events", "[", "i", "]", ".", "streamRevision", ">", "this", ".", "lastRevision", ")", "{", "this", ".", "lastRevision", "=", "this", ".", "events", "[", "i", "]", ".", "streamRevision", ";", "}", "}", "return", "this", ".", "lastRevision", ";", "}" ]
This helper function calculates and returns the current stream revision. @returns {Number} lastRevision
[ "This", "helper", "function", "calculates", "and", "returns", "the", "current", "stream", "revision", "." ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventStream.js#L76-L84
13,913
adrai/node-eventstore
lib/eventStream.js
function(events) { if (!_.isArray(events)) { var errEvtsArrMsg = 'events should be an array!'; debug(errEvtsArrMsg); throw new Error(errEvtsArrMsg); } var self = this; _.each(events, function(evt) { self.addEvent(evt); }); }
javascript
function(events) { if (!_.isArray(events)) { var errEvtsArrMsg = 'events should be an array!'; debug(errEvtsArrMsg); throw new Error(errEvtsArrMsg); } var self = this; _.each(events, function(evt) { self.addEvent(evt); }); }
[ "function", "(", "events", ")", "{", "if", "(", "!", "_", ".", "isArray", "(", "events", ")", ")", "{", "var", "errEvtsArrMsg", "=", "'events should be an array!'", ";", "debug", "(", "errEvtsArrMsg", ")", ";", "throw", "new", "Error", "(", "errEvtsArrMsg", ")", ";", "}", "var", "self", "=", "this", ";", "_", ".", "each", "(", "events", ",", "function", "(", "evt", ")", "{", "self", ".", "addEvent", "(", "evt", ")", ";", "}", ")", ";", "}" ]
adds an array of events to the uncommittedEvents array @param {Array} events
[ "adds", "an", "array", "of", "events", "to", "the", "uncommittedEvents", "array" ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventStream.js#L98-L108
13,914
adrai/node-eventstore
lib/eventDispatcher.js
trigger
function trigger (dispatcher) { var queue = dispatcher.undispatchedEventsQueue || [] var event; // if the last loop is still in progress leave this loop if (dispatcher.isRunning) return; dispatcher.isRunning = true; (function next (e) { // dipatch one event in queue and call the _next_ callback, which // will call _process_ for the next undispatched event in queue. function process (event, nxt) { // Publish it now... debug('publish event...'); dispatcher.publisher(event.payload, function(err) { if (err) { return debug(err); } // ...and set the published event to dispatched. debug('set event to dispatched...'); dispatcher.store.setEventToDispatched(event, function(err) { if (err) { debug(err); } else { debug('event set to dispatched'); } }); }); nxt(); } // serial process all events in queue if (!e && queue.length) { process(queue.shift(), next) } else { debug(e); } })(); dispatcher.isRunning = false; }
javascript
function trigger (dispatcher) { var queue = dispatcher.undispatchedEventsQueue || [] var event; // if the last loop is still in progress leave this loop if (dispatcher.isRunning) return; dispatcher.isRunning = true; (function next (e) { // dipatch one event in queue and call the _next_ callback, which // will call _process_ for the next undispatched event in queue. function process (event, nxt) { // Publish it now... debug('publish event...'); dispatcher.publisher(event.payload, function(err) { if (err) { return debug(err); } // ...and set the published event to dispatched. debug('set event to dispatched...'); dispatcher.store.setEventToDispatched(event, function(err) { if (err) { debug(err); } else { debug('event set to dispatched'); } }); }); nxt(); } // serial process all events in queue if (!e && queue.length) { process(queue.shift(), next) } else { debug(e); } })(); dispatcher.isRunning = false; }
[ "function", "trigger", "(", "dispatcher", ")", "{", "var", "queue", "=", "dispatcher", ".", "undispatchedEventsQueue", "||", "[", "]", "var", "event", ";", "// if the last loop is still in progress leave this loop", "if", "(", "dispatcher", ".", "isRunning", ")", "return", ";", "dispatcher", ".", "isRunning", "=", "true", ";", "(", "function", "next", "(", "e", ")", "{", "// dipatch one event in queue and call the _next_ callback, which", "// will call _process_ for the next undispatched event in queue.", "function", "process", "(", "event", ",", "nxt", ")", "{", "// Publish it now...", "debug", "(", "'publish event...'", ")", ";", "dispatcher", ".", "publisher", "(", "event", ".", "payload", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "debug", "(", "err", ")", ";", "}", "// ...and set the published event to dispatched.", "debug", "(", "'set event to dispatched...'", ")", ";", "dispatcher", ".", "store", ".", "setEventToDispatched", "(", "event", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "}", "else", "{", "debug", "(", "'event set to dispatched'", ")", ";", "}", "}", ")", ";", "}", ")", ";", "nxt", "(", ")", ";", "}", "// serial process all events in queue", "if", "(", "!", "e", "&&", "queue", ".", "length", ")", "{", "process", "(", "queue", ".", "shift", "(", ")", ",", "next", ")", "}", "else", "{", "debug", "(", "e", ")", ";", "}", "}", ")", "(", ")", ";", "dispatcher", ".", "isRunning", "=", "false", ";", "}" ]
Triggers to publish all events in undispatchedEventsQueue.
[ "Triggers", "to", "publish", "all", "events", "in", "undispatchedEventsQueue", "." ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventDispatcher.js#L19-L63
13,915
adrai/node-eventstore
lib/eventDispatcher.js
process
function process (event, nxt) { // Publish it now... debug('publish event...'); dispatcher.publisher(event.payload, function(err) { if (err) { return debug(err); } // ...and set the published event to dispatched. debug('set event to dispatched...'); dispatcher.store.setEventToDispatched(event, function(err) { if (err) { debug(err); } else { debug('event set to dispatched'); } }); }); nxt(); }
javascript
function process (event, nxt) { // Publish it now... debug('publish event...'); dispatcher.publisher(event.payload, function(err) { if (err) { return debug(err); } // ...and set the published event to dispatched. debug('set event to dispatched...'); dispatcher.store.setEventToDispatched(event, function(err) { if (err) { debug(err); } else { debug('event set to dispatched'); } }); }); nxt(); }
[ "function", "process", "(", "event", ",", "nxt", ")", "{", "// Publish it now...", "debug", "(", "'publish event...'", ")", ";", "dispatcher", ".", "publisher", "(", "event", ".", "payload", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "debug", "(", "err", ")", ";", "}", "// ...and set the published event to dispatched.", "debug", "(", "'set event to dispatched...'", ")", ";", "dispatcher", ".", "store", ".", "setEventToDispatched", "(", "event", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "}", "else", "{", "debug", "(", "'event set to dispatched'", ")", ";", "}", "}", ")", ";", "}", ")", ";", "nxt", "(", ")", ";", "}" ]
dipatch one event in queue and call the _next_ callback, which will call _process_ for the next undispatched event in queue.
[ "dipatch", "one", "event", "in", "queue", "and", "call", "the", "_next_", "callback", "which", "will", "call", "_process_", "for", "the", "next", "undispatched", "event", "in", "queue", "." ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventDispatcher.js#L32-L52
13,916
adrai/node-eventstore
lib/eventDispatcher.js
function(events) { var self = this; events.forEach(function(event) { self.undispatchedEventsQueue.push(event); }); trigger(this); }
javascript
function(events) { var self = this; events.forEach(function(event) { self.undispatchedEventsQueue.push(event); }); trigger(this); }
[ "function", "(", "events", ")", "{", "var", "self", "=", "this", ";", "events", ".", "forEach", "(", "function", "(", "event", ")", "{", "self", ".", "undispatchedEventsQueue", ".", "push", "(", "event", ")", ";", "}", ")", ";", "trigger", "(", "this", ")", ";", "}" ]
Queues the passed in events for dispatching. @param events
[ "Queues", "the", "passed", "in", "events", "for", "dispatching", "." ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventDispatcher.js#L71-L77
13,917
adrai/node-eventstore
lib/eventDispatcher.js
function(callback) { if (typeof this.publisher !== 'function') { var pubErrMsg = 'publisher not injected!'; debug(pubErrMsg); if (callback) callback(new Error(pubErrMsg)); return; } if (!this.store || typeof this.store.getUndispatchedEvents !== 'function' || typeof this.store.setEventToDispatched !== 'function') { var storeErrMsg = 'store not injected!'; debug(storeErrMsg); if (callback) callback(new Error(storeErrMsg)) return; } var self = this; // Get all undispatched events from store and queue them // before all other events passed in by the addUndispatchedEvents function. this.store.getUndispatchedEvents(function(err, events) { if (err) { debug(err); if (callback) callback(err); return; } var triggered = false; if (events) { for (var i = 0, len = events.length; i < len; i++) { self.undispatchedEventsQueue.push(events[i]); // If there are a lot of events then we can hit issues with the call stack size when processing in one go triggered = false; if (i % 1000 === 0){ triggered = true; trigger(self); } } } if (!triggered) { trigger(self); } if (callback) callback(null); }); }
javascript
function(callback) { if (typeof this.publisher !== 'function') { var pubErrMsg = 'publisher not injected!'; debug(pubErrMsg); if (callback) callback(new Error(pubErrMsg)); return; } if (!this.store || typeof this.store.getUndispatchedEvents !== 'function' || typeof this.store.setEventToDispatched !== 'function') { var storeErrMsg = 'store not injected!'; debug(storeErrMsg); if (callback) callback(new Error(storeErrMsg)) return; } var self = this; // Get all undispatched events from store and queue them // before all other events passed in by the addUndispatchedEvents function. this.store.getUndispatchedEvents(function(err, events) { if (err) { debug(err); if (callback) callback(err); return; } var triggered = false; if (events) { for (var i = 0, len = events.length; i < len; i++) { self.undispatchedEventsQueue.push(events[i]); // If there are a lot of events then we can hit issues with the call stack size when processing in one go triggered = false; if (i % 1000 === 0){ triggered = true; trigger(self); } } } if (!triggered) { trigger(self); } if (callback) callback(null); }); }
[ "function", "(", "callback", ")", "{", "if", "(", "typeof", "this", ".", "publisher", "!==", "'function'", ")", "{", "var", "pubErrMsg", "=", "'publisher not injected!'", ";", "debug", "(", "pubErrMsg", ")", ";", "if", "(", "callback", ")", "callback", "(", "new", "Error", "(", "pubErrMsg", ")", ")", ";", "return", ";", "}", "if", "(", "!", "this", ".", "store", "||", "typeof", "this", ".", "store", ".", "getUndispatchedEvents", "!==", "'function'", "||", "typeof", "this", ".", "store", ".", "setEventToDispatched", "!==", "'function'", ")", "{", "var", "storeErrMsg", "=", "'store not injected!'", ";", "debug", "(", "storeErrMsg", ")", ";", "if", "(", "callback", ")", "callback", "(", "new", "Error", "(", "storeErrMsg", ")", ")", "return", ";", "}", "var", "self", "=", "this", ";", "// Get all undispatched events from store and queue them", "// before all other events passed in by the addUndispatchedEvents function.", "this", ".", "store", ".", "getUndispatchedEvents", "(", "function", "(", "err", ",", "events", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "if", "(", "callback", ")", "callback", "(", "err", ")", ";", "return", ";", "}", "var", "triggered", "=", "false", ";", "if", "(", "events", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "events", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "self", ".", "undispatchedEventsQueue", ".", "push", "(", "events", "[", "i", "]", ")", ";", "// If there are a lot of events then we can hit issues with the call stack size when processing in one go", "triggered", "=", "false", ";", "if", "(", "i", "%", "1000", "===", "0", ")", "{", "triggered", "=", "true", ";", "trigger", "(", "self", ")", ";", "}", "}", "}", "if", "(", "!", "triggered", ")", "{", "trigger", "(", "self", ")", ";", "}", "if", "(", "callback", ")", "callback", "(", "null", ")", ";", "}", ")", ";", "}" ]
Starts the instance to publish all undispatched events. @param callback the function that will be called when this action has finished
[ "Starts", "the", "instance", "to", "publish", "all", "undispatched", "events", "." ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventDispatcher.js#L83-L131
13,918
adrai/node-eventstore
lib/eventstore.js
function (fn) { if (fn.length === 1) { fn = _.wrap(fn, function(func, evt, callback) { func(evt); callback(null); }); } this.publisher = fn; return this; }
javascript
function (fn) { if (fn.length === 1) { fn = _.wrap(fn, function(func, evt, callback) { func(evt); callback(null); }); } this.publisher = fn; return this; }
[ "function", "(", "fn", ")", "{", "if", "(", "fn", ".", "length", "===", "1", ")", "{", "fn", "=", "_", ".", "wrap", "(", "fn", ",", "function", "(", "func", ",", "evt", ",", "callback", ")", "{", "func", "(", "evt", ")", ";", "callback", "(", "null", ")", ";", "}", ")", ";", "}", "this", ".", "publisher", "=", "fn", ";", "return", "this", ";", "}" ]
Inject function for event publishing. @param {Function} fn the function to be injected @returns {Eventstore} to be able to chain...
[ "Inject", "function", "for", "event", "publishing", "." ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventstore.js#L35-L46
13,919
adrai/node-eventstore
lib/eventstore.js
function (callback) { var self = this; function initDispatcher() { debug('init event dispatcher'); self.dispatcher = new EventDispatcher(self.publisher, self); self.dispatcher.start(callback); } this.store.on('connect', function () { self.emit('connect'); }); this.store.on('disconnect', function () { self.emit('disconnect'); }); process.nextTick(function() { tolerate(function(callback) { self.store.connect(callback); }, self.options.timeout || 0, function (err) { if (err) { debug(err); if (callback) callback(err); return; } if (!self.publisher) { debug('no publisher defined'); if (callback) callback(null); return; } initDispatcher(); }); }); }
javascript
function (callback) { var self = this; function initDispatcher() { debug('init event dispatcher'); self.dispatcher = new EventDispatcher(self.publisher, self); self.dispatcher.start(callback); } this.store.on('connect', function () { self.emit('connect'); }); this.store.on('disconnect', function () { self.emit('disconnect'); }); process.nextTick(function() { tolerate(function(callback) { self.store.connect(callback); }, self.options.timeout || 0, function (err) { if (err) { debug(err); if (callback) callback(err); return; } if (!self.publisher) { debug('no publisher defined'); if (callback) callback(null); return; } initDispatcher(); }); }); }
[ "function", "(", "callback", ")", "{", "var", "self", "=", "this", ";", "function", "initDispatcher", "(", ")", "{", "debug", "(", "'init event dispatcher'", ")", ";", "self", ".", "dispatcher", "=", "new", "EventDispatcher", "(", "self", ".", "publisher", ",", "self", ")", ";", "self", ".", "dispatcher", ".", "start", "(", "callback", ")", ";", "}", "this", ".", "store", ".", "on", "(", "'connect'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'connect'", ")", ";", "}", ")", ";", "this", ".", "store", ".", "on", "(", "'disconnect'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'disconnect'", ")", ";", "}", ")", ";", "process", ".", "nextTick", "(", "function", "(", ")", "{", "tolerate", "(", "function", "(", "callback", ")", "{", "self", ".", "store", ".", "connect", "(", "callback", ")", ";", "}", ",", "self", ".", "options", ".", "timeout", "||", "0", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "if", "(", "callback", ")", "callback", "(", "err", ")", ";", "return", ";", "}", "if", "(", "!", "self", ".", "publisher", ")", "{", "debug", "(", "'no publisher defined'", ")", ";", "if", "(", "callback", ")", "callback", "(", "null", ")", ";", "return", ";", "}", "initDispatcher", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Call this function to initialize the eventstore. If an event publisher function was injected it will additionally initialize an event dispatcher. @param {Function} callback the function that will be called when this action has finished [optional]
[ "Call", "this", "function", "to", "initialize", "the", "eventstore", ".", "If", "an", "event", "publisher", "function", "was", "injected", "it", "will", "additionally", "initialize", "an", "event", "dispatcher", "." ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventstore.js#L77-L111
13,920
adrai/node-eventstore
lib/eventstore.js
function (query, skip, limit) { if (!this.store.streamEvents) { throw new Error('Streaming API is not suppoted by '+(this.options.type || 'inmemory') +' db implementation.'); } if (typeof query === 'number') { limit = skip; skip = query; query = {}; }; if (typeof query === 'string') { query = { aggregateId: query }; } return this.store.streamEvents(query, skip, limit); }
javascript
function (query, skip, limit) { if (!this.store.streamEvents) { throw new Error('Streaming API is not suppoted by '+(this.options.type || 'inmemory') +' db implementation.'); } if (typeof query === 'number') { limit = skip; skip = query; query = {}; }; if (typeof query === 'string') { query = { aggregateId: query }; } return this.store.streamEvents(query, skip, limit); }
[ "function", "(", "query", ",", "skip", ",", "limit", ")", "{", "if", "(", "!", "this", ".", "store", ".", "streamEvents", ")", "{", "throw", "new", "Error", "(", "'Streaming API is not suppoted by '", "+", "(", "this", ".", "options", ".", "type", "||", "'inmemory'", ")", "+", "' db implementation.'", ")", ";", "}", "if", "(", "typeof", "query", "===", "'number'", ")", "{", "limit", "=", "skip", ";", "skip", "=", "query", ";", "query", "=", "{", "}", ";", "}", ";", "if", "(", "typeof", "query", "===", "'string'", ")", "{", "query", "=", "{", "aggregateId", ":", "query", "}", ";", "}", "return", "this", ".", "store", ".", "streamEvents", "(", "query", ",", "skip", ",", "limit", ")", ";", "}" ]
streaming api streams the events @param {Object || String} query the query object [optional] @param {Number} skip how many events should be skipped? [optional] @param {Number} limit how many events do you want in the result? [optional] @returns {Stream} a stream with the events
[ "streaming", "api", "streams", "the", "events" ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventstore.js#L123-L139
13,921
adrai/node-eventstore
lib/eventstore.js
function (commitStamp, skip, limit) { if (!this.store.streamEvents) { throw new Error('Streaming API is not suppoted by '+(this.options.type || 'inmemory') +' db implementation.'); } if (!commitStamp) { var err = new Error('Please pass in a date object!'); debug(err); throw err; } var self = this; commitStamp = new Date(commitStamp); return this.store.streamEventsSince(commitStamp, skip, limit); }
javascript
function (commitStamp, skip, limit) { if (!this.store.streamEvents) { throw new Error('Streaming API is not suppoted by '+(this.options.type || 'inmemory') +' db implementation.'); } if (!commitStamp) { var err = new Error('Please pass in a date object!'); debug(err); throw err; } var self = this; commitStamp = new Date(commitStamp); return this.store.streamEventsSince(commitStamp, skip, limit); }
[ "function", "(", "commitStamp", ",", "skip", ",", "limit", ")", "{", "if", "(", "!", "this", ".", "store", ".", "streamEvents", ")", "{", "throw", "new", "Error", "(", "'Streaming API is not suppoted by '", "+", "(", "this", ".", "options", ".", "type", "||", "'inmemory'", ")", "+", "' db implementation.'", ")", ";", "}", "if", "(", "!", "commitStamp", ")", "{", "var", "err", "=", "new", "Error", "(", "'Please pass in a date object!'", ")", ";", "debug", "(", "err", ")", ";", "throw", "err", ";", "}", "var", "self", "=", "this", ";", "commitStamp", "=", "new", "Date", "(", "commitStamp", ")", ";", "return", "this", ".", "store", ".", "streamEventsSince", "(", "commitStamp", ",", "skip", ",", "limit", ")", ";", "}" ]
streams all the events since passed commitStamp @param {Date} commitStamp the date object @param {Number} skip how many events should be skipped? [optional] @param {Number} limit how many events do you want in the result? [optional] @returns {Stream} a stream with the events
[ "streams", "all", "the", "events", "since", "passed", "commitStamp" ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventstore.js#L148-L163
13,922
adrai/node-eventstore
lib/eventstore.js
function (query, revMin, revMax) { if (typeof query === 'string') { query = { aggregateId: query }; } if (!query.aggregateId) { var err = new Error('An aggregateId should be passed!'); debug(err); if (callback) callback(err); return; } return this.store.streamEventsByRevision(query, revMin, revMax); }
javascript
function (query, revMin, revMax) { if (typeof query === 'string') { query = { aggregateId: query }; } if (!query.aggregateId) { var err = new Error('An aggregateId should be passed!'); debug(err); if (callback) callback(err); return; } return this.store.streamEventsByRevision(query, revMin, revMax); }
[ "function", "(", "query", ",", "revMin", ",", "revMax", ")", "{", "if", "(", "typeof", "query", "===", "'string'", ")", "{", "query", "=", "{", "aggregateId", ":", "query", "}", ";", "}", "if", "(", "!", "query", ".", "aggregateId", ")", "{", "var", "err", "=", "new", "Error", "(", "'An aggregateId should be passed!'", ")", ";", "debug", "(", "err", ")", ";", "if", "(", "callback", ")", "callback", "(", "err", ")", ";", "return", ";", "}", "return", "this", ".", "store", ".", "streamEventsByRevision", "(", "query", ",", "revMin", ",", "revMax", ")", ";", "}" ]
stream events by revision @param {Object || String} query the query object @param {Number} revMin revision start point [optional] @param {Number} revMax revision end point (hint: -1 = to end) [optional] @returns {Stream} a stream with the events
[ "stream", "events", "by", "revision" ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventstore.js#L173-L186
13,923
adrai/node-eventstore
lib/eventstore.js
function (commitStamp, skip, limit, callback) { if (!commitStamp) { var err = new Error('Please pass in a date object!'); debug(err); throw err; } if (typeof skip === 'function') { callback = skip; skip = 0; limit = -1; } else if (typeof limit === 'function') { callback = limit; limit = -1; } var self = this; function nextFn(callback) { if (limit < 0) { var resEvts = []; resEvts.next = nextFn; return process.nextTick(function () { callback(null, resEvts) }); } skip += limit; _getEventsSince(commitStamp, skip, limit, callback); } commitStamp = new Date(commitStamp); function _getEventsSince(commitStamp, skip, limit, callback) { self.store.getEventsSince(commitStamp, skip, limit, function (err, evts) { if (err) return callback(err); evts.next = nextFn; callback(null, evts); }); } _getEventsSince(commitStamp, skip, limit, callback); }
javascript
function (commitStamp, skip, limit, callback) { if (!commitStamp) { var err = new Error('Please pass in a date object!'); debug(err); throw err; } if (typeof skip === 'function') { callback = skip; skip = 0; limit = -1; } else if (typeof limit === 'function') { callback = limit; limit = -1; } var self = this; function nextFn(callback) { if (limit < 0) { var resEvts = []; resEvts.next = nextFn; return process.nextTick(function () { callback(null, resEvts) }); } skip += limit; _getEventsSince(commitStamp, skip, limit, callback); } commitStamp = new Date(commitStamp); function _getEventsSince(commitStamp, skip, limit, callback) { self.store.getEventsSince(commitStamp, skip, limit, function (err, evts) { if (err) return callback(err); evts.next = nextFn; callback(null, evts); }); } _getEventsSince(commitStamp, skip, limit, callback); }
[ "function", "(", "commitStamp", ",", "skip", ",", "limit", ",", "callback", ")", "{", "if", "(", "!", "commitStamp", ")", "{", "var", "err", "=", "new", "Error", "(", "'Please pass in a date object!'", ")", ";", "debug", "(", "err", ")", ";", "throw", "err", ";", "}", "if", "(", "typeof", "skip", "===", "'function'", ")", "{", "callback", "=", "skip", ";", "skip", "=", "0", ";", "limit", "=", "-", "1", ";", "}", "else", "if", "(", "typeof", "limit", "===", "'function'", ")", "{", "callback", "=", "limit", ";", "limit", "=", "-", "1", ";", "}", "var", "self", "=", "this", ";", "function", "nextFn", "(", "callback", ")", "{", "if", "(", "limit", "<", "0", ")", "{", "var", "resEvts", "=", "[", "]", ";", "resEvts", ".", "next", "=", "nextFn", ";", "return", "process", ".", "nextTick", "(", "function", "(", ")", "{", "callback", "(", "null", ",", "resEvts", ")", "}", ")", ";", "}", "skip", "+=", "limit", ";", "_getEventsSince", "(", "commitStamp", ",", "skip", ",", "limit", ",", "callback", ")", ";", "}", "commitStamp", "=", "new", "Date", "(", "commitStamp", ")", ";", "function", "_getEventsSince", "(", "commitStamp", ",", "skip", ",", "limit", ",", "callback", ")", "{", "self", ".", "store", ".", "getEventsSince", "(", "commitStamp", ",", "skip", ",", "limit", ",", "function", "(", "err", ",", "evts", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "evts", ".", "next", "=", "nextFn", ";", "callback", "(", "null", ",", "evts", ")", ";", "}", ")", ";", "}", "_getEventsSince", "(", "commitStamp", ",", "skip", ",", "limit", ",", "callback", ")", ";", "}" ]
loads all the events since passed commitStamp @param {Date} commitStamp the date object @param {Number} skip how many events should be skipped? [optional] @param {Number} limit how many events do you want in the result? [optional] @param {Function} callback the function that will be called when this action has finished `function(err, events){}`
[ "loads", "all", "the", "events", "since", "passed", "commitStamp" ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventstore.js#L255-L294
13,924
adrai/node-eventstore
lib/eventstore.js
function (query, revMin, revMax, callback) { if (typeof revMin === 'function') { callback = revMin; revMin = 0; revMax = -1; } else if (typeof revMax === 'function') { callback = revMax; revMax = -1; } if (typeof query === 'string') { query = { aggregateId: query }; } if (!query.aggregateId) { var err = new Error('An aggregateId should be passed!'); debug(err); if (callback) callback(err); return; } var self = this; this.getEventsByRevision(query, revMin, revMax, function(err, evts) { if (err) { return callback(err); } callback(null, new EventStream(self, query, evts)); }); }
javascript
function (query, revMin, revMax, callback) { if (typeof revMin === 'function') { callback = revMin; revMin = 0; revMax = -1; } else if (typeof revMax === 'function') { callback = revMax; revMax = -1; } if (typeof query === 'string') { query = { aggregateId: query }; } if (!query.aggregateId) { var err = new Error('An aggregateId should be passed!'); debug(err); if (callback) callback(err); return; } var self = this; this.getEventsByRevision(query, revMin, revMax, function(err, evts) { if (err) { return callback(err); } callback(null, new EventStream(self, query, evts)); }); }
[ "function", "(", "query", ",", "revMin", ",", "revMax", ",", "callback", ")", "{", "if", "(", "typeof", "revMin", "===", "'function'", ")", "{", "callback", "=", "revMin", ";", "revMin", "=", "0", ";", "revMax", "=", "-", "1", ";", "}", "else", "if", "(", "typeof", "revMax", "===", "'function'", ")", "{", "callback", "=", "revMax", ";", "revMax", "=", "-", "1", ";", "}", "if", "(", "typeof", "query", "===", "'string'", ")", "{", "query", "=", "{", "aggregateId", ":", "query", "}", ";", "}", "if", "(", "!", "query", ".", "aggregateId", ")", "{", "var", "err", "=", "new", "Error", "(", "'An aggregateId should be passed!'", ")", ";", "debug", "(", "err", ")", ";", "if", "(", "callback", ")", "callback", "(", "err", ")", ";", "return", ";", "}", "var", "self", "=", "this", ";", "this", ".", "getEventsByRevision", "(", "query", ",", "revMin", ",", "revMax", ",", "function", "(", "err", ",", "evts", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "callback", "(", "null", ",", "new", "EventStream", "(", "self", ",", "query", ",", "evts", ")", ")", ";", "}", ")", ";", "}" ]
loads the event stream @param {Object || String} query the query object @param {Number} revMin revision start point [optional] @param {Number} revMax revision end point (hint: -1 = to end) [optional] @param {Function} callback the function that will be called when this action has finished `function(err, eventstream){}`
[ "loads", "the", "event", "stream" ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventstore.js#L336-L365
13,925
adrai/node-eventstore
lib/eventstore.js
function (query, revMax, callback) { if (typeof revMax === 'function') { callback = revMax; revMax = -1; } if (typeof query === 'string') { query = { aggregateId: query }; } if (!query.aggregateId) { var err = new Error('An aggregateId should be passed!'); debug(err); if (callback) callback(err); return; } var self = this; async.waterfall([ function getSnapshot(callback) { self.store.getSnapshot(query, revMax, callback); }, function getEventStream(snap, callback) { var rev = 0; if (snap && (snap.revision !== undefined && snap.revision !== null)) { rev = snap.revision + 1; } self.getEventStream(query, rev, revMax, function(err, stream) { if (err) { return callback(err); } if (rev > 0 && stream.lastRevision == -1) { stream.lastRevision = snap.revision; } callback(null, snap, stream); }); }], callback ); }
javascript
function (query, revMax, callback) { if (typeof revMax === 'function') { callback = revMax; revMax = -1; } if (typeof query === 'string') { query = { aggregateId: query }; } if (!query.aggregateId) { var err = new Error('An aggregateId should be passed!'); debug(err); if (callback) callback(err); return; } var self = this; async.waterfall([ function getSnapshot(callback) { self.store.getSnapshot(query, revMax, callback); }, function getEventStream(snap, callback) { var rev = 0; if (snap && (snap.revision !== undefined && snap.revision !== null)) { rev = snap.revision + 1; } self.getEventStream(query, rev, revMax, function(err, stream) { if (err) { return callback(err); } if (rev > 0 && stream.lastRevision == -1) { stream.lastRevision = snap.revision; } callback(null, snap, stream); }); }], callback ); }
[ "function", "(", "query", ",", "revMax", ",", "callback", ")", "{", "if", "(", "typeof", "revMax", "===", "'function'", ")", "{", "callback", "=", "revMax", ";", "revMax", "=", "-", "1", ";", "}", "if", "(", "typeof", "query", "===", "'string'", ")", "{", "query", "=", "{", "aggregateId", ":", "query", "}", ";", "}", "if", "(", "!", "query", ".", "aggregateId", ")", "{", "var", "err", "=", "new", "Error", "(", "'An aggregateId should be passed!'", ")", ";", "debug", "(", "err", ")", ";", "if", "(", "callback", ")", "callback", "(", "err", ")", ";", "return", ";", "}", "var", "self", "=", "this", ";", "async", ".", "waterfall", "(", "[", "function", "getSnapshot", "(", "callback", ")", "{", "self", ".", "store", ".", "getSnapshot", "(", "query", ",", "revMax", ",", "callback", ")", ";", "}", ",", "function", "getEventStream", "(", "snap", ",", "callback", ")", "{", "var", "rev", "=", "0", ";", "if", "(", "snap", "&&", "(", "snap", ".", "revision", "!==", "undefined", "&&", "snap", ".", "revision", "!==", "null", ")", ")", "{", "rev", "=", "snap", ".", "revision", "+", "1", ";", "}", "self", ".", "getEventStream", "(", "query", ",", "rev", ",", "revMax", ",", "function", "(", "err", ",", "stream", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "if", "(", "rev", ">", "0", "&&", "stream", ".", "lastRevision", "==", "-", "1", ")", "{", "stream", ".", "lastRevision", "=", "snap", ".", "revision", ";", "}", "callback", "(", "null", ",", "snap", ",", "stream", ")", ";", "}", ")", ";", "}", "]", ",", "callback", ")", ";", "}" ]
loads the next snapshot back from given max revision @param {Object || String} query the query object @param {Number} revMax revision end point (hint: -1 = to end) [optional] @param {Function} callback the function that will be called when this action has finished `function(err, snapshot, eventstream){}`
[ "loads", "the", "next", "snapshot", "back", "from", "given", "max", "revision" ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventstore.js#L374-L421
13,926
adrai/node-eventstore
lib/eventstore.js
function(obj, callback) { if (obj.streamId && !obj.aggregateId) { obj.aggregateId = obj.streamId; } if (!obj.aggregateId) { var err = new Error('An aggregateId should be passed!'); debug(err); if (callback) callback(err); return; } obj.streamId = obj.aggregateId; var self = this; async.waterfall([ function getNewIdFromStorage(callback) { self.getNewId(callback); }, function commit(id, callback) { try { var snap = new Snapshot(id, obj); snap.commitStamp = new Date(); } catch (err) { return callback(err); } self.store.addSnapshot(snap, function(error) { if (self.options.maxSnapshotsCount) { self.store.cleanSnapshots(_.pick(obj, 'aggregateId', 'aggregate', 'context'), callback); } else { callback(error); } }); }], callback ); }
javascript
function(obj, callback) { if (obj.streamId && !obj.aggregateId) { obj.aggregateId = obj.streamId; } if (!obj.aggregateId) { var err = new Error('An aggregateId should be passed!'); debug(err); if (callback) callback(err); return; } obj.streamId = obj.aggregateId; var self = this; async.waterfall([ function getNewIdFromStorage(callback) { self.getNewId(callback); }, function commit(id, callback) { try { var snap = new Snapshot(id, obj); snap.commitStamp = new Date(); } catch (err) { return callback(err); } self.store.addSnapshot(snap, function(error) { if (self.options.maxSnapshotsCount) { self.store.cleanSnapshots(_.pick(obj, 'aggregateId', 'aggregate', 'context'), callback); } else { callback(error); } }); }], callback ); }
[ "function", "(", "obj", ",", "callback", ")", "{", "if", "(", "obj", ".", "streamId", "&&", "!", "obj", ".", "aggregateId", ")", "{", "obj", ".", "aggregateId", "=", "obj", ".", "streamId", ";", "}", "if", "(", "!", "obj", ".", "aggregateId", ")", "{", "var", "err", "=", "new", "Error", "(", "'An aggregateId should be passed!'", ")", ";", "debug", "(", "err", ")", ";", "if", "(", "callback", ")", "callback", "(", "err", ")", ";", "return", ";", "}", "obj", ".", "streamId", "=", "obj", ".", "aggregateId", ";", "var", "self", "=", "this", ";", "async", ".", "waterfall", "(", "[", "function", "getNewIdFromStorage", "(", "callback", ")", "{", "self", ".", "getNewId", "(", "callback", ")", ";", "}", ",", "function", "commit", "(", "id", ",", "callback", ")", "{", "try", "{", "var", "snap", "=", "new", "Snapshot", "(", "id", ",", "obj", ")", ";", "snap", ".", "commitStamp", "=", "new", "Date", "(", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "self", ".", "store", ".", "addSnapshot", "(", "snap", ",", "function", "(", "error", ")", "{", "if", "(", "self", ".", "options", ".", "maxSnapshotsCount", ")", "{", "self", ".", "store", ".", "cleanSnapshots", "(", "_", ".", "pick", "(", "obj", ",", "'aggregateId'", ",", "'aggregate'", ",", "'context'", ")", ",", "callback", ")", ";", "}", "else", "{", "callback", "(", "error", ")", ";", "}", "}", ")", ";", "}", "]", ",", "callback", ")", ";", "}" ]
stores a new snapshot @param {Object} obj the snapshot data @param {Function} callback the function that will be called when this action has finished [optional]
[ "stores", "a", "new", "snapshot" ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventstore.js#L428-L466
13,927
adrai/node-eventstore
lib/eventstore.js
function(eventstream, callback) { var self = this; async.waterfall([ function getNewCommitId(callback) { self.getNewId(callback); }, function commitEvents(id, callback) { // start committing. var event, currentRevision = eventstream.currentRevision(), uncommittedEvents = [].concat(eventstream.uncommittedEvents); eventstream.uncommittedEvents = []; self.store.getNextPositions(uncommittedEvents.length, function(err, positions) { if (err) return callback(err) for (var i = 0, len = uncommittedEvents.length; i < len; i++) { event = uncommittedEvents[i]; event.id = id + i.toString(); event.commitId = id; event.commitSequence = i; event.restInCommitStream = len - 1 - i; event.commitStamp = new Date(); currentRevision++; event.streamRevision = currentRevision; if (positions) event.position = positions[i]; event.applyMappings(); } self.store.addEvents(uncommittedEvents, function(err) { if (err) { // add uncommitted events back to eventstream eventstream.uncommittedEvents = uncommittedEvents.concat(eventstream.uncommittedEvents); return callback(err); } if (self.publisher && self.dispatcher) { // push to undispatchedQueue self.dispatcher.addUndispatchedEvents(uncommittedEvents); } else { eventstream.eventsToDispatch = [].concat(uncommittedEvents); } // move uncommitted events to events eventstream.events = eventstream.events.concat(uncommittedEvents); eventstream.currentRevision(); callback(null, eventstream); }); }); }], callback ); }
javascript
function(eventstream, callback) { var self = this; async.waterfall([ function getNewCommitId(callback) { self.getNewId(callback); }, function commitEvents(id, callback) { // start committing. var event, currentRevision = eventstream.currentRevision(), uncommittedEvents = [].concat(eventstream.uncommittedEvents); eventstream.uncommittedEvents = []; self.store.getNextPositions(uncommittedEvents.length, function(err, positions) { if (err) return callback(err) for (var i = 0, len = uncommittedEvents.length; i < len; i++) { event = uncommittedEvents[i]; event.id = id + i.toString(); event.commitId = id; event.commitSequence = i; event.restInCommitStream = len - 1 - i; event.commitStamp = new Date(); currentRevision++; event.streamRevision = currentRevision; if (positions) event.position = positions[i]; event.applyMappings(); } self.store.addEvents(uncommittedEvents, function(err) { if (err) { // add uncommitted events back to eventstream eventstream.uncommittedEvents = uncommittedEvents.concat(eventstream.uncommittedEvents); return callback(err); } if (self.publisher && self.dispatcher) { // push to undispatchedQueue self.dispatcher.addUndispatchedEvents(uncommittedEvents); } else { eventstream.eventsToDispatch = [].concat(uncommittedEvents); } // move uncommitted events to events eventstream.events = eventstream.events.concat(uncommittedEvents); eventstream.currentRevision(); callback(null, eventstream); }); }); }], callback ); }
[ "function", "(", "eventstream", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "async", ".", "waterfall", "(", "[", "function", "getNewCommitId", "(", "callback", ")", "{", "self", ".", "getNewId", "(", "callback", ")", ";", "}", ",", "function", "commitEvents", "(", "id", ",", "callback", ")", "{", "// start committing.", "var", "event", ",", "currentRevision", "=", "eventstream", ".", "currentRevision", "(", ")", ",", "uncommittedEvents", "=", "[", "]", ".", "concat", "(", "eventstream", ".", "uncommittedEvents", ")", ";", "eventstream", ".", "uncommittedEvents", "=", "[", "]", ";", "self", ".", "store", ".", "getNextPositions", "(", "uncommittedEvents", ".", "length", ",", "function", "(", "err", ",", "positions", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", "for", "(", "var", "i", "=", "0", ",", "len", "=", "uncommittedEvents", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "event", "=", "uncommittedEvents", "[", "i", "]", ";", "event", ".", "id", "=", "id", "+", "i", ".", "toString", "(", ")", ";", "event", ".", "commitId", "=", "id", ";", "event", ".", "commitSequence", "=", "i", ";", "event", ".", "restInCommitStream", "=", "len", "-", "1", "-", "i", ";", "event", ".", "commitStamp", "=", "new", "Date", "(", ")", ";", "currentRevision", "++", ";", "event", ".", "streamRevision", "=", "currentRevision", ";", "if", "(", "positions", ")", "event", ".", "position", "=", "positions", "[", "i", "]", ";", "event", ".", "applyMappings", "(", ")", ";", "}", "self", ".", "store", ".", "addEvents", "(", "uncommittedEvents", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "// add uncommitted events back to eventstream", "eventstream", ".", "uncommittedEvents", "=", "uncommittedEvents", ".", "concat", "(", "eventstream", ".", "uncommittedEvents", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "if", "(", "self", ".", "publisher", "&&", "self", ".", "dispatcher", ")", "{", "// push to undispatchedQueue", "self", ".", "dispatcher", ".", "addUndispatchedEvents", "(", "uncommittedEvents", ")", ";", "}", "else", "{", "eventstream", ".", "eventsToDispatch", "=", "[", "]", ".", "concat", "(", "uncommittedEvents", ")", ";", "}", "// move uncommitted events to events", "eventstream", ".", "events", "=", "eventstream", ".", "events", ".", "concat", "(", "uncommittedEvents", ")", ";", "eventstream", ".", "currentRevision", "(", ")", ";", "callback", "(", "null", ",", "eventstream", ")", ";", "}", ")", ";", "}", ")", ";", "}", "]", ",", "callback", ")", ";", "}" ]
commits all uncommittedEvents in the eventstream @param eventstream the eventstream that should be saved (hint: directly use the commit function on eventstream) @param {Function} callback the function that will be called when this action has finished `function(err, eventstream){}` (hint: eventstream.eventsToDispatch)
[ "commits", "all", "uncommittedEvents", "in", "the", "eventstream" ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventstore.js#L474-L535
13,928
adrai/node-eventstore
lib/eventstore.js
function (query, callback) { if (!callback) { callback = query; query = null; } if (typeof query === 'string') { query = { aggregateId: query }; } this.store.getUndispatchedEvents(query, callback); }
javascript
function (query, callback) { if (!callback) { callback = query; query = null; } if (typeof query === 'string') { query = { aggregateId: query }; } this.store.getUndispatchedEvents(query, callback); }
[ "function", "(", "query", ",", "callback", ")", "{", "if", "(", "!", "callback", ")", "{", "callback", "=", "query", ";", "query", "=", "null", ";", "}", "if", "(", "typeof", "query", "===", "'string'", ")", "{", "query", "=", "{", "aggregateId", ":", "query", "}", ";", "}", "this", ".", "store", ".", "getUndispatchedEvents", "(", "query", ",", "callback", ")", ";", "}" ]
loads all undispatched events @param {Object || String} query the query object [optional] @param {Function} callback the function that will be called when this action has finished `function(err, events){}`
[ "loads", "all", "undispatched", "events" ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventstore.js#L543-L554
13,929
adrai/node-eventstore
lib/eventstore.js
function (query, callback) { if (!callback) { callback = query; query = null; } if (typeof query === 'string') { query = { aggregateId: query }; } this.store.getLastEvent(query, callback); }
javascript
function (query, callback) { if (!callback) { callback = query; query = null; } if (typeof query === 'string') { query = { aggregateId: query }; } this.store.getLastEvent(query, callback); }
[ "function", "(", "query", ",", "callback", ")", "{", "if", "(", "!", "callback", ")", "{", "callback", "=", "query", ";", "query", "=", "null", ";", "}", "if", "(", "typeof", "query", "===", "'string'", ")", "{", "query", "=", "{", "aggregateId", ":", "query", "}", ";", "}", "this", ".", "store", ".", "getLastEvent", "(", "query", ",", "callback", ")", ";", "}" ]
loads the last event @param {Object || String} query the query object [optional] @param {Function} callback the function that will be called when this action has finished `function(err, event){}`
[ "loads", "the", "last", "event" ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventstore.js#L562-L573
13,930
adrai/node-eventstore
lib/eventstore.js
function (query, callback) { if (!callback) { callback = query; query = null; } if (typeof query === 'string') { query = { aggregateId: query }; } var self = this; this.store.getLastEvent(query, function (err, evt) { if (err) return callback(err); callback(null, new EventStream(self, query, evt ? [evt] : [])); }); }
javascript
function (query, callback) { if (!callback) { callback = query; query = null; } if (typeof query === 'string') { query = { aggregateId: query }; } var self = this; this.store.getLastEvent(query, function (err, evt) { if (err) return callback(err); callback(null, new EventStream(self, query, evt ? [evt] : [])); }); }
[ "function", "(", "query", ",", "callback", ")", "{", "if", "(", "!", "callback", ")", "{", "callback", "=", "query", ";", "query", "=", "null", ";", "}", "if", "(", "typeof", "query", "===", "'string'", ")", "{", "query", "=", "{", "aggregateId", ":", "query", "}", ";", "}", "var", "self", "=", "this", ";", "this", ".", "store", ".", "getLastEvent", "(", "query", ",", "function", "(", "err", ",", "evt", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "callback", "(", "null", ",", "new", "EventStream", "(", "self", ",", "query", ",", "evt", "?", "[", "evt", "]", ":", "[", "]", ")", ")", ";", "}", ")", ";", "}" ]
loads the last event in a stream @param {Object || String} query the query object [optional] @param {Function} callback the function that will be called when this action has finished `function(err, eventstream){}`
[ "loads", "the", "last", "event", "in", "a", "stream" ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventstore.js#L581-L598
13,931
adrai/node-eventstore
lib/eventstore.js
function (evtOrId, callback) { if (typeof evtOrId === 'object') { evtOrId = evtOrId.id; } this.store.setEventToDispatched(evtOrId, callback); }
javascript
function (evtOrId, callback) { if (typeof evtOrId === 'object') { evtOrId = evtOrId.id; } this.store.setEventToDispatched(evtOrId, callback); }
[ "function", "(", "evtOrId", ",", "callback", ")", "{", "if", "(", "typeof", "evtOrId", "===", "'object'", ")", "{", "evtOrId", "=", "evtOrId", ".", "id", ";", "}", "this", ".", "store", ".", "setEventToDispatched", "(", "evtOrId", ",", "callback", ")", ";", "}" ]
Sets the given event to dispatched. @param {Object || String} evtOrId the event object or its id @param {Function} callback the function that will be called when this action has finished [optional]
[ "Sets", "the", "given", "event", "to", "dispatched", "." ]
5ba58aa68d79b2ff81dd390b2464dab62f5c4c40
https://github.com/adrai/node-eventstore/blob/5ba58aa68d79b2ff81dd390b2464dab62f5c4c40/lib/eventstore.js#L605-L610
13,932
magicbookproject/magicbook
src/plugins/toc.js
getSections
function getSections($, root, relative) { var items = []; var sections = root.children("section[data-type], div[data-type='part']"); sections.each(function(index, el) { var jel = $(el); var header = jel.find("> header"); // create section item var item = { id: jel.attr("id"), type: jel.attr("data-type") }; // find title of section var title = header.length ? header.find("> h1, > h2, > h3, > h4, > h5") : jel.find("> h1, > h2, > h3, > h4, > h5"); if(title.length) { item.label = title.first().text(); } // find level of section var level; if(item.type in levels) { level = levels[item.type]; } else { return; } // find href of section item.relative = relative; if(level <= maxLevel) { item.children = getSections($, jel, relative); } items.push(item); }); return items; }
javascript
function getSections($, root, relative) { var items = []; var sections = root.children("section[data-type], div[data-type='part']"); sections.each(function(index, el) { var jel = $(el); var header = jel.find("> header"); // create section item var item = { id: jel.attr("id"), type: jel.attr("data-type") }; // find title of section var title = header.length ? header.find("> h1, > h2, > h3, > h4, > h5") : jel.find("> h1, > h2, > h3, > h4, > h5"); if(title.length) { item.label = title.first().text(); } // find level of section var level; if(item.type in levels) { level = levels[item.type]; } else { return; } // find href of section item.relative = relative; if(level <= maxLevel) { item.children = getSections($, jel, relative); } items.push(item); }); return items; }
[ "function", "getSections", "(", "$", ",", "root", ",", "relative", ")", "{", "var", "items", "=", "[", "]", ";", "var", "sections", "=", "root", ".", "children", "(", "\"section[data-type], div[data-type='part']\"", ")", ";", "sections", ".", "each", "(", "function", "(", "index", ",", "el", ")", "{", "var", "jel", "=", "$", "(", "el", ")", ";", "var", "header", "=", "jel", ".", "find", "(", "\"> header\"", ")", ";", "// create section item", "var", "item", "=", "{", "id", ":", "jel", ".", "attr", "(", "\"id\"", ")", ",", "type", ":", "jel", ".", "attr", "(", "\"data-type\"", ")", "}", ";", "// find title of section", "var", "title", "=", "header", ".", "length", "?", "header", ".", "find", "(", "\"> h1, > h2, > h3, > h4, > h5\"", ")", ":", "jel", ".", "find", "(", "\"> h1, > h2, > h3, > h4, > h5\"", ")", ";", "if", "(", "title", ".", "length", ")", "{", "item", ".", "label", "=", "title", ".", "first", "(", ")", ".", "text", "(", ")", ";", "}", "// find level of section", "var", "level", ";", "if", "(", "item", ".", "type", "in", "levels", ")", "{", "level", "=", "levels", "[", "item", ".", "type", "]", ";", "}", "else", "{", "return", ";", "}", "// find href of section", "item", ".", "relative", "=", "relative", ";", "if", "(", "level", "<=", "maxLevel", ")", "{", "item", ".", "children", "=", "getSections", "(", "$", ",", "jel", ",", "relative", ")", ";", "}", "items", ".", "push", "(", "item", ")", ";", "}", ")", ";", "return", "items", ";", "}" ]
takes an element and finds all direct section in its children. recursively calls itself on all section children to get a tree of sections.
[ "takes", "an", "element", "and", "finds", "all", "direct", "section", "in", "its", "children", ".", "recursively", "calls", "itself", "on", "all", "section", "children", "to", "get", "a", "tree", "of", "sections", "." ]
626486dd46f5d65b61e71321832540cbfc722725
https://github.com/magicbookproject/magicbook/blob/626486dd46f5d65b61e71321832540cbfc722725/src/plugins/toc.js#L45-L87
13,933
magicbookproject/magicbook
src/plugins/toc.js
function(config, stream, extras, callback) { var tocFiles = this.tocFiles = []; // First run through every file and get a tree of the section // navigation within that file. Save to our nav object. stream = stream.pipe(through.obj(function(file, enc, cb) { // create cheerio element for file if not present file.$el = file.$el || cheerio.load(file.contents.toString()); // make this work whether or not we have a // full HTML file. var root = file.$el.root(); var body = file.$el('body'); if(body.length) root = body; // add sections to plugin array for use later in the pipeline tocFiles.push({ file: file, sections: getSections(file.$el, root, file.relative) }); cb(null, file); })); callback(null, config, stream, extras); }
javascript
function(config, stream, extras, callback) { var tocFiles = this.tocFiles = []; // First run through every file and get a tree of the section // navigation within that file. Save to our nav object. stream = stream.pipe(through.obj(function(file, enc, cb) { // create cheerio element for file if not present file.$el = file.$el || cheerio.load(file.contents.toString()); // make this work whether or not we have a // full HTML file. var root = file.$el.root(); var body = file.$el('body'); if(body.length) root = body; // add sections to plugin array for use later in the pipeline tocFiles.push({ file: file, sections: getSections(file.$el, root, file.relative) }); cb(null, file); })); callback(null, config, stream, extras); }
[ "function", "(", "config", ",", "stream", ",", "extras", ",", "callback", ")", "{", "var", "tocFiles", "=", "this", ".", "tocFiles", "=", "[", "]", ";", "// First run through every file and get a tree of the section", "// navigation within that file. Save to our nav object.", "stream", "=", "stream", ".", "pipe", "(", "through", ".", "obj", "(", "function", "(", "file", ",", "enc", ",", "cb", ")", "{", "// create cheerio element for file if not present", "file", ".", "$el", "=", "file", ".", "$el", "||", "cheerio", ".", "load", "(", "file", ".", "contents", ".", "toString", "(", ")", ")", ";", "// make this work whether or not we have a", "// full HTML file.", "var", "root", "=", "file", ".", "$el", ".", "root", "(", ")", ";", "var", "body", "=", "file", ".", "$el", "(", "'body'", ")", ";", "if", "(", "body", ".", "length", ")", "root", "=", "body", ";", "// add sections to plugin array for use later in the pipeline", "tocFiles", ".", "push", "(", "{", "file", ":", "file", ",", "sections", ":", "getSections", "(", "file", ".", "$el", ",", "root", ",", "file", ".", "relative", ")", "}", ")", ";", "cb", "(", "null", ",", "file", ")", ";", "}", ")", ")", ";", "callback", "(", "null", ",", "config", ",", "stream", ",", "extras", ")", ";", "}" ]
When the files have been converted, we run the TOC generation. This is happening before the layouts, because it won't work if the markup is wrapped in container div's. We should rewrite the TOC generation to work with this.
[ "When", "the", "files", "have", "been", "converted", "we", "run", "the", "TOC", "generation", ".", "This", "is", "happening", "before", "the", "layouts", "because", "it", "won", "t", "work", "if", "the", "markup", "is", "wrapped", "in", "container", "div", "s", ".", "We", "should", "rewrite", "the", "TOC", "generation", "to", "work", "with", "this", "." ]
626486dd46f5d65b61e71321832540cbfc722725
https://github.com/magicbookproject/magicbook/blob/626486dd46f5d65b61e71321832540cbfc722725/src/plugins/toc.js#L106-L133
13,934
magicbookproject/magicbook
src/plugins/toc.js
relativeTOC
function relativeTOC(file, parent) { _.each(parent.children, function(child) { if(child.relative) { var href = ""; if(config.format != "pdf") { var relativeFolder = path.relative(path.dirname(file.relative), path.dirname(child.relative)); href = path.join(relativeFolder, path.basename(child.relative)) } if(child.id) { href += "#" + child.id; } child.href = href; } if(child.children) { child = relativeTOC(file, child); } }); return parent; }
javascript
function relativeTOC(file, parent) { _.each(parent.children, function(child) { if(child.relative) { var href = ""; if(config.format != "pdf") { var relativeFolder = path.relative(path.dirname(file.relative), path.dirname(child.relative)); href = path.join(relativeFolder, path.basename(child.relative)) } if(child.id) { href += "#" + child.id; } child.href = href; } if(child.children) { child = relativeTOC(file, child); } }); return parent; }
[ "function", "relativeTOC", "(", "file", ",", "parent", ")", "{", "_", ".", "each", "(", "parent", ".", "children", ",", "function", "(", "child", ")", "{", "if", "(", "child", ".", "relative", ")", "{", "var", "href", "=", "\"\"", ";", "if", "(", "config", ".", "format", "!=", "\"pdf\"", ")", "{", "var", "relativeFolder", "=", "path", ".", "relative", "(", "path", ".", "dirname", "(", "file", ".", "relative", ")", ",", "path", ".", "dirname", "(", "child", ".", "relative", ")", ")", ";", "href", "=", "path", ".", "join", "(", "relativeFolder", ",", "path", ".", "basename", "(", "child", ".", "relative", ")", ")", "}", "if", "(", "child", ".", "id", ")", "{", "href", "+=", "\"#\"", "+", "child", ".", "id", ";", "}", "child", ".", "href", "=", "href", ";", "}", "if", "(", "child", ".", "children", ")", "{", "child", "=", "relativeTOC", "(", "file", ",", "child", ")", ";", "}", "}", ")", ";", "return", "parent", ";", "}" ]
a function to turn a toc tree into relative URL's for a specific file.
[ "a", "function", "to", "turn", "a", "toc", "tree", "into", "relative", "URL", "s", "for", "a", "specific", "file", "." ]
626486dd46f5d65b61e71321832540cbfc722725
https://github.com/magicbookproject/magicbook/blob/626486dd46f5d65b61e71321832540cbfc722725/src/plugins/toc.js#L195-L213
13,935
magicbookproject/magicbook
src/index.js
loadConfig
function loadConfig(path) { try { var configJSON = JSON.parse(fs.readFileSync(process.cwd() + "/" + path)); console.log("Config file detected: " + path) return configJSON; } catch(e) { console.log("Config file: " + e.toString()) } }
javascript
function loadConfig(path) { try { var configJSON = JSON.parse(fs.readFileSync(process.cwd() + "/" + path)); console.log("Config file detected: " + path) return configJSON; } catch(e) { console.log("Config file: " + e.toString()) } }
[ "function", "loadConfig", "(", "path", ")", "{", "try", "{", "var", "configJSON", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "process", ".", "cwd", "(", ")", "+", "\"/\"", "+", "path", ")", ")", ";", "console", ".", "log", "(", "\"Config file detected: \"", "+", "path", ")", "return", "configJSON", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "\"Config file: \"", "+", "e", ".", "toString", "(", ")", ")", "}", "}" ]
Loads the config file into a JS object
[ "Loads", "the", "config", "file", "into", "a", "JS", "object" ]
626486dd46f5d65b61e71321832540cbfc722725
https://github.com/magicbookproject/magicbook/blob/626486dd46f5d65b61e71321832540cbfc722725/src/index.js#L14-L23
13,936
magicbookproject/magicbook
src/index.js
triggerBuild
function triggerBuild() { // Pick command lines options that take precedence var cmdConfig = _.pick(argv, ['files', 'verbose']);; // load config file and merge into config var jsonConfig = loadConfig(argv.config || 'magicbook.json'); _.defaults(cmdConfig, jsonConfig); // trigger the build with the new config buildFunction(cmdConfig); return cmdConfig; }
javascript
function triggerBuild() { // Pick command lines options that take precedence var cmdConfig = _.pick(argv, ['files', 'verbose']);; // load config file and merge into config var jsonConfig = loadConfig(argv.config || 'magicbook.json'); _.defaults(cmdConfig, jsonConfig); // trigger the build with the new config buildFunction(cmdConfig); return cmdConfig; }
[ "function", "triggerBuild", "(", ")", "{", "// Pick command lines options that take precedence", "var", "cmdConfig", "=", "_", ".", "pick", "(", "argv", ",", "[", "'files'", ",", "'verbose'", "]", ")", ";", ";", "// load config file and merge into config", "var", "jsonConfig", "=", "loadConfig", "(", "argv", ".", "config", "||", "'magicbook.json'", ")", ";", "_", ".", "defaults", "(", "cmdConfig", ",", "jsonConfig", ")", ";", "// trigger the build with the new config", "buildFunction", "(", "cmdConfig", ")", ";", "return", "cmdConfig", ";", "}" ]
Trigger a build
[ "Trigger", "a", "build" ]
626486dd46f5d65b61e71321832540cbfc722725
https://github.com/magicbookproject/magicbook/blob/626486dd46f5d65b61e71321832540cbfc722725/src/index.js#L26-L40
13,937
magicbookproject/magicbook
src/plugins/fonts.js
function(config, extras, callback) { // load all files in the source folder vfs.src(config.fonts.files) // vinyl-fs dest automatically determines whether a file // should be updated or not, based on the mtime timestamp. // so we don't need to do that manually. .pipe(vfs.dest(path.join(extras.destination, config.fonts.destination))) .on('finish', function() { callback(null, config, extras); }); }
javascript
function(config, extras, callback) { // load all files in the source folder vfs.src(config.fonts.files) // vinyl-fs dest automatically determines whether a file // should be updated or not, based on the mtime timestamp. // so we don't need to do that manually. .pipe(vfs.dest(path.join(extras.destination, config.fonts.destination))) .on('finish', function() { callback(null, config, extras); }); }
[ "function", "(", "config", ",", "extras", ",", "callback", ")", "{", "// load all files in the source folder", "vfs", ".", "src", "(", "config", ".", "fonts", ".", "files", ")", "// vinyl-fs dest automatically determines whether a file", "// should be updated or not, based on the mtime timestamp.", "// so we don't need to do that manually.", ".", "pipe", "(", "vfs", ".", "dest", "(", "path", ".", "join", "(", "extras", ".", "destination", ",", "config", ".", "fonts", ".", "destination", ")", ")", ")", ".", "on", "(", "'finish'", ",", "function", "(", ")", "{", "callback", "(", "null", ",", "config", ",", "extras", ")", ";", "}", ")", ";", "}" ]
simply move all font files at setup
[ "simply", "move", "all", "font", "files", "at", "setup" ]
626486dd46f5d65b61e71321832540cbfc722725
https://github.com/magicbookproject/magicbook/blob/626486dd46f5d65b61e71321832540cbfc722725/src/plugins/fonts.js#L15-L27
13,938
magicbookproject/magicbook
src/plugins/navigation.js
function(config, stream, extras, callback) { // Finish the stream so we get a full array of files, that // we can use to figure out whether add prev/next placeholders. streamHelpers.finishWithFiles(stream, function(files) { // loop through each file and get the title of the heading // as well as the relative file path. _.each(files, function(file, i) { var nav = {}; // if there was a file before this one, add placeholders if(files[i-1]) { file.prev = files[i-1]; nav.prev = { label: "MBINSERTPREVLABEL", href: "MBINSERTPREVHREF" } } // if there is a file after this one, add placeholders if(files[i+1]) { file.next = files[i+1]; nav.next = { label: "MBINSERTNEXTLABEL", href: "MBINSERTNEXTHREF" } } _.set(file, "pageLocals.navigation", nav); _.set(file, "layoutLocals.navigation", nav); }); // create new stream from the files stream = streamHelpers.streamFromArray(files); callback(null, config, stream, extras); }); }
javascript
function(config, stream, extras, callback) { // Finish the stream so we get a full array of files, that // we can use to figure out whether add prev/next placeholders. streamHelpers.finishWithFiles(stream, function(files) { // loop through each file and get the title of the heading // as well as the relative file path. _.each(files, function(file, i) { var nav = {}; // if there was a file before this one, add placeholders if(files[i-1]) { file.prev = files[i-1]; nav.prev = { label: "MBINSERTPREVLABEL", href: "MBINSERTPREVHREF" } } // if there is a file after this one, add placeholders if(files[i+1]) { file.next = files[i+1]; nav.next = { label: "MBINSERTNEXTLABEL", href: "MBINSERTNEXTHREF" } } _.set(file, "pageLocals.navigation", nav); _.set(file, "layoutLocals.navigation", nav); }); // create new stream from the files stream = streamHelpers.streamFromArray(files); callback(null, config, stream, extras); }); }
[ "function", "(", "config", ",", "stream", ",", "extras", ",", "callback", ")", "{", "// Finish the stream so we get a full array of files, that", "// we can use to figure out whether add prev/next placeholders.", "streamHelpers", ".", "finishWithFiles", "(", "stream", ",", "function", "(", "files", ")", "{", "// loop through each file and get the title of the heading", "// as well as the relative file path.", "_", ".", "each", "(", "files", ",", "function", "(", "file", ",", "i", ")", "{", "var", "nav", "=", "{", "}", ";", "// if there was a file before this one, add placeholders", "if", "(", "files", "[", "i", "-", "1", "]", ")", "{", "file", ".", "prev", "=", "files", "[", "i", "-", "1", "]", ";", "nav", ".", "prev", "=", "{", "label", ":", "\"MBINSERTPREVLABEL\"", ",", "href", ":", "\"MBINSERTPREVHREF\"", "}", "}", "// if there is a file after this one, add placeholders", "if", "(", "files", "[", "i", "+", "1", "]", ")", "{", "file", ".", "next", "=", "files", "[", "i", "+", "1", "]", ";", "nav", ".", "next", "=", "{", "label", ":", "\"MBINSERTNEXTLABEL\"", ",", "href", ":", "\"MBINSERTNEXTHREF\"", "}", "}", "_", ".", "set", "(", "file", ",", "\"pageLocals.navigation\"", ",", "nav", ")", ";", "_", ".", "set", "(", "file", ",", "\"layoutLocals.navigation\"", ",", "nav", ")", ";", "}", ")", ";", "// create new stream from the files", "stream", "=", "streamHelpers", ".", "streamFromArray", "(", "files", ")", ";", "callback", "(", "null", ",", "config", ",", "stream", ",", "extras", ")", ";", "}", ")", ";", "}" ]
On load we add placeholders, to be filled in later in the build process when we have the correct filenames.
[ "On", "load", "we", "add", "placeholders", "to", "be", "filled", "in", "later", "in", "the", "build", "process", "when", "we", "have", "the", "correct", "filenames", "." ]
626486dd46f5d65b61e71321832540cbfc722725
https://github.com/magicbookproject/magicbook/blob/626486dd46f5d65b61e71321832540cbfc722725/src/plugins/navigation.js#L16-L51
13,939
magicbookproject/magicbook
src/plugins/navigation.js
function(config, stream, extras, callback) { stream = stream.pipe(through.obj(function(file, enc, cb) { var contents = file.contents.toString(); var changed = false; if(file.prev) { changed = true; file.prev.$el = file.prev.$el || cheerio.load(file.prev.contents.toString()); var title = file.prev.$el('h1').first().text(); contents = contents.replace(/MBINSERTPREVLABEL/g, title); var href = path.relative(path.dirname(file.relative), file.prev.relative); contents = contents.replace(/MBINSERTPREVHREF/g, href); } if(file.next) { changed = true; file.next.$el = file.next.$el || cheerio.load(file.next.contents.toString()); var title = file.next.$el('h1').first().text(); contents = contents.replace(/MBINSERTNEXTLABEL/g, title); var href = path.relative(path.dirname(file.relative), file.next.relative); contents = contents.replace(/MBINSERTNEXTHREF/g, href); } if(changed) { file.contents = new Buffer(contents); file.$el = undefined; } cb(null, file); })); callback(null, config, stream, extras); }
javascript
function(config, stream, extras, callback) { stream = stream.pipe(through.obj(function(file, enc, cb) { var contents = file.contents.toString(); var changed = false; if(file.prev) { changed = true; file.prev.$el = file.prev.$el || cheerio.load(file.prev.contents.toString()); var title = file.prev.$el('h1').first().text(); contents = contents.replace(/MBINSERTPREVLABEL/g, title); var href = path.relative(path.dirname(file.relative), file.prev.relative); contents = contents.replace(/MBINSERTPREVHREF/g, href); } if(file.next) { changed = true; file.next.$el = file.next.$el || cheerio.load(file.next.contents.toString()); var title = file.next.$el('h1').first().text(); contents = contents.replace(/MBINSERTNEXTLABEL/g, title); var href = path.relative(path.dirname(file.relative), file.next.relative); contents = contents.replace(/MBINSERTNEXTHREF/g, href); } if(changed) { file.contents = new Buffer(contents); file.$el = undefined; } cb(null, file); })); callback(null, config, stream, extras); }
[ "function", "(", "config", ",", "stream", ",", "extras", ",", "callback", ")", "{", "stream", "=", "stream", ".", "pipe", "(", "through", ".", "obj", "(", "function", "(", "file", ",", "enc", ",", "cb", ")", "{", "var", "contents", "=", "file", ".", "contents", ".", "toString", "(", ")", ";", "var", "changed", "=", "false", ";", "if", "(", "file", ".", "prev", ")", "{", "changed", "=", "true", ";", "file", ".", "prev", ".", "$el", "=", "file", ".", "prev", ".", "$el", "||", "cheerio", ".", "load", "(", "file", ".", "prev", ".", "contents", ".", "toString", "(", ")", ")", ";", "var", "title", "=", "file", ".", "prev", ".", "$el", "(", "'h1'", ")", ".", "first", "(", ")", ".", "text", "(", ")", ";", "contents", "=", "contents", ".", "replace", "(", "/", "MBINSERTPREVLABEL", "/", "g", ",", "title", ")", ";", "var", "href", "=", "path", ".", "relative", "(", "path", ".", "dirname", "(", "file", ".", "relative", ")", ",", "file", ".", "prev", ".", "relative", ")", ";", "contents", "=", "contents", ".", "replace", "(", "/", "MBINSERTPREVHREF", "/", "g", ",", "href", ")", ";", "}", "if", "(", "file", ".", "next", ")", "{", "changed", "=", "true", ";", "file", ".", "next", ".", "$el", "=", "file", ".", "next", ".", "$el", "||", "cheerio", ".", "load", "(", "file", ".", "next", ".", "contents", ".", "toString", "(", ")", ")", ";", "var", "title", "=", "file", ".", "next", ".", "$el", "(", "'h1'", ")", ".", "first", "(", ")", ".", "text", "(", ")", ";", "contents", "=", "contents", ".", "replace", "(", "/", "MBINSERTNEXTLABEL", "/", "g", ",", "title", ")", ";", "var", "href", "=", "path", ".", "relative", "(", "path", ".", "dirname", "(", "file", ".", "relative", ")", ",", "file", ".", "next", ".", "relative", ")", ";", "contents", "=", "contents", ".", "replace", "(", "/", "MBINSERTNEXTHREF", "/", "g", ",", "href", ")", ";", "}", "if", "(", "changed", ")", "{", "file", ".", "contents", "=", "new", "Buffer", "(", "contents", ")", ";", "file", ".", "$el", "=", "undefined", ";", "}", "cb", "(", "null", ",", "file", ")", ";", "}", ")", ")", ";", "callback", "(", "null", ",", "config", ",", "stream", ",", "extras", ")", ";", "}" ]
Pipe through all the files and insert the title and link instead of the placeholders.
[ "Pipe", "through", "all", "the", "files", "and", "insert", "the", "title", "and", "link", "instead", "of", "the", "placeholders", "." ]
626486dd46f5d65b61e71321832540cbfc722725
https://github.com/magicbookproject/magicbook/blob/626486dd46f5d65b61e71321832540cbfc722725/src/plugins/navigation.js#L55-L88
13,940
magicbookproject/magicbook
src/plugins/images.js
mapImages
function mapImages(imageMap, srcFolder, destFolder) { return through.obj(function(file, enc, cb) { // find the relative path to image. If any pipe has changed the filename, // it's the original is set in orgRelative, so we look at that first. var relativeFrom = file.orgRelative || file.relative; var relativeTo = path.join(destFolder, file.relative); imageMap[relativeFrom] = relativeTo; cb(null, file); }); }
javascript
function mapImages(imageMap, srcFolder, destFolder) { return through.obj(function(file, enc, cb) { // find the relative path to image. If any pipe has changed the filename, // it's the original is set in orgRelative, so we look at that first. var relativeFrom = file.orgRelative || file.relative; var relativeTo = path.join(destFolder, file.relative); imageMap[relativeFrom] = relativeTo; cb(null, file); }); }
[ "function", "mapImages", "(", "imageMap", ",", "srcFolder", ",", "destFolder", ")", "{", "return", "through", ".", "obj", "(", "function", "(", "file", ",", "enc", ",", "cb", ")", "{", "// find the relative path to image. If any pipe has changed the filename,", "// it's the original is set in orgRelative, so we look at that first.", "var", "relativeFrom", "=", "file", ".", "orgRelative", "||", "file", ".", "relative", ";", "var", "relativeTo", "=", "path", ".", "join", "(", "destFolder", ",", "file", ".", "relative", ")", ";", "imageMap", "[", "relativeFrom", "]", "=", "relativeTo", ";", "cb", "(", "null", ",", "file", ")", ";", "}", ")", ";", "}" ]
through2 pipe function that creates a hasmap of old -> image names.
[ "through2", "pipe", "function", "that", "creates", "a", "hasmap", "of", "old", "-", ">", "image", "names", "." ]
626486dd46f5d65b61e71321832540cbfc722725
https://github.com/magicbookproject/magicbook/blob/626486dd46f5d65b61e71321832540cbfc722725/src/plugins/images.js#L20-L29
13,941
magicbookproject/magicbook
src/plugins/images.js
replaceSrc
function replaceSrc(imageMap) { return through.obj(function(file, enc, cb) { file.$el = file.$el || cheerio.load(file.contents.toString()); var changed = false; // loop over each image file.$el("img").each(function(i, el) { // convert el to cheerio el var jel = file.$el(this); var src = jel.attr("src"); // if this image exists in source folder, // replace src with new source if (imageMap[src]) { // this file has changed changed = true; // find the relative path from the image to the file var srcRelative = path.relative( path.dirname(file.relative), imageMap[src] ); jel.attr("src", srcRelative); } else if (!src.match(/^http/)) { console.log("image not found in source folder: " + src); } }); // only if we find an image, replace contents in file if (changed) { file.contents = new Buffer(file.$el("body").html()); } cb(null, file); }); }
javascript
function replaceSrc(imageMap) { return through.obj(function(file, enc, cb) { file.$el = file.$el || cheerio.load(file.contents.toString()); var changed = false; // loop over each image file.$el("img").each(function(i, el) { // convert el to cheerio el var jel = file.$el(this); var src = jel.attr("src"); // if this image exists in source folder, // replace src with new source if (imageMap[src]) { // this file has changed changed = true; // find the relative path from the image to the file var srcRelative = path.relative( path.dirname(file.relative), imageMap[src] ); jel.attr("src", srcRelative); } else if (!src.match(/^http/)) { console.log("image not found in source folder: " + src); } }); // only if we find an image, replace contents in file if (changed) { file.contents = new Buffer(file.$el("body").html()); } cb(null, file); }); }
[ "function", "replaceSrc", "(", "imageMap", ")", "{", "return", "through", ".", "obj", "(", "function", "(", "file", ",", "enc", ",", "cb", ")", "{", "file", ".", "$el", "=", "file", ".", "$el", "||", "cheerio", ".", "load", "(", "file", ".", "contents", ".", "toString", "(", ")", ")", ";", "var", "changed", "=", "false", ";", "// loop over each image", "file", ".", "$el", "(", "\"img\"", ")", ".", "each", "(", "function", "(", "i", ",", "el", ")", "{", "// convert el to cheerio el", "var", "jel", "=", "file", ".", "$el", "(", "this", ")", ";", "var", "src", "=", "jel", ".", "attr", "(", "\"src\"", ")", ";", "// if this image exists in source folder,", "// replace src with new source", "if", "(", "imageMap", "[", "src", "]", ")", "{", "// this file has changed", "changed", "=", "true", ";", "// find the relative path from the image to the file", "var", "srcRelative", "=", "path", ".", "relative", "(", "path", ".", "dirname", "(", "file", ".", "relative", ")", ",", "imageMap", "[", "src", "]", ")", ";", "jel", ".", "attr", "(", "\"src\"", ",", "srcRelative", ")", ";", "}", "else", "if", "(", "!", "src", ".", "match", "(", "/", "^http", "/", ")", ")", "{", "console", ".", "log", "(", "\"image not found in source folder: \"", "+", "src", ")", ";", "}", "}", ")", ";", "// only if we find an image, replace contents in file", "if", "(", "changed", ")", "{", "file", ".", "contents", "=", "new", "Buffer", "(", "file", ".", "$el", "(", "\"body\"", ")", ".", "html", "(", ")", ")", ";", "}", "cb", "(", "null", ",", "file", ")", ";", "}", ")", ";", "}" ]
through2 pipe function that replaces images src attributes based on values in hashmap.
[ "through2", "pipe", "function", "that", "replaces", "images", "src", "attributes", "based", "on", "values", "in", "hashmap", "." ]
626486dd46f5d65b61e71321832540cbfc722725
https://github.com/magicbookproject/magicbook/blob/626486dd46f5d65b61e71321832540cbfc722725/src/plugins/images.js#L33-L70
13,942
Kurento/kurento-client-js
lib/KurentoClient.js
serializeParams
function serializeParams(params) { for (var key in params) { var param = params[key]; if (param instanceof MediaObject || (param && (params.object !== undefined || params.hub !== undefined || params.sink !== undefined))) { if (param && param.id != null) { params[key] = param.id; } } }; return params; }
javascript
function serializeParams(params) { for (var key in params) { var param = params[key]; if (param instanceof MediaObject || (param && (params.object !== undefined || params.hub !== undefined || params.sink !== undefined))) { if (param && param.id != null) { params[key] = param.id; } } }; return params; }
[ "function", "serializeParams", "(", "params", ")", "{", "for", "(", "var", "key", "in", "params", ")", "{", "var", "param", "=", "params", "[", "key", "]", ";", "if", "(", "param", "instanceof", "MediaObject", "||", "(", "param", "&&", "(", "params", ".", "object", "!==", "undefined", "||", "params", ".", "hub", "!==", "undefined", "||", "params", ".", "sink", "!==", "undefined", ")", ")", ")", "{", "if", "(", "param", "&&", "param", ".", "id", "!=", "null", ")", "{", "params", "[", "key", "]", "=", "param", ".", "id", ";", "}", "}", "}", ";", "return", "params", ";", "}" ]
Serialize objects using their id @function module:kurentoClient.KurentoClient~serializeParams @param {external:Object} params @return {external:Object}
[ "Serialize", "objects", "using", "their", "id" ]
c17823b0c0a4381112fb2f084f407cbca627fc42
https://github.com/Kurento/kurento-client-js/blob/c17823b0c0a4381112fb2f084f407cbca627fc42/lib/KurentoClient.js#L82-L95
13,943
Kurento/kurento-client-js
lib/KurentoClient.js
encodeRpc
function encodeRpc(transaction, method, params, callback) { if (transaction) return transactionOperation.call(transaction, method, params, callback); var object = params.object; if (object && object.transactions && object.transactions.length) { var error = new TransactionNotCommitedException(); error.method = method; error.params = params; return setTimeout(callback, 0, error) }; for (var key in params.operationParams) { var object = params.operationParams[key]; if (object && object.transactions && object.transactions.length) { var error = new TransactionNotCommitedException(); error.method = method; error.params = params; return setTimeout(callback, 0, error) }; } if (transactionsManager.length) return transactionOperation.call(transactionsManager, method, params, callback); var promise = new Promise(function (resolve, reject) { function callback2(error, result) { if (error) return reject(error); resolve(result); }; prevRpc = deferred(params.object, params.operationParams, prevRpc, function (error) { if (error) throw error params = serializeParams(params); params.operationParams = serializeParams(params .operationParams); return encode(method, params, callback2); }) .catch(reject) }); prevRpc_result = promiseCallback(promise, callback); if (method == 'release') prevRpc = prevRpc_result; }
javascript
function encodeRpc(transaction, method, params, callback) { if (transaction) return transactionOperation.call(transaction, method, params, callback); var object = params.object; if (object && object.transactions && object.transactions.length) { var error = new TransactionNotCommitedException(); error.method = method; error.params = params; return setTimeout(callback, 0, error) }; for (var key in params.operationParams) { var object = params.operationParams[key]; if (object && object.transactions && object.transactions.length) { var error = new TransactionNotCommitedException(); error.method = method; error.params = params; return setTimeout(callback, 0, error) }; } if (transactionsManager.length) return transactionOperation.call(transactionsManager, method, params, callback); var promise = new Promise(function (resolve, reject) { function callback2(error, result) { if (error) return reject(error); resolve(result); }; prevRpc = deferred(params.object, params.operationParams, prevRpc, function (error) { if (error) throw error params = serializeParams(params); params.operationParams = serializeParams(params .operationParams); return encode(method, params, callback2); }) .catch(reject) }); prevRpc_result = promiseCallback(promise, callback); if (method == 'release') prevRpc = prevRpc_result; }
[ "function", "encodeRpc", "(", "transaction", ",", "method", ",", "params", ",", "callback", ")", "{", "if", "(", "transaction", ")", "return", "transactionOperation", ".", "call", "(", "transaction", ",", "method", ",", "params", ",", "callback", ")", ";", "var", "object", "=", "params", ".", "object", ";", "if", "(", "object", "&&", "object", ".", "transactions", "&&", "object", ".", "transactions", ".", "length", ")", "{", "var", "error", "=", "new", "TransactionNotCommitedException", "(", ")", ";", "error", ".", "method", "=", "method", ";", "error", ".", "params", "=", "params", ";", "return", "setTimeout", "(", "callback", ",", "0", ",", "error", ")", "}", ";", "for", "(", "var", "key", "in", "params", ".", "operationParams", ")", "{", "var", "object", "=", "params", ".", "operationParams", "[", "key", "]", ";", "if", "(", "object", "&&", "object", ".", "transactions", "&&", "object", ".", "transactions", ".", "length", ")", "{", "var", "error", "=", "new", "TransactionNotCommitedException", "(", ")", ";", "error", ".", "method", "=", "method", ";", "error", ".", "params", "=", "params", ";", "return", "setTimeout", "(", "callback", ",", "0", ",", "error", ")", "}", ";", "}", "if", "(", "transactionsManager", ".", "length", ")", "return", "transactionOperation", ".", "call", "(", "transactionsManager", ",", "method", ",", "params", ",", "callback", ")", ";", "var", "promise", "=", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "function", "callback2", "(", "error", ",", "result", ")", "{", "if", "(", "error", ")", "return", "reject", "(", "error", ")", ";", "resolve", "(", "result", ")", ";", "}", ";", "prevRpc", "=", "deferred", "(", "params", ".", "object", ",", "params", ".", "operationParams", ",", "prevRpc", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "throw", "error", "params", "=", "serializeParams", "(", "params", ")", ";", "params", ".", "operationParams", "=", "serializeParams", "(", "params", ".", "operationParams", ")", ";", "return", "encode", "(", "method", ",", "params", ",", "callback2", ")", ";", "}", ")", ".", "catch", "(", "reject", ")", "}", ")", ";", "prevRpc_result", "=", "promiseCallback", "(", "promise", ",", "callback", ")", ";", "if", "(", "method", "==", "'release'", ")", "prevRpc", "=", "prevRpc_result", ";", "}" ]
Request a generic functionality to be procesed by the server
[ "Request", "a", "generic", "functionality", "to", "be", "procesed", "by", "the", "server" ]
c17823b0c0a4381112fb2f084f407cbca627fc42
https://github.com/Kurento/kurento-client-js/blob/c17823b0c0a4381112fb2f084f407cbca627fc42/lib/KurentoClient.js#L544-L597
13,944
Kurento/kurento-client-js
lib/disguise.js
disguise
function disguise(target, source, unthenable) { if (source == null || target === source) return target for (var key in source) { if (target[key] !== undefined) continue if (unthenable && (key === 'then' || key === 'catch')) continue if (typeof source[key] === 'function') var descriptor = { value: source[key] } else var descriptor = { get: function () { return source[key] }, set: function (value) { source[key] = value } } descriptor.enumerable = true Object.defineProperty(target, key, descriptor) } return target }
javascript
function disguise(target, source, unthenable) { if (source == null || target === source) return target for (var key in source) { if (target[key] !== undefined) continue if (unthenable && (key === 'then' || key === 'catch')) continue if (typeof source[key] === 'function') var descriptor = { value: source[key] } else var descriptor = { get: function () { return source[key] }, set: function (value) { source[key] = value } } descriptor.enumerable = true Object.defineProperty(target, key, descriptor) } return target }
[ "function", "disguise", "(", "target", ",", "source", ",", "unthenable", ")", "{", "if", "(", "source", "==", "null", "||", "target", "===", "source", ")", "return", "target", "for", "(", "var", "key", "in", "source", ")", "{", "if", "(", "target", "[", "key", "]", "!==", "undefined", ")", "continue", "if", "(", "unthenable", "&&", "(", "key", "===", "'then'", "||", "key", "===", "'catch'", ")", ")", "continue", "if", "(", "typeof", "source", "[", "key", "]", "===", "'function'", ")", "var", "descriptor", "=", "{", "value", ":", "source", "[", "key", "]", "}", "else", "var", "descriptor", "=", "{", "get", ":", "function", "(", ")", "{", "return", "source", "[", "key", "]", "}", ",", "set", ":", "function", "(", "value", ")", "{", "source", "[", "key", "]", "=", "value", "}", "}", "descriptor", ".", "enumerable", "=", "true", "Object", ".", "defineProperty", "(", "target", ",", "key", ",", "descriptor", ")", "}", "return", "target", "}" ]
Public API Disguise an object giving it the appearance of another Add bind'ed functions and properties to a `target` object delegating the actions and attributes updates to the `source` one while retaining its original personality (i.e. duplicates and `instanceof` are preserved) @param {Object} target - the object to be disguised @param {Object} source - the object where to fetch its methods and attributes @param {Object} [unthenable] - the returned object should not be a thenable @return {Object} `target` disguised
[ "Public", "API", "Disguise", "an", "object", "giving", "it", "the", "appearance", "of", "another" ]
c17823b0c0a4381112fb2f084f407cbca627fc42
https://github.com/Kurento/kurento-client-js/blob/c17823b0c0a4381112fb2f084f407cbca627fc42/lib/disguise.js#L32-L58
13,945
Kurento/kurento-client-js
lib/disguise.js
disguiseThenable
function disguiseThenable(target, source) { if (target === source) return target if (target.then instanceof Function) { var target_then = target.then function then(onFulfilled, onRejected) { if (onFulfilled != null) onFulfilled = onFulfilled.bind(target) if (onRejected != null) onRejected = onRejected.bind(target) var promise = target_then.call(target, onFulfilled, onRejected) return disguiseThenable(promise, source) } Object.defineProperties(target, { then: { value: then }, catch: { value: promiseCatch } }) } return disguise(target, source) }
javascript
function disguiseThenable(target, source) { if (target === source) return target if (target.then instanceof Function) { var target_then = target.then function then(onFulfilled, onRejected) { if (onFulfilled != null) onFulfilled = onFulfilled.bind(target) if (onRejected != null) onRejected = onRejected.bind(target) var promise = target_then.call(target, onFulfilled, onRejected) return disguiseThenable(promise, source) } Object.defineProperties(target, { then: { value: then }, catch: { value: promiseCatch } }) } return disguise(target, source) }
[ "function", "disguiseThenable", "(", "target", ",", "source", ")", "{", "if", "(", "target", "===", "source", ")", "return", "target", "if", "(", "target", ".", "then", "instanceof", "Function", ")", "{", "var", "target_then", "=", "target", ".", "then", "function", "then", "(", "onFulfilled", ",", "onRejected", ")", "{", "if", "(", "onFulfilled", "!=", "null", ")", "onFulfilled", "=", "onFulfilled", ".", "bind", "(", "target", ")", "if", "(", "onRejected", "!=", "null", ")", "onRejected", "=", "onRejected", ".", "bind", "(", "target", ")", "var", "promise", "=", "target_then", ".", "call", "(", "target", ",", "onFulfilled", ",", "onRejected", ")", "return", "disguiseThenable", "(", "promise", ",", "source", ")", "}", "Object", ".", "defineProperties", "(", "target", ",", "{", "then", ":", "{", "value", ":", "then", "}", ",", "catch", ":", "{", "value", ":", "promiseCatch", "}", "}", ")", "}", "return", "disguise", "(", "target", ",", "source", ")", "}" ]
Disguise a thenable object If available, `target.then()` gets replaced by a method that exec the `onFulfilled` and `onRejected` callbacks using `source` as `this` object, and return the Promise returned by the original `target.then()` method already disguised. It also add a `target.catch()` method pointing to the newly added `target.then()`, being it previously available or not. @param {thenable} target - the object to be disguised @param {Object} source - the object where to fetch its methods and attributes @return {thenable} `target` disguised
[ "Disguise", "a", "thenable", "object" ]
c17823b0c0a4381112fb2f084f407cbca627fc42
https://github.com/Kurento/kurento-client-js/blob/c17823b0c0a4381112fb2f084f407cbca627fc42/lib/disguise.js#L74-L100
13,946
Kurento/kurento-client-js
lib/MediaObjectCreator.js
getConstructor
function getConstructor(type, strict) { var result = register.classes[type.qualifiedType] || register.abstracts[type .qualifiedType] || register.classes[type.type] || register.abstracts[type.type] || register.classes[type] || register.abstracts[type]; if (result) return result; if (type.hierarchy != undefined) { for (var i = 0; i <= type.hierarchy.length - 1; i++) { var result = register.classes[type.hierarchy[i]] || register.abstracts[ type.hierarchy[i]]; if (result) return result; }; } if (strict) { var error = new SyntaxError("Unknown type '" + type + "'") error.type = type throw error } console.warn("Unknown type '", type, "', using MediaObject instead"); return register.abstracts.MediaObject; }
javascript
function getConstructor(type, strict) { var result = register.classes[type.qualifiedType] || register.abstracts[type .qualifiedType] || register.classes[type.type] || register.abstracts[type.type] || register.classes[type] || register.abstracts[type]; if (result) return result; if (type.hierarchy != undefined) { for (var i = 0; i <= type.hierarchy.length - 1; i++) { var result = register.classes[type.hierarchy[i]] || register.abstracts[ type.hierarchy[i]]; if (result) return result; }; } if (strict) { var error = new SyntaxError("Unknown type '" + type + "'") error.type = type throw error } console.warn("Unknown type '", type, "', using MediaObject instead"); return register.abstracts.MediaObject; }
[ "function", "getConstructor", "(", "type", ",", "strict", ")", "{", "var", "result", "=", "register", ".", "classes", "[", "type", ".", "qualifiedType", "]", "||", "register", ".", "abstracts", "[", "type", ".", "qualifiedType", "]", "||", "register", ".", "classes", "[", "type", ".", "type", "]", "||", "register", ".", "abstracts", "[", "type", ".", "type", "]", "||", "register", ".", "classes", "[", "type", "]", "||", "register", ".", "abstracts", "[", "type", "]", ";", "if", "(", "result", ")", "return", "result", ";", "if", "(", "type", ".", "hierarchy", "!=", "undefined", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<=", "type", ".", "hierarchy", ".", "length", "-", "1", ";", "i", "++", ")", "{", "var", "result", "=", "register", ".", "classes", "[", "type", ".", "hierarchy", "[", "i", "]", "]", "||", "register", ".", "abstracts", "[", "type", ".", "hierarchy", "[", "i", "]", "]", ";", "if", "(", "result", ")", "return", "result", ";", "}", ";", "}", "if", "(", "strict", ")", "{", "var", "error", "=", "new", "SyntaxError", "(", "\"Unknown type '\"", "+", "type", "+", "\"'\"", ")", "error", ".", "type", "=", "type", "throw", "error", "}", "console", ".", "warn", "(", "\"Unknown type '\"", ",", "type", ",", "\"', using MediaObject instead\"", ")", ";", "return", "register", ".", "abstracts", ".", "MediaObject", ";", "}" ]
Get the constructor for a type If the type is not registered, use generic {module:core/abstracts.MediaObject} @function module:kurentoClient~MediaObjectCreator~getConstructor @param {external:string} type @param {external:Boolean} strict @return {module:core/abstracts.MediaObject}
[ "Get", "the", "constructor", "for", "a", "type" ]
c17823b0c0a4381112fb2f084f407cbca627fc42
https://github.com/Kurento/kurento-client-js/blob/c17823b0c0a4381112fb2f084f407cbca627fc42/lib/MediaObjectCreator.js#L40-L63
13,947
Kurento/kurento-client-js
lib/MediaObjectCreator.js
createMediaObject
function createMediaObject(item, callback) { var transaction = item.transaction; delete item.transaction; var constructor = createConstructor(item, strict); item = constructor.item; delete constructor.item; var params = item.params || {}; delete item.params; if (params.mediaPipeline == undefined && host instanceof register.classes .MediaPipeline) params.mediaPipeline = host; var params_ = extend({}, params) item.constructorParams = checkParams(params_, constructor.constructorParams, item.type); if (Object.keys(params_)) { item.properties = params_; } if (!Object.keys(item.constructorParams).length) delete item.constructorParams; try { var mediaObject = createObject(constructor) } catch (error) { return callback(error) }; Object.defineProperty(item, 'object', { value: mediaObject }); encodeCreate(transaction, item, callback); return mediaObject }
javascript
function createMediaObject(item, callback) { var transaction = item.transaction; delete item.transaction; var constructor = createConstructor(item, strict); item = constructor.item; delete constructor.item; var params = item.params || {}; delete item.params; if (params.mediaPipeline == undefined && host instanceof register.classes .MediaPipeline) params.mediaPipeline = host; var params_ = extend({}, params) item.constructorParams = checkParams(params_, constructor.constructorParams, item.type); if (Object.keys(params_)) { item.properties = params_; } if (!Object.keys(item.constructorParams).length) delete item.constructorParams; try { var mediaObject = createObject(constructor) } catch (error) { return callback(error) }; Object.defineProperty(item, 'object', { value: mediaObject }); encodeCreate(transaction, item, callback); return mediaObject }
[ "function", "createMediaObject", "(", "item", ",", "callback", ")", "{", "var", "transaction", "=", "item", ".", "transaction", ";", "delete", "item", ".", "transaction", ";", "var", "constructor", "=", "createConstructor", "(", "item", ",", "strict", ")", ";", "item", "=", "constructor", ".", "item", ";", "delete", "constructor", ".", "item", ";", "var", "params", "=", "item", ".", "params", "||", "{", "}", ";", "delete", "item", ".", "params", ";", "if", "(", "params", ".", "mediaPipeline", "==", "undefined", "&&", "host", "instanceof", "register", ".", "classes", ".", "MediaPipeline", ")", "params", ".", "mediaPipeline", "=", "host", ";", "var", "params_", "=", "extend", "(", "{", "}", ",", "params", ")", "item", ".", "constructorParams", "=", "checkParams", "(", "params_", ",", "constructor", ".", "constructorParams", ",", "item", ".", "type", ")", ";", "if", "(", "Object", ".", "keys", "(", "params_", ")", ")", "{", "item", ".", "properties", "=", "params_", ";", "}", "if", "(", "!", "Object", ".", "keys", "(", "item", ".", "constructorParams", ")", ".", "length", ")", "delete", "item", ".", "constructorParams", ";", "try", "{", "var", "mediaObject", "=", "createObject", "(", "constructor", ")", "}", "catch", "(", "error", ")", "{", "return", "callback", "(", "error", ")", "}", ";", "Object", ".", "defineProperty", "(", "item", ",", "'object'", ",", "{", "value", ":", "mediaObject", "}", ")", ";", "encodeCreate", "(", "transaction", ",", "item", ",", "callback", ")", ";", "return", "mediaObject", "}" ]
Request to the server to create a new MediaElement @param item @param {module:kurentoClient~MediaObjectCreator~createMediaObjectCallback} [callback]
[ "Request", "to", "the", "server", "to", "create", "a", "new", "MediaElement" ]
c17823b0c0a4381112fb2f084f407cbca627fc42
https://github.com/Kurento/kurento-client-js/blob/c17823b0c0a4381112fb2f084f407cbca627fc42/lib/MediaObjectCreator.js#L136-L176
13,948
glimmerjs/glimmer-vm
bin/run-qunit.js
exec
function exec(command, args) { execa.sync(command, args, { stdio: 'inherit', preferLocal: true, }); }
javascript
function exec(command, args) { execa.sync(command, args, { stdio: 'inherit', preferLocal: true, }); }
[ "function", "exec", "(", "command", ",", "args", ")", "{", "execa", ".", "sync", "(", "command", ",", "args", ",", "{", "stdio", ":", "'inherit'", ",", "preferLocal", ":", "true", ",", "}", ")", ";", "}" ]
Executes a command and pipes stdout back to the user.
[ "Executes", "a", "command", "and", "pipes", "stdout", "back", "to", "the", "user", "." ]
6978df9dc54721dbbec36e8c3024eb187626b999
https://github.com/glimmerjs/glimmer-vm/blob/6978df9dc54721dbbec36e8c3024eb187626b999/bin/run-qunit.js#L28-L33
13,949
orling/grapheme-splitter
index.js
codePointAt
function codePointAt(str, idx){ if(idx === undefined){ idx = 0; } var code = str.charCodeAt(idx); // if a high surrogate if (0xD800 <= code && code <= 0xDBFF && idx < str.length - 1){ var hi = code; var low = str.charCodeAt(idx + 1); if (0xDC00 <= low && low <= 0xDFFF){ return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000; } return hi; } // if a low surrogate if (0xDC00 <= code && code <= 0xDFFF && idx >= 1){ var hi = str.charCodeAt(idx - 1); var low = code; if (0xD800 <= hi && hi <= 0xDBFF){ return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000; } return low; } //just return the char if an unmatched surrogate half or a //single-char codepoint return code; }
javascript
function codePointAt(str, idx){ if(idx === undefined){ idx = 0; } var code = str.charCodeAt(idx); // if a high surrogate if (0xD800 <= code && code <= 0xDBFF && idx < str.length - 1){ var hi = code; var low = str.charCodeAt(idx + 1); if (0xDC00 <= low && low <= 0xDFFF){ return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000; } return hi; } // if a low surrogate if (0xDC00 <= code && code <= 0xDFFF && idx >= 1){ var hi = str.charCodeAt(idx - 1); var low = code; if (0xD800 <= hi && hi <= 0xDBFF){ return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000; } return low; } //just return the char if an unmatched surrogate half or a //single-char codepoint return code; }
[ "function", "codePointAt", "(", "str", ",", "idx", ")", "{", "if", "(", "idx", "===", "undefined", ")", "{", "idx", "=", "0", ";", "}", "var", "code", "=", "str", ".", "charCodeAt", "(", "idx", ")", ";", "// if a high surrogate", "if", "(", "0xD800", "<=", "code", "&&", "code", "<=", "0xDBFF", "&&", "idx", "<", "str", ".", "length", "-", "1", ")", "{", "var", "hi", "=", "code", ";", "var", "low", "=", "str", ".", "charCodeAt", "(", "idx", "+", "1", ")", ";", "if", "(", "0xDC00", "<=", "low", "&&", "low", "<=", "0xDFFF", ")", "{", "return", "(", "(", "hi", "-", "0xD800", ")", "*", "0x400", ")", "+", "(", "low", "-", "0xDC00", ")", "+", "0x10000", ";", "}", "return", "hi", ";", "}", "// if a low surrogate", "if", "(", "0xDC00", "<=", "code", "&&", "code", "<=", "0xDFFF", "&&", "idx", ">=", "1", ")", "{", "var", "hi", "=", "str", ".", "charCodeAt", "(", "idx", "-", "1", ")", ";", "var", "low", "=", "code", ";", "if", "(", "0xD800", "<=", "hi", "&&", "hi", "<=", "0xDBFF", ")", "{", "return", "(", "(", "hi", "-", "0xD800", ")", "*", "0x400", ")", "+", "(", "low", "-", "0xDC00", ")", "+", "0x10000", ";", "}", "return", "low", ";", "}", "//just return the char if an unmatched surrogate half or a ", "//single-char codepoint", "return", "code", ";", "}" ]
Private function, gets a Unicode code point from a JavaScript UTF-16 string handling surrogate pairs appropriately
[ "Private", "function", "gets", "a", "Unicode", "code", "point", "from", "a", "JavaScript", "UTF", "-", "16", "string", "handling", "surrogate", "pairs", "appropriately" ]
0609d90dcbc93b42d8ceebb7aec0eda38b5d916d
https://github.com/orling/grapheme-splitter/blob/0609d90dcbc93b42d8ceebb7aec0eda38b5d916d/index.js#L45-L76
13,950
Galooshi/import-js
lib/ModuleFinder.js
expandFiles
function expandFiles(files, workingDirectory) { const promises = []; files.forEach((file) => { if ( file.path !== './package.json' && file.path !== './npm-shrinkwrap.json' ) { promises.push(Promise.resolve(file)); return; } findPackageDependencies(workingDirectory, true).forEach((dep) => { let resolvedPath; try { resolvedPath = forwardSlashes(path.relative( workingDirectory, requireRelative.resolve(dep, workingDirectory), )); if (!resolvedPath.startsWith('.')) { // path.relative won't add "./", but we need it further down the line resolvedPath = `./${resolvedPath}`; } } catch (e) { winston.error(`Failed to resolve "${dep}" relative to ${workingDirectory}`); return; } promises.push(lastUpdate.failSafe(resolvedPath, workingDirectory) .then(({ mtime }) => Promise.resolve({ path: resolvedPath, mtime, packageName: dep, }))); }); }); return Promise.all(promises); }
javascript
function expandFiles(files, workingDirectory) { const promises = []; files.forEach((file) => { if ( file.path !== './package.json' && file.path !== './npm-shrinkwrap.json' ) { promises.push(Promise.resolve(file)); return; } findPackageDependencies(workingDirectory, true).forEach((dep) => { let resolvedPath; try { resolvedPath = forwardSlashes(path.relative( workingDirectory, requireRelative.resolve(dep, workingDirectory), )); if (!resolvedPath.startsWith('.')) { // path.relative won't add "./", but we need it further down the line resolvedPath = `./${resolvedPath}`; } } catch (e) { winston.error(`Failed to resolve "${dep}" relative to ${workingDirectory}`); return; } promises.push(lastUpdate.failSafe(resolvedPath, workingDirectory) .then(({ mtime }) => Promise.resolve({ path: resolvedPath, mtime, packageName: dep, }))); }); }); return Promise.all(promises); }
[ "function", "expandFiles", "(", "files", ",", "workingDirectory", ")", "{", "const", "promises", "=", "[", "]", ";", "files", ".", "forEach", "(", "(", "file", ")", "=>", "{", "if", "(", "file", ".", "path", "!==", "'./package.json'", "&&", "file", ".", "path", "!==", "'./npm-shrinkwrap.json'", ")", "{", "promises", ".", "push", "(", "Promise", ".", "resolve", "(", "file", ")", ")", ";", "return", ";", "}", "findPackageDependencies", "(", "workingDirectory", ",", "true", ")", ".", "forEach", "(", "(", "dep", ")", "=>", "{", "let", "resolvedPath", ";", "try", "{", "resolvedPath", "=", "forwardSlashes", "(", "path", ".", "relative", "(", "workingDirectory", ",", "requireRelative", ".", "resolve", "(", "dep", ",", "workingDirectory", ")", ",", ")", ")", ";", "if", "(", "!", "resolvedPath", ".", "startsWith", "(", "'.'", ")", ")", "{", "// path.relative won't add \"./\", but we need it further down the line", "resolvedPath", "=", "`", "${", "resolvedPath", "}", "`", ";", "}", "}", "catch", "(", "e", ")", "{", "winston", ".", "error", "(", "`", "${", "dep", "}", "${", "workingDirectory", "}", "`", ")", ";", "return", ";", "}", "promises", ".", "push", "(", "lastUpdate", ".", "failSafe", "(", "resolvedPath", ",", "workingDirectory", ")", ".", "then", "(", "(", "{", "mtime", "}", ")", "=>", "Promise", ".", "resolve", "(", "{", "path", ":", "resolvedPath", ",", "mtime", ",", "packageName", ":", "dep", ",", "}", ")", ")", ")", ";", "}", ")", ";", "}", ")", ";", "return", "Promise", ".", "all", "(", "promises", ")", ";", "}" ]
Checks for package.json or npm-shrinkwrap.json inside a list of files and expands the list of files to include package dependencies if so.
[ "Checks", "for", "package", ".", "json", "or", "npm", "-", "shrinkwrap", ".", "json", "inside", "a", "list", "of", "files", "and", "expands", "the", "list", "of", "files", "to", "include", "package", "dependencies", "if", "so", "." ]
dc8a158d15df50b2f15be3461f73706958df986d
https://github.com/Galooshi/import-js/blob/dc8a158d15df50b2f15be3461f73706958df986d/lib/ModuleFinder.js#L18-L53
13,951
Galooshi/import-js
lib/findExports.js
findAliasesForExports
function findAliasesForExports(nodes) { const result = new Set(['exports']); nodes.forEach((node) => { if (node.type !== 'VariableDeclaration') { return; } node.declarations.forEach(({ id, init }) => { if (!init) { return; } if (init.type !== 'Identifier') { return; } if (init.name !== 'exports') { return; } // We have something like // var foo = exports; result.add(id.name); }); }); return result; }
javascript
function findAliasesForExports(nodes) { const result = new Set(['exports']); nodes.forEach((node) => { if (node.type !== 'VariableDeclaration') { return; } node.declarations.forEach(({ id, init }) => { if (!init) { return; } if (init.type !== 'Identifier') { return; } if (init.name !== 'exports') { return; } // We have something like // var foo = exports; result.add(id.name); }); }); return result; }
[ "function", "findAliasesForExports", "(", "nodes", ")", "{", "const", "result", "=", "new", "Set", "(", "[", "'exports'", "]", ")", ";", "nodes", ".", "forEach", "(", "(", "node", ")", "=>", "{", "if", "(", "node", ".", "type", "!==", "'VariableDeclaration'", ")", "{", "return", ";", "}", "node", ".", "declarations", ".", "forEach", "(", "(", "{", "id", ",", "init", "}", ")", "=>", "{", "if", "(", "!", "init", ")", "{", "return", ";", "}", "if", "(", "init", ".", "type", "!==", "'Identifier'", ")", "{", "return", ";", "}", "if", "(", "init", ".", "name", "!==", "'exports'", ")", "{", "return", ";", "}", "// We have something like", "// var foo = exports;", "result", ".", "add", "(", "id", ".", "name", ")", ";", "}", ")", ";", "}", ")", ";", "return", "result", ";", "}" ]
This function will find variable declarations where `exports` is redefined as something else. E.g. const moduleName = exports;
[ "This", "function", "will", "find", "variable", "declarations", "where", "exports", "is", "redefined", "as", "something", "else", ".", "E", ".", "g", "." ]
dc8a158d15df50b2f15be3461f73706958df986d
https://github.com/Galooshi/import-js/blob/dc8a158d15df50b2f15be3461f73706958df986d/lib/findExports.js#L280-L302
13,952
mapbox/wellknown
index.js
stringify
function stringify (gj) { if (gj.type === 'Feature') { gj = gj.geometry; } function pairWKT (c) { return c.join(' '); } function ringWKT (r) { return r.map(pairWKT).join(', '); } function ringsWKT (r) { return r.map(ringWKT).map(wrapParens).join(', '); } function multiRingsWKT (r) { return r.map(ringsWKT).map(wrapParens).join(', '); } function wrapParens (s) { return '(' + s + ')'; } switch (gj.type) { case 'Point': return 'POINT (' + pairWKT(gj.coordinates) + ')'; case 'LineString': return 'LINESTRING (' + ringWKT(gj.coordinates) + ')'; case 'Polygon': return 'POLYGON (' + ringsWKT(gj.coordinates) + ')'; case 'MultiPoint': return 'MULTIPOINT (' + ringWKT(gj.coordinates) + ')'; case 'MultiPolygon': return 'MULTIPOLYGON (' + multiRingsWKT(gj.coordinates) + ')'; case 'MultiLineString': return 'MULTILINESTRING (' + ringsWKT(gj.coordinates) + ')'; case 'GeometryCollection': return 'GEOMETRYCOLLECTION (' + gj.geometries.map(stringify).join(', ') + ')'; default: throw new Error('stringify requires a valid GeoJSON Feature or geometry object as input'); } }
javascript
function stringify (gj) { if (gj.type === 'Feature') { gj = gj.geometry; } function pairWKT (c) { return c.join(' '); } function ringWKT (r) { return r.map(pairWKT).join(', '); } function ringsWKT (r) { return r.map(ringWKT).map(wrapParens).join(', '); } function multiRingsWKT (r) { return r.map(ringsWKT).map(wrapParens).join(', '); } function wrapParens (s) { return '(' + s + ')'; } switch (gj.type) { case 'Point': return 'POINT (' + pairWKT(gj.coordinates) + ')'; case 'LineString': return 'LINESTRING (' + ringWKT(gj.coordinates) + ')'; case 'Polygon': return 'POLYGON (' + ringsWKT(gj.coordinates) + ')'; case 'MultiPoint': return 'MULTIPOINT (' + ringWKT(gj.coordinates) + ')'; case 'MultiPolygon': return 'MULTIPOLYGON (' + multiRingsWKT(gj.coordinates) + ')'; case 'MultiLineString': return 'MULTILINESTRING (' + ringsWKT(gj.coordinates) + ')'; case 'GeometryCollection': return 'GEOMETRYCOLLECTION (' + gj.geometries.map(stringify).join(', ') + ')'; default: throw new Error('stringify requires a valid GeoJSON Feature or geometry object as input'); } }
[ "function", "stringify", "(", "gj", ")", "{", "if", "(", "gj", ".", "type", "===", "'Feature'", ")", "{", "gj", "=", "gj", ".", "geometry", ";", "}", "function", "pairWKT", "(", "c", ")", "{", "return", "c", ".", "join", "(", "' '", ")", ";", "}", "function", "ringWKT", "(", "r", ")", "{", "return", "r", ".", "map", "(", "pairWKT", ")", ".", "join", "(", "', '", ")", ";", "}", "function", "ringsWKT", "(", "r", ")", "{", "return", "r", ".", "map", "(", "ringWKT", ")", ".", "map", "(", "wrapParens", ")", ".", "join", "(", "', '", ")", ";", "}", "function", "multiRingsWKT", "(", "r", ")", "{", "return", "r", ".", "map", "(", "ringsWKT", ")", ".", "map", "(", "wrapParens", ")", ".", "join", "(", "', '", ")", ";", "}", "function", "wrapParens", "(", "s", ")", "{", "return", "'('", "+", "s", "+", "')'", ";", "}", "switch", "(", "gj", ".", "type", ")", "{", "case", "'Point'", ":", "return", "'POINT ('", "+", "pairWKT", "(", "gj", ".", "coordinates", ")", "+", "')'", ";", "case", "'LineString'", ":", "return", "'LINESTRING ('", "+", "ringWKT", "(", "gj", ".", "coordinates", ")", "+", "')'", ";", "case", "'Polygon'", ":", "return", "'POLYGON ('", "+", "ringsWKT", "(", "gj", ".", "coordinates", ")", "+", "')'", ";", "case", "'MultiPoint'", ":", "return", "'MULTIPOINT ('", "+", "ringWKT", "(", "gj", ".", "coordinates", ")", "+", "')'", ";", "case", "'MultiPolygon'", ":", "return", "'MULTIPOLYGON ('", "+", "multiRingsWKT", "(", "gj", ".", "coordinates", ")", "+", "')'", ";", "case", "'MultiLineString'", ":", "return", "'MULTILINESTRING ('", "+", "ringsWKT", "(", "gj", ".", "coordinates", ")", "+", "')'", ";", "case", "'GeometryCollection'", ":", "return", "'GEOMETRYCOLLECTION ('", "+", "gj", ".", "geometries", ".", "map", "(", "stringify", ")", ".", "join", "(", "', '", ")", "+", "')'", ";", "default", ":", "throw", "new", "Error", "(", "'stringify requires a valid GeoJSON Feature or geometry object as input'", ")", ";", "}", "}" ]
Stringifies a GeoJSON object into WKT
[ "Stringifies", "a", "GeoJSON", "object", "into", "WKT" ]
2d22aee0968bcfc11d58ea7dea0d7da1f1def541
https://github.com/mapbox/wellknown/blob/2d22aee0968bcfc11d58ea7dea0d7da1f1def541/index.js#L229-L270
13,953
anvilresearch/connect
oidc/sendVerificationEmail.js
sendVerificationEmail
function sendVerificationEmail (req, res, next) { // skip if we don't need to send the email if (!req.sendVerificationEmail) { next() // send the email } else { var user = req.user var ttl = (settings.emailVerification && settings.emailVerification.tokenTTL) || (3600 * 24 * 7) OneTimeToken.issue({ ttl: ttl, sub: user._id, use: 'emailVerification' }, function (err, token) { if (err) { return next(err) } var params = { token: token._id } ;[ 'redirect_uri', 'client_id', 'response_type', 'scope' ] .forEach(function (key) { var value = req.connectParams[key] if (value) { params[key] = value } }) // build email link var verifyURL = url.parse(settings.issuer) verifyURL.pathname = 'email/verify' verifyURL.query = params // email template data var locals = { email: user.email, name: { first: user.givenName, last: user.familyName }, verifyURL: url.format(verifyURL) } // Send verification email mailer.getMailer().sendMail('verifyEmail', locals, { to: user.email, subject: 'Verify your e-mail address' }, function (err, responseStatus) { if (err) { } // TODO: REQUIRES REFACTOR TO MAIL QUEUE next() }) }) } }
javascript
function sendVerificationEmail (req, res, next) { // skip if we don't need to send the email if (!req.sendVerificationEmail) { next() // send the email } else { var user = req.user var ttl = (settings.emailVerification && settings.emailVerification.tokenTTL) || (3600 * 24 * 7) OneTimeToken.issue({ ttl: ttl, sub: user._id, use: 'emailVerification' }, function (err, token) { if (err) { return next(err) } var params = { token: token._id } ;[ 'redirect_uri', 'client_id', 'response_type', 'scope' ] .forEach(function (key) { var value = req.connectParams[key] if (value) { params[key] = value } }) // build email link var verifyURL = url.parse(settings.issuer) verifyURL.pathname = 'email/verify' verifyURL.query = params // email template data var locals = { email: user.email, name: { first: user.givenName, last: user.familyName }, verifyURL: url.format(verifyURL) } // Send verification email mailer.getMailer().sendMail('verifyEmail', locals, { to: user.email, subject: 'Verify your e-mail address' }, function (err, responseStatus) { if (err) { } // TODO: REQUIRES REFACTOR TO MAIL QUEUE next() }) }) } }
[ "function", "sendVerificationEmail", "(", "req", ",", "res", ",", "next", ")", "{", "// skip if we don't need to send the email", "if", "(", "!", "req", ".", "sendVerificationEmail", ")", "{", "next", "(", ")", "// send the email", "}", "else", "{", "var", "user", "=", "req", ".", "user", "var", "ttl", "=", "(", "settings", ".", "emailVerification", "&&", "settings", ".", "emailVerification", ".", "tokenTTL", ")", "||", "(", "3600", "*", "24", "*", "7", ")", "OneTimeToken", ".", "issue", "(", "{", "ttl", ":", "ttl", ",", "sub", ":", "user", ".", "_id", ",", "use", ":", "'emailVerification'", "}", ",", "function", "(", "err", ",", "token", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", "}", "var", "params", "=", "{", "token", ":", "token", ".", "_id", "}", ";", "[", "'redirect_uri'", ",", "'client_id'", ",", "'response_type'", ",", "'scope'", "]", ".", "forEach", "(", "function", "(", "key", ")", "{", "var", "value", "=", "req", ".", "connectParams", "[", "key", "]", "if", "(", "value", ")", "{", "params", "[", "key", "]", "=", "value", "}", "}", ")", "// build email link", "var", "verifyURL", "=", "url", ".", "parse", "(", "settings", ".", "issuer", ")", "verifyURL", ".", "pathname", "=", "'email/verify'", "verifyURL", ".", "query", "=", "params", "// email template data", "var", "locals", "=", "{", "email", ":", "user", ".", "email", ",", "name", ":", "{", "first", ":", "user", ".", "givenName", ",", "last", ":", "user", ".", "familyName", "}", ",", "verifyURL", ":", "url", ".", "format", "(", "verifyURL", ")", "}", "// Send verification email", "mailer", ".", "getMailer", "(", ")", ".", "sendMail", "(", "'verifyEmail'", ",", "locals", ",", "{", "to", ":", "user", ".", "email", ",", "subject", ":", "'Verify your e-mail address'", "}", ",", "function", "(", "err", ",", "responseStatus", ")", "{", "if", "(", "err", ")", "{", "}", "// TODO: REQUIRES REFACTOR TO MAIL QUEUE", "next", "(", ")", "}", ")", "}", ")", "}", "}" ]
Send verification email middleware
[ "Send", "verification", "email", "middleware" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/oidc/sendVerificationEmail.js#L13-L71
13,954
anvilresearch/connect
oidc/determineProvider.js
determineProvider
function determineProvider (req, res, next) { var providerID = req.params.provider || req.body.provider if (providerID && settings.providers[providerID]) { req.provider = providers[providerID] } next() }
javascript
function determineProvider (req, res, next) { var providerID = req.params.provider || req.body.provider if (providerID && settings.providers[providerID]) { req.provider = providers[providerID] } next() }
[ "function", "determineProvider", "(", "req", ",", "res", ",", "next", ")", "{", "var", "providerID", "=", "req", ".", "params", ".", "provider", "||", "req", ".", "body", ".", "provider", "if", "(", "providerID", "&&", "settings", ".", "providers", "[", "providerID", "]", ")", "{", "req", ".", "provider", "=", "providers", "[", "providerID", "]", "}", "next", "(", ")", "}" ]
Determine provider middleware
[ "Determine", "provider", "middleware" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/oidc/determineProvider.js#L12-L18
13,955
anvilresearch/connect
lib/authenticator.js
setUserOnRequest
function setUserOnRequest (req, res, next) { if (!req.session || !req.session.user) { return next() } User.get(req.session.user, function (err, user) { if (err) { return next(err) } if (!user) { delete req.session.user return next() } req.user = user next() }) }
javascript
function setUserOnRequest (req, res, next) { if (!req.session || !req.session.user) { return next() } User.get(req.session.user, function (err, user) { if (err) { return next(err) } if (!user) { delete req.session.user return next() } req.user = user next() }) }
[ "function", "setUserOnRequest", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "!", "req", ".", "session", "||", "!", "req", ".", "session", ".", "user", ")", "{", "return", "next", "(", ")", "}", "User", ".", "get", "(", "req", ".", "session", ".", "user", ",", "function", "(", "err", ",", "user", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", "}", "if", "(", "!", "user", ")", "{", "delete", "req", ".", "session", ".", "user", "return", "next", "(", ")", "}", "req", ".", "user", "=", "user", "next", "(", ")", "}", ")", "}" ]
Set req.user
[ "Set", "req", ".", "user" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/lib/authenticator.js#L44-L60
13,956
anvilresearch/connect
models/User.js
hashPassword
function hashPassword (data) { var password = data.password var hash = data.hash if (password) { var salt = bcrypt.genSaltSync(10) hash = bcrypt.hashSync(password, salt) } this.hash = hash }
javascript
function hashPassword (data) { var password = data.password var hash = data.hash if (password) { var salt = bcrypt.genSaltSync(10) hash = bcrypt.hashSync(password, salt) } this.hash = hash }
[ "function", "hashPassword", "(", "data", ")", "{", "var", "password", "=", "data", ".", "password", "var", "hash", "=", "data", ".", "hash", "if", "(", "password", ")", "{", "var", "salt", "=", "bcrypt", ".", "genSaltSync", "(", "10", ")", "hash", "=", "bcrypt", ".", "hashSync", "(", "password", ",", "salt", ")", "}", "this", ".", "hash", "=", "hash", "}" ]
Hash Password Setter
[ "Hash", "Password", "Setter" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/models/User.js#L93-L103
13,957
anvilresearch/connect
models/Client.js
function (req, callback) { var params = req.body var clientId = params.client_id var clientSecret = params.client_secret // missing credentials if (!clientId || !clientSecret) { return callback(new AuthorizationError({ error: 'unauthorized_client', error_description: 'Missing client credentials', statusCode: 400 })) } Client.get(clientId, function (err, client) { if (err) { return callback(err) } // Unknown client if (!client) { return callback(new AuthorizationError({ error: 'unauthorized_client', error_description: 'Unknown client identifier', statusCode: 401 })) } // Mismatching secret if (client.client_secret !== clientSecret) { return callback(new AuthorizationError({ error: 'unauthorized_client', error_description: 'Mismatching client secret', statusCode: 401 })) } callback(null, client) }) }
javascript
function (req, callback) { var params = req.body var clientId = params.client_id var clientSecret = params.client_secret // missing credentials if (!clientId || !clientSecret) { return callback(new AuthorizationError({ error: 'unauthorized_client', error_description: 'Missing client credentials', statusCode: 400 })) } Client.get(clientId, function (err, client) { if (err) { return callback(err) } // Unknown client if (!client) { return callback(new AuthorizationError({ error: 'unauthorized_client', error_description: 'Unknown client identifier', statusCode: 401 })) } // Mismatching secret if (client.client_secret !== clientSecret) { return callback(new AuthorizationError({ error: 'unauthorized_client', error_description: 'Mismatching client secret', statusCode: 401 })) } callback(null, client) }) }
[ "function", "(", "req", ",", "callback", ")", "{", "var", "params", "=", "req", ".", "body", "var", "clientId", "=", "params", ".", "client_id", "var", "clientSecret", "=", "params", ".", "client_secret", "// missing credentials", "if", "(", "!", "clientId", "||", "!", "clientSecret", ")", "{", "return", "callback", "(", "new", "AuthorizationError", "(", "{", "error", ":", "'unauthorized_client'", ",", "error_description", ":", "'Missing client credentials'", ",", "statusCode", ":", "400", "}", ")", ")", "}", "Client", ".", "get", "(", "clientId", ",", "function", "(", "err", ",", "client", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", "}", "// Unknown client", "if", "(", "!", "client", ")", "{", "return", "callback", "(", "new", "AuthorizationError", "(", "{", "error", ":", "'unauthorized_client'", ",", "error_description", ":", "'Unknown client identifier'", ",", "statusCode", ":", "401", "}", ")", ")", "}", "// Mismatching secret", "if", "(", "client", ".", "client_secret", "!==", "clientSecret", ")", "{", "return", "callback", "(", "new", "AuthorizationError", "(", "{", "error", ":", "'unauthorized_client'", ",", "error_description", ":", "'Mismatching client secret'", ",", "statusCode", ":", "401", "}", ")", ")", "}", "callback", "(", "null", ",", "client", ")", "}", ")", "}" ]
HTTP POST body authentication
[ "HTTP", "POST", "body", "authentication" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/models/Client.js#L1007-L1044
13,958
anvilresearch/connect
protocols/LDAP.js
dnToDomain
function dnToDomain (dn) { if (!dn || typeof dn !== 'string') { return null } var matches = domainDnRegex.exec(dn) if (matches) { return matches[1].replace(dnPartRegex, '$1.').toLowerCase() } else { return null } }
javascript
function dnToDomain (dn) { if (!dn || typeof dn !== 'string') { return null } var matches = domainDnRegex.exec(dn) if (matches) { return matches[1].replace(dnPartRegex, '$1.').toLowerCase() } else { return null } }
[ "function", "dnToDomain", "(", "dn", ")", "{", "if", "(", "!", "dn", "||", "typeof", "dn", "!==", "'string'", ")", "{", "return", "null", "}", "var", "matches", "=", "domainDnRegex", ".", "exec", "(", "dn", ")", "if", "(", "matches", ")", "{", "return", "matches", "[", "1", "]", ".", "replace", "(", "dnPartRegex", ",", "'$1.'", ")", ".", "toLowerCase", "(", ")", "}", "else", "{", "return", "null", "}", "}" ]
Extracts a lowercased domain from a distinguished name for comparison purposes. e.g. "CN=User,OU=MyBusiness,DC=example,DC=com" will return "example.com."
[ "Extracts", "a", "lowercased", "domain", "from", "a", "distinguished", "name", "for", "comparison", "purposes", "." ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/protocols/LDAP.js#L26-L34
13,959
anvilresearch/connect
protocols/LDAP.js
normalizeDN
function normalizeDN (dn) { if (!dn || typeof dn !== 'string') { return null } var normalizedDN = '' // Take advantage of replace() to grab the matched segments of the DN. If what // is left over contains unexpected characters, we assume the original DN was // malformed. var extra = dn.replace(dnPartRegex, function (match) { normalizedDN += match.toLowerCase() + ',' return '' }) if (!normalizedDN) { return null } if (badExtra.test(extra)) { return null } return normalizedDN.substr(0, normalizedDN.length - 1) }
javascript
function normalizeDN (dn) { if (!dn || typeof dn !== 'string') { return null } var normalizedDN = '' // Take advantage of replace() to grab the matched segments of the DN. If what // is left over contains unexpected characters, we assume the original DN was // malformed. var extra = dn.replace(dnPartRegex, function (match) { normalizedDN += match.toLowerCase() + ',' return '' }) if (!normalizedDN) { return null } if (badExtra.test(extra)) { return null } return normalizedDN.substr(0, normalizedDN.length - 1) }
[ "function", "normalizeDN", "(", "dn", ")", "{", "if", "(", "!", "dn", "||", "typeof", "dn", "!==", "'string'", ")", "{", "return", "null", "}", "var", "normalizedDN", "=", "''", "// Take advantage of replace() to grab the matched segments of the DN. If what", "// is left over contains unexpected characters, we assume the original DN was", "// malformed.", "var", "extra", "=", "dn", ".", "replace", "(", "dnPartRegex", ",", "function", "(", "match", ")", "{", "normalizedDN", "+=", "match", ".", "toLowerCase", "(", ")", "+", "','", "return", "''", "}", ")", "if", "(", "!", "normalizedDN", ")", "{", "return", "null", "}", "if", "(", "badExtra", ".", "test", "(", "extra", ")", ")", "{", "return", "null", "}", "return", "normalizedDN", ".", "substr", "(", "0", ",", "normalizedDN", ".", "length", "-", "1", ")", "}" ]
Normalizes distinguished names, removing any extra whitespace, lowercasing the DN, and running some basic validation checks. If the DN is found to be malformed, will return null.
[ "Normalizes", "distinguished", "names", "removing", "any", "extra", "whitespace", "lowercasing", "the", "DN", "and", "running", "some", "basic", "validation", "checks", "." ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/protocols/LDAP.js#L43-L56
13,960
anvilresearch/connect
protocols/OAuth2.js
authorizationCodeGrant
function authorizationCodeGrant (code, done) { var endpoint = this.endpoints.token var provider = this.provider var client = this.client var url = endpoint.url var method = endpoint.method && endpoint.method.toLowerCase() var auth = endpoint.auth var parser = endpoint.parser var accept = endpoint.accept || 'application/json' var params = {} // required token parameters params.grant_type = 'authorization_code' params.code = code params.redirect_uri = provider.redirect_uri // start building the request var req = request[method || 'post'](url) // Authenticate the client with HTTP Basic if (auth === 'client_secret_basic') { req.set('Authorization', 'Basic ' + this.base64credentials()) } // Authenticate the client with POST params if (auth === 'client_secret_post') { params.client_id = client.client_id params.client_secret = client.client_secret } // Add request body params and set other headers req.send(qs.stringify(params)) req.set('accept', accept) req.set('user-agent', agent) // Execute the request return req.end(function (err, res) { if (err) { return done(err) } var response = (parser === 'x-www-form-urlencoded') ? qs.parse(res.text) : res.body if (res.statusCode !== 200) { return done(response) } done(null, response) }) }
javascript
function authorizationCodeGrant (code, done) { var endpoint = this.endpoints.token var provider = this.provider var client = this.client var url = endpoint.url var method = endpoint.method && endpoint.method.toLowerCase() var auth = endpoint.auth var parser = endpoint.parser var accept = endpoint.accept || 'application/json' var params = {} // required token parameters params.grant_type = 'authorization_code' params.code = code params.redirect_uri = provider.redirect_uri // start building the request var req = request[method || 'post'](url) // Authenticate the client with HTTP Basic if (auth === 'client_secret_basic') { req.set('Authorization', 'Basic ' + this.base64credentials()) } // Authenticate the client with POST params if (auth === 'client_secret_post') { params.client_id = client.client_id params.client_secret = client.client_secret } // Add request body params and set other headers req.send(qs.stringify(params)) req.set('accept', accept) req.set('user-agent', agent) // Execute the request return req.end(function (err, res) { if (err) { return done(err) } var response = (parser === 'x-www-form-urlencoded') ? qs.parse(res.text) : res.body if (res.statusCode !== 200) { return done(response) } done(null, response) }) }
[ "function", "authorizationCodeGrant", "(", "code", ",", "done", ")", "{", "var", "endpoint", "=", "this", ".", "endpoints", ".", "token", "var", "provider", "=", "this", ".", "provider", "var", "client", "=", "this", ".", "client", "var", "url", "=", "endpoint", ".", "url", "var", "method", "=", "endpoint", ".", "method", "&&", "endpoint", ".", "method", ".", "toLowerCase", "(", ")", "var", "auth", "=", "endpoint", ".", "auth", "var", "parser", "=", "endpoint", ".", "parser", "var", "accept", "=", "endpoint", ".", "accept", "||", "'application/json'", "var", "params", "=", "{", "}", "// required token parameters", "params", ".", "grant_type", "=", "'authorization_code'", "params", ".", "code", "=", "code", "params", ".", "redirect_uri", "=", "provider", ".", "redirect_uri", "// start building the request", "var", "req", "=", "request", "[", "method", "||", "'post'", "]", "(", "url", ")", "// Authenticate the client with HTTP Basic", "if", "(", "auth", "===", "'client_secret_basic'", ")", "{", "req", ".", "set", "(", "'Authorization'", ",", "'Basic '", "+", "this", ".", "base64credentials", "(", ")", ")", "}", "// Authenticate the client with POST params", "if", "(", "auth", "===", "'client_secret_post'", ")", "{", "params", ".", "client_id", "=", "client", ".", "client_id", "params", ".", "client_secret", "=", "client", ".", "client_secret", "}", "// Add request body params and set other headers", "req", ".", "send", "(", "qs", ".", "stringify", "(", "params", ")", ")", "req", ".", "set", "(", "'accept'", ",", "accept", ")", "req", ".", "set", "(", "'user-agent'", ",", "agent", ")", "// Execute the request", "return", "req", ".", "end", "(", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "return", "done", "(", "err", ")", "}", "var", "response", "=", "(", "parser", "===", "'x-www-form-urlencoded'", ")", "?", "qs", ".", "parse", "(", "res", ".", "text", ")", ":", "res", ".", "body", "if", "(", "res", ".", "statusCode", "!==", "200", ")", "{", "return", "done", "(", "response", ")", "}", "done", "(", "null", ",", "response", ")", "}", ")", "}" ]
Authorization Code Grant Request
[ "Authorization", "Code", "Grant", "Request" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/protocols/OAuth2.js#L166-L214
13,961
anvilresearch/connect
models/UserApplications.js
function (done) { Client.listByTrusted('true', { select: [ '_id', 'client_name', 'client_uri', 'application_type', 'logo_uri', 'trusted', 'scopes', 'created', 'modified' ] }, function (err, clients) { if (err) { return done(err) } done(null, clients) }) }
javascript
function (done) { Client.listByTrusted('true', { select: [ '_id', 'client_name', 'client_uri', 'application_type', 'logo_uri', 'trusted', 'scopes', 'created', 'modified' ] }, function (err, clients) { if (err) { return done(err) } done(null, clients) }) }
[ "function", "(", "done", ")", "{", "Client", ".", "listByTrusted", "(", "'true'", ",", "{", "select", ":", "[", "'_id'", ",", "'client_name'", ",", "'client_uri'", ",", "'application_type'", ",", "'logo_uri'", ",", "'trusted'", ",", "'scopes'", ",", "'created'", ",", "'modified'", "]", "}", ",", "function", "(", "err", ",", "clients", ")", "{", "if", "(", "err", ")", "{", "return", "done", "(", "err", ")", "}", "done", "(", "null", ",", "clients", ")", "}", ")", "}" ]
List the trusted clients
[ "List", "the", "trusted", "clients" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/models/UserApplications.js#L15-L32
13,962
anvilresearch/connect
models/UserApplications.js
function (done) { user.authorizedScope(function (err, scopes) { if (err) { return done(err) } done(null, scopes) }) }
javascript
function (done) { user.authorizedScope(function (err, scopes) { if (err) { return done(err) } done(null, scopes) }) }
[ "function", "(", "done", ")", "{", "user", ".", "authorizedScope", "(", "function", "(", "err", ",", "scopes", ")", "{", "if", "(", "err", ")", "{", "return", "done", "(", "err", ")", "}", "done", "(", "null", ",", "scopes", ")", "}", ")", "}" ]
Get the authorized scope for the user
[ "Get", "the", "authorized", "scope", "for", "the", "user" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/models/UserApplications.js#L35-L40
13,963
anvilresearch/connect
models/UserApplications.js
function (done) { var index = 'users:' + user._id + ':clients' Client.__client.zrevrange(index, 0, -1, function (err, ids) { if (err) { return done(err) } done(null, ids) }) }
javascript
function (done) { var index = 'users:' + user._id + ':clients' Client.__client.zrevrange(index, 0, -1, function (err, ids) { if (err) { return done(err) } done(null, ids) }) }
[ "function", "(", "done", ")", "{", "var", "index", "=", "'users:'", "+", "user", ".", "_id", "+", "':clients'", "Client", ".", "__client", ".", "zrevrange", "(", "index", ",", "0", ",", "-", "1", ",", "function", "(", "err", ",", "ids", ")", "{", "if", "(", "err", ")", "{", "return", "done", "(", "err", ")", "}", "done", "(", "null", ",", "ids", ")", "}", ")", "}" ]
List of client ids the user has visited
[ "List", "of", "client", "ids", "the", "user", "has", "visited" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/models/UserApplications.js#L43-L49
13,964
anvilresearch/connect
public/javascript/session.js
setOPBrowserState
function setOPBrowserState (event) { var key = 'anvil.connect.op.state' var current = localStorage[key] var update = event.data if (current !== update) { document.cookie = 'anvil.connect.op.state=' + update localStorage['anvil.connect.op.state'] = update } }
javascript
function setOPBrowserState (event) { var key = 'anvil.connect.op.state' var current = localStorage[key] var update = event.data if (current !== update) { document.cookie = 'anvil.connect.op.state=' + update localStorage['anvil.connect.op.state'] = update } }
[ "function", "setOPBrowserState", "(", "event", ")", "{", "var", "key", "=", "'anvil.connect.op.state'", "var", "current", "=", "localStorage", "[", "key", "]", "var", "update", "=", "event", ".", "data", "if", "(", "current", "!==", "update", ")", "{", "document", ".", "cookie", "=", "'anvil.connect.op.state='", "+", "update", "localStorage", "[", "'anvil.connect.op.state'", "]", "=", "update", "}", "}" ]
Set browser state
[ "Set", "browser", "state" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/public/javascript/session.js#L29-L38
13,965
anvilresearch/connect
public/javascript/session.js
pushToRP
function pushToRP (event) { if (source) { console.log('updating RP: changed') source.postMessage('changed', origin) } else { console.log('updateRP called but source undefined') } }
javascript
function pushToRP (event) { if (source) { console.log('updating RP: changed') source.postMessage('changed', origin) } else { console.log('updateRP called but source undefined') } }
[ "function", "pushToRP", "(", "event", ")", "{", "if", "(", "source", ")", "{", "console", ".", "log", "(", "'updating RP: changed'", ")", "source", ".", "postMessage", "(", "'changed'", ",", "origin", ")", "}", "else", "{", "console", ".", "log", "(", "'updateRP called but source undefined'", ")", "}", "}" ]
Watch localStorage and keep the RP updated
[ "Watch", "localStorage", "and", "keep", "the", "RP", "updated" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/public/javascript/session.js#L51-L58
13,966
anvilresearch/connect
public/javascript/session.js
respondToRPMessage
function respondToRPMessage (event) { var parser, messenger, clientId, rpss, salt, opbs, input, opss, comparison // Parse message origin origin = event.origin parser = document.createElement('a') parser.href = document.referrer messenger = parser.protocol + '//' + parser.host // Ignore the message if origin doesn't match if (origin !== messenger) { return } // get a reference to the source so we can message it // immediately in response to a change in sessionState source = event.source // Parse the message clientId = event.data.split(' ')[0] rpss = event.data.split(' ')[1] salt = rpss.split('.')[1] // Validate message syntax if (!clientId || !rpss || !salt) { event.source.postMessage('error', origin) } // Get the OP browser state opbs = getOPBrowserState() // Recalculate session state for comparison input = [clientId, origin, opbs, salt].join(' ') opss = [CryptoJS.SHA256(input), salt].join('.') // Compare the RP session state with the OP session state comparison = compareSessionState(rpss, opss) // Compare session state and reply to RP event.source.postMessage(comparison, origin) }
javascript
function respondToRPMessage (event) { var parser, messenger, clientId, rpss, salt, opbs, input, opss, comparison // Parse message origin origin = event.origin parser = document.createElement('a') parser.href = document.referrer messenger = parser.protocol + '//' + parser.host // Ignore the message if origin doesn't match if (origin !== messenger) { return } // get a reference to the source so we can message it // immediately in response to a change in sessionState source = event.source // Parse the message clientId = event.data.split(' ')[0] rpss = event.data.split(' ')[1] salt = rpss.split('.')[1] // Validate message syntax if (!clientId || !rpss || !salt) { event.source.postMessage('error', origin) } // Get the OP browser state opbs = getOPBrowserState() // Recalculate session state for comparison input = [clientId, origin, opbs, salt].join(' ') opss = [CryptoJS.SHA256(input), salt].join('.') // Compare the RP session state with the OP session state comparison = compareSessionState(rpss, opss) // Compare session state and reply to RP event.source.postMessage(comparison, origin) }
[ "function", "respondToRPMessage", "(", "event", ")", "{", "var", "parser", ",", "messenger", ",", "clientId", ",", "rpss", ",", "salt", ",", "opbs", ",", "input", ",", "opss", ",", "comparison", "// Parse message origin", "origin", "=", "event", ".", "origin", "parser", "=", "document", ".", "createElement", "(", "'a'", ")", "parser", ".", "href", "=", "document", ".", "referrer", "messenger", "=", "parser", ".", "protocol", "+", "'//'", "+", "parser", ".", "host", "// Ignore the message if origin doesn't match", "if", "(", "origin", "!==", "messenger", ")", "{", "return", "}", "// get a reference to the source so we can message it", "// immediately in response to a change in sessionState", "source", "=", "event", ".", "source", "// Parse the message", "clientId", "=", "event", ".", "data", ".", "split", "(", "' '", ")", "[", "0", "]", "rpss", "=", "event", ".", "data", ".", "split", "(", "' '", ")", "[", "1", "]", "salt", "=", "rpss", ".", "split", "(", "'.'", ")", "[", "1", "]", "// Validate message syntax", "if", "(", "!", "clientId", "||", "!", "rpss", "||", "!", "salt", ")", "{", "event", ".", "source", ".", "postMessage", "(", "'error'", ",", "origin", ")", "}", "// Get the OP browser state", "opbs", "=", "getOPBrowserState", "(", ")", "// Recalculate session state for comparison", "input", "=", "[", "clientId", ",", "origin", ",", "opbs", ",", "salt", "]", ".", "join", "(", "' '", ")", "opss", "=", "[", "CryptoJS", ".", "SHA256", "(", "input", ")", ",", "salt", "]", ".", "join", "(", "'.'", ")", "// Compare the RP session state with the OP session state", "comparison", "=", "compareSessionState", "(", "rpss", ",", "opss", ")", "// Compare session state and reply to RP", "event", ".", "source", ".", "postMessage", "(", "comparison", ",", "origin", ")", "}" ]
Respond to RP postMessage
[ "Respond", "to", "RP", "postMessage" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/public/javascript/session.js#L74-L115
13,967
anvilresearch/connect
oidc/getBearerToken.js
getBearerToken
function getBearerToken (req, res, next) { // check for access token in the authorization header if (req.authorization.scheme && req.authorization.scheme.match(/Bearer/i)) { req.bearer = req.authorization.credentials } // check for access token in the query params if (req.query && req.query.access_token) { if (req.bearer) { return next(new UnauthorizedError({ error: 'invalid_request', error_description: 'Multiple authentication methods', statusCode: 400 })) } req.bearer = req.query.access_token } // check for access token in the request body if (req.body && req.body.access_token) { if (req.bearer) { return next(new UnauthorizedError({ error: 'invalid_request', error_description: 'Multiple authentication methods', statusCode: 400 })) } if (req.headers && req.headers['content-type'] !== 'application/x-www-form-urlencoded') { return next(new UnauthorizedError({ error: 'invalid_request', error_description: 'Invalid content-type', statusCode: 400 })) } req.bearer = req.body.access_token } next() }
javascript
function getBearerToken (req, res, next) { // check for access token in the authorization header if (req.authorization.scheme && req.authorization.scheme.match(/Bearer/i)) { req.bearer = req.authorization.credentials } // check for access token in the query params if (req.query && req.query.access_token) { if (req.bearer) { return next(new UnauthorizedError({ error: 'invalid_request', error_description: 'Multiple authentication methods', statusCode: 400 })) } req.bearer = req.query.access_token } // check for access token in the request body if (req.body && req.body.access_token) { if (req.bearer) { return next(new UnauthorizedError({ error: 'invalid_request', error_description: 'Multiple authentication methods', statusCode: 400 })) } if (req.headers && req.headers['content-type'] !== 'application/x-www-form-urlencoded') { return next(new UnauthorizedError({ error: 'invalid_request', error_description: 'Invalid content-type', statusCode: 400 })) } req.bearer = req.body.access_token } next() }
[ "function", "getBearerToken", "(", "req", ",", "res", ",", "next", ")", "{", "// check for access token in the authorization header", "if", "(", "req", ".", "authorization", ".", "scheme", "&&", "req", ".", "authorization", ".", "scheme", ".", "match", "(", "/", "Bearer", "/", "i", ")", ")", "{", "req", ".", "bearer", "=", "req", ".", "authorization", ".", "credentials", "}", "// check for access token in the query params", "if", "(", "req", ".", "query", "&&", "req", ".", "query", ".", "access_token", ")", "{", "if", "(", "req", ".", "bearer", ")", "{", "return", "next", "(", "new", "UnauthorizedError", "(", "{", "error", ":", "'invalid_request'", ",", "error_description", ":", "'Multiple authentication methods'", ",", "statusCode", ":", "400", "}", ")", ")", "}", "req", ".", "bearer", "=", "req", ".", "query", ".", "access_token", "}", "// check for access token in the request body", "if", "(", "req", ".", "body", "&&", "req", ".", "body", ".", "access_token", ")", "{", "if", "(", "req", ".", "bearer", ")", "{", "return", "next", "(", "new", "UnauthorizedError", "(", "{", "error", ":", "'invalid_request'", ",", "error_description", ":", "'Multiple authentication methods'", ",", "statusCode", ":", "400", "}", ")", ")", "}", "if", "(", "req", ".", "headers", "&&", "req", ".", "headers", "[", "'content-type'", "]", "!==", "'application/x-www-form-urlencoded'", ")", "{", "return", "next", "(", "new", "UnauthorizedError", "(", "{", "error", ":", "'invalid_request'", ",", "error_description", ":", "'Invalid content-type'", ",", "statusCode", ":", "400", "}", ")", ")", "}", "req", ".", "bearer", "=", "req", ".", "body", ".", "access_token", "}", "next", "(", ")", "}" ]
Get Bearer Token NOTE: This middleware assumes parseAuthorizationHeader has been invoked upstream.
[ "Get", "Bearer", "Token" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/oidc/getBearerToken.js#L14-L56
13,968
anvilresearch/connect
oidc/selectConnectParams.js
selectConnectParams
function selectConnectParams (req, res, next) { req.connectParams = req[lookupField[req.method]] || {} next() }
javascript
function selectConnectParams (req, res, next) { req.connectParams = req[lookupField[req.method]] || {} next() }
[ "function", "selectConnectParams", "(", "req", ",", "res", ",", "next", ")", "{", "req", ".", "connectParams", "=", "req", "[", "lookupField", "[", "req", ".", "method", "]", "]", "||", "{", "}", "next", "(", ")", "}" ]
Select Authorization Parameters
[ "Select", "Authorization", "Parameters" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/oidc/selectConnectParams.js#L18-L21
13,969
anvilresearch/connect
models/AccessToken.js
function (done) { // the token is random if (token.indexOf('.') === -1) { AccessToken.get(token, function (err, instance) { if (err) { return done(err) } if (!instance) { return done(new UnauthorizedError({ realm: 'user', error: 'invalid_request', error_description: 'Unknown access token', statusCode: 401 })) } done(null, { jti: instance.at, iss: instance.iss, sub: instance.uid, aud: instance.cid, iat: instance.created, exp: instance.created + instance.ei, scope: instance.scope }) }) // the token is not random } else { done() } }
javascript
function (done) { // the token is random if (token.indexOf('.') === -1) { AccessToken.get(token, function (err, instance) { if (err) { return done(err) } if (!instance) { return done(new UnauthorizedError({ realm: 'user', error: 'invalid_request', error_description: 'Unknown access token', statusCode: 401 })) } done(null, { jti: instance.at, iss: instance.iss, sub: instance.uid, aud: instance.cid, iat: instance.created, exp: instance.created + instance.ei, scope: instance.scope }) }) // the token is not random } else { done() } }
[ "function", "(", "done", ")", "{", "// the token is random", "if", "(", "token", ".", "indexOf", "(", "'.'", ")", "===", "-", "1", ")", "{", "AccessToken", ".", "get", "(", "token", ",", "function", "(", "err", ",", "instance", ")", "{", "if", "(", "err", ")", "{", "return", "done", "(", "err", ")", "}", "if", "(", "!", "instance", ")", "{", "return", "done", "(", "new", "UnauthorizedError", "(", "{", "realm", ":", "'user'", ",", "error", ":", "'invalid_request'", ",", "error_description", ":", "'Unknown access token'", ",", "statusCode", ":", "401", "}", ")", ")", "}", "done", "(", "null", ",", "{", "jti", ":", "instance", ".", "at", ",", "iss", ":", "instance", ".", "iss", ",", "sub", ":", "instance", ".", "uid", ",", "aud", ":", "instance", ".", "cid", ",", "iat", ":", "instance", ".", "created", ",", "exp", ":", "instance", ".", "created", "+", "instance", ".", "ei", ",", "scope", ":", "instance", ".", "scope", "}", ")", "}", ")", "// the token is not random", "}", "else", "{", "done", "(", ")", "}", "}" ]
Fetch from database
[ "Fetch", "from", "database" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/models/AccessToken.js#L279-L311
13,970
anvilresearch/connect
oidc/determineClientScope.js
determineClientScope
function determineClientScope (req, res, next) { var params = req.connectParams var subject = req.client var scope = params.scope || subject.default_client_scope if (params.grant_type === 'client_credentials') { Scope.determine(scope, subject, function (err, scope, scopes) { if (err) { return next(err) } req.scope = scope req.scopes = scopes next() }) } else { next() } }
javascript
function determineClientScope (req, res, next) { var params = req.connectParams var subject = req.client var scope = params.scope || subject.default_client_scope if (params.grant_type === 'client_credentials') { Scope.determine(scope, subject, function (err, scope, scopes) { if (err) { return next(err) } req.scope = scope req.scopes = scopes next() }) } else { next() } }
[ "function", "determineClientScope", "(", "req", ",", "res", ",", "next", ")", "{", "var", "params", "=", "req", ".", "connectParams", "var", "subject", "=", "req", ".", "client", "var", "scope", "=", "params", ".", "scope", "||", "subject", ".", "default_client_scope", "if", "(", "params", ".", "grant_type", "===", "'client_credentials'", ")", "{", "Scope", ".", "determine", "(", "scope", ",", "subject", ",", "function", "(", "err", ",", "scope", ",", "scopes", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", "}", "req", ".", "scope", "=", "scope", "req", ".", "scopes", "=", "scopes", "next", "(", ")", "}", ")", "}", "else", "{", "next", "(", ")", "}", "}" ]
Determine client scope
[ "Determine", "client", "scope" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/oidc/determineClientScope.js#L11-L26
13,971
anvilresearch/connect
oidc/unstashParams.js
unstashParams
function unstashParams (req, res, next) { // OAuth 2.0 callbacks should have a state param // OAuth 1.0 must use the session to store the state value var id = req.query.state || req.session.state var key = 'authorization:' + id if (!id) { // && request is OAuth 2.0 return next(new MissingStateError()) } client.get(key, function (err, params) { if (err) { return next(err) } // This handles expired and mismatching state params if (!params) { return next(new ExpiredAuthorizationRequestError()) } try { req.connectParams = JSON.parse(params) } catch (err) { next(err) } next() }) }
javascript
function unstashParams (req, res, next) { // OAuth 2.0 callbacks should have a state param // OAuth 1.0 must use the session to store the state value var id = req.query.state || req.session.state var key = 'authorization:' + id if (!id) { // && request is OAuth 2.0 return next(new MissingStateError()) } client.get(key, function (err, params) { if (err) { return next(err) } // This handles expired and mismatching state params if (!params) { return next(new ExpiredAuthorizationRequestError()) } try { req.connectParams = JSON.parse(params) } catch (err) { next(err) } next() }) }
[ "function", "unstashParams", "(", "req", ",", "res", ",", "next", ")", "{", "// OAuth 2.0 callbacks should have a state param", "// OAuth 1.0 must use the session to store the state value", "var", "id", "=", "req", ".", "query", ".", "state", "||", "req", ".", "session", ".", "state", "var", "key", "=", "'authorization:'", "+", "id", "if", "(", "!", "id", ")", "{", "// && request is OAuth 2.0", "return", "next", "(", "new", "MissingStateError", "(", ")", ")", "}", "client", ".", "get", "(", "key", ",", "function", "(", "err", ",", "params", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", "}", "// This handles expired and mismatching state params", "if", "(", "!", "params", ")", "{", "return", "next", "(", "new", "ExpiredAuthorizationRequestError", "(", ")", ")", "}", "try", "{", "req", ".", "connectParams", "=", "JSON", ".", "parse", "(", "params", ")", "}", "catch", "(", "err", ")", "{", "next", "(", "err", ")", "}", "next", "(", ")", "}", ")", "}" ]
Unstash authorization params
[ "Unstash", "authorization", "params" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/oidc/unstashParams.js#L13-L37
13,972
anvilresearch/connect
oidc/verifyAuthorizationCode.js
verifyAuthorizationCode
function verifyAuthorizationCode (req, res, next) { var params = req.connectParams if (params.grant_type === 'authorization_code') { AuthorizationCode.getByCode(params.code, function (err, ac) { if (err) { return next(err) } // Can't find authorization code if (!ac) { return next(new AuthorizationError({ error: 'invalid_grant', error_description: 'Authorization not found', statusCode: 400 })) } // Authorization code has been previously used if (ac.used === true) { return next(new AuthorizationError({ error: 'invalid_grant', error_description: 'Authorization code invalid', statusCode: 400 })) } // Authorization code is expired if (nowSeconds() > ac.expires_at) { return next(new AuthorizationError({ error: 'invalid_grant', error_description: 'Authorization code expired', statusCode: 400 })) } // Mismatching redirect uri if (ac.redirect_uri !== params.redirect_uri) { return next(new AuthorizationError({ error: 'invalid_grant', error_description: 'Mismatching redirect uri', statusCode: 400 })) } // Mismatching client id if (ac.client_id !== req.client._id) { return next(new AuthorizationError({ error: 'invalid_grant', error_description: 'Mismatching client id', statusCode: 400 })) } // Mismatching user id // if (ac.user_id !== req.user._id) { // return next(new AuthorizationError({ // error: 'invalid_grant', // error_description: 'Mismatching client id', // statusCode: 400 // })) // } req.code = ac // Update the code to show that it's been used. AuthorizationCode.patch(ac._id, { used: true }, function (err) { next(err) }) }) } else { next() } }
javascript
function verifyAuthorizationCode (req, res, next) { var params = req.connectParams if (params.grant_type === 'authorization_code') { AuthorizationCode.getByCode(params.code, function (err, ac) { if (err) { return next(err) } // Can't find authorization code if (!ac) { return next(new AuthorizationError({ error: 'invalid_grant', error_description: 'Authorization not found', statusCode: 400 })) } // Authorization code has been previously used if (ac.used === true) { return next(new AuthorizationError({ error: 'invalid_grant', error_description: 'Authorization code invalid', statusCode: 400 })) } // Authorization code is expired if (nowSeconds() > ac.expires_at) { return next(new AuthorizationError({ error: 'invalid_grant', error_description: 'Authorization code expired', statusCode: 400 })) } // Mismatching redirect uri if (ac.redirect_uri !== params.redirect_uri) { return next(new AuthorizationError({ error: 'invalid_grant', error_description: 'Mismatching redirect uri', statusCode: 400 })) } // Mismatching client id if (ac.client_id !== req.client._id) { return next(new AuthorizationError({ error: 'invalid_grant', error_description: 'Mismatching client id', statusCode: 400 })) } // Mismatching user id // if (ac.user_id !== req.user._id) { // return next(new AuthorizationError({ // error: 'invalid_grant', // error_description: 'Mismatching client id', // statusCode: 400 // })) // } req.code = ac // Update the code to show that it's been used. AuthorizationCode.patch(ac._id, { used: true }, function (err) { next(err) }) }) } else { next() } }
[ "function", "verifyAuthorizationCode", "(", "req", ",", "res", ",", "next", ")", "{", "var", "params", "=", "req", ".", "connectParams", "if", "(", "params", ".", "grant_type", "===", "'authorization_code'", ")", "{", "AuthorizationCode", ".", "getByCode", "(", "params", ".", "code", ",", "function", "(", "err", ",", "ac", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", "}", "// Can't find authorization code", "if", "(", "!", "ac", ")", "{", "return", "next", "(", "new", "AuthorizationError", "(", "{", "error", ":", "'invalid_grant'", ",", "error_description", ":", "'Authorization not found'", ",", "statusCode", ":", "400", "}", ")", ")", "}", "// Authorization code has been previously used", "if", "(", "ac", ".", "used", "===", "true", ")", "{", "return", "next", "(", "new", "AuthorizationError", "(", "{", "error", ":", "'invalid_grant'", ",", "error_description", ":", "'Authorization code invalid'", ",", "statusCode", ":", "400", "}", ")", ")", "}", "// Authorization code is expired", "if", "(", "nowSeconds", "(", ")", ">", "ac", ".", "expires_at", ")", "{", "return", "next", "(", "new", "AuthorizationError", "(", "{", "error", ":", "'invalid_grant'", ",", "error_description", ":", "'Authorization code expired'", ",", "statusCode", ":", "400", "}", ")", ")", "}", "// Mismatching redirect uri", "if", "(", "ac", ".", "redirect_uri", "!==", "params", ".", "redirect_uri", ")", "{", "return", "next", "(", "new", "AuthorizationError", "(", "{", "error", ":", "'invalid_grant'", ",", "error_description", ":", "'Mismatching redirect uri'", ",", "statusCode", ":", "400", "}", ")", ")", "}", "// Mismatching client id", "if", "(", "ac", ".", "client_id", "!==", "req", ".", "client", ".", "_id", ")", "{", "return", "next", "(", "new", "AuthorizationError", "(", "{", "error", ":", "'invalid_grant'", ",", "error_description", ":", "'Mismatching client id'", ",", "statusCode", ":", "400", "}", ")", ")", "}", "// Mismatching user id", "// if (ac.user_id !== req.user._id) {", "// return next(new AuthorizationError({", "// error: 'invalid_grant',", "// error_description: 'Mismatching client id',", "// statusCode: 400", "// }))", "// }", "req", ".", "code", "=", "ac", "// Update the code to show that it's been used.", "AuthorizationCode", ".", "patch", "(", "ac", ".", "_id", ",", "{", "used", ":", "true", "}", ",", "function", "(", "err", ")", "{", "next", "(", "err", ")", "}", ")", "}", ")", "}", "else", "{", "next", "(", ")", "}", "}" ]
Verify authorization code
[ "Verify", "authorization", "code" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/oidc/verifyAuthorizationCode.js#L13-L84
13,973
anvilresearch/connect
oidc/parseAuthorizationHeader.js
parseAuthorizationHeader
function parseAuthorizationHeader (req, res, next) { // parse the header if it's present in the request if (req.headers && req.headers.authorization) { var components = req.headers.authorization.split(' ') var scheme = components[0] var credentials = components[1] // ensure the correct number of components if (components.length !== 2) { return next(new UnauthorizedError({ error: 'invalid_request', error_description: 'Invalid authorization header', statusCode: 400 })) } // ensure the scheme is valid if (!scheme.match(/Basic|Bearer|Digest/i)) { return next(new UnauthorizedError({ error: 'invalid_request', error_description: 'Invalid authorization scheme', statusCode: 400 })) } req.authorization = { scheme: scheme, credentials: credentials } // otherwise add an empty authorization object } else { req.authorization = {} } next() }
javascript
function parseAuthorizationHeader (req, res, next) { // parse the header if it's present in the request if (req.headers && req.headers.authorization) { var components = req.headers.authorization.split(' ') var scheme = components[0] var credentials = components[1] // ensure the correct number of components if (components.length !== 2) { return next(new UnauthorizedError({ error: 'invalid_request', error_description: 'Invalid authorization header', statusCode: 400 })) } // ensure the scheme is valid if (!scheme.match(/Basic|Bearer|Digest/i)) { return next(new UnauthorizedError({ error: 'invalid_request', error_description: 'Invalid authorization scheme', statusCode: 400 })) } req.authorization = { scheme: scheme, credentials: credentials } // otherwise add an empty authorization object } else { req.authorization = {} } next() }
[ "function", "parseAuthorizationHeader", "(", "req", ",", "res", ",", "next", ")", "{", "// parse the header if it's present in the request", "if", "(", "req", ".", "headers", "&&", "req", ".", "headers", ".", "authorization", ")", "{", "var", "components", "=", "req", ".", "headers", ".", "authorization", ".", "split", "(", "' '", ")", "var", "scheme", "=", "components", "[", "0", "]", "var", "credentials", "=", "components", "[", "1", "]", "// ensure the correct number of components", "if", "(", "components", ".", "length", "!==", "2", ")", "{", "return", "next", "(", "new", "UnauthorizedError", "(", "{", "error", ":", "'invalid_request'", ",", "error_description", ":", "'Invalid authorization header'", ",", "statusCode", ":", "400", "}", ")", ")", "}", "// ensure the scheme is valid", "if", "(", "!", "scheme", ".", "match", "(", "/", "Basic|Bearer|Digest", "/", "i", ")", ")", "{", "return", "next", "(", "new", "UnauthorizedError", "(", "{", "error", ":", "'invalid_request'", ",", "error_description", ":", "'Invalid authorization scheme'", ",", "statusCode", ":", "400", "}", ")", ")", "}", "req", ".", "authorization", "=", "{", "scheme", ":", "scheme", ",", "credentials", ":", "credentials", "}", "// otherwise add an empty authorization object", "}", "else", "{", "req", ".", "authorization", "=", "{", "}", "}", "next", "(", ")", "}" ]
Parse Authorization Header
[ "Parse", "Authorization", "Header" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/oidc/parseAuthorizationHeader.js#L11-L47
13,974
anvilresearch/connect
routes/signup.js
createUser
function createUser (req, res, next) { User.insert(req.body, { private: true }, function (err, user) { if (err) { res.render('signup', { params: qs.stringify(req.body), request: req.body, providers: settings.providers, error: err.message }) } else { authenticator.dispatch('password', req, res, next, function (err, user, info) { if (err) { return next(err) } if (!user) { } else { authenticator.login(req, user) req.sendVerificationEmail = req.provider.emailVerification.enable req.flash('isNewUser', true) next() } }) } }) }
javascript
function createUser (req, res, next) { User.insert(req.body, { private: true }, function (err, user) { if (err) { res.render('signup', { params: qs.stringify(req.body), request: req.body, providers: settings.providers, error: err.message }) } else { authenticator.dispatch('password', req, res, next, function (err, user, info) { if (err) { return next(err) } if (!user) { } else { authenticator.login(req, user) req.sendVerificationEmail = req.provider.emailVerification.enable req.flash('isNewUser', true) next() } }) } }) }
[ "function", "createUser", "(", "req", ",", "res", ",", "next", ")", "{", "User", ".", "insert", "(", "req", ".", "body", ",", "{", "private", ":", "true", "}", ",", "function", "(", "err", ",", "user", ")", "{", "if", "(", "err", ")", "{", "res", ".", "render", "(", "'signup'", ",", "{", "params", ":", "qs", ".", "stringify", "(", "req", ".", "body", ")", ",", "request", ":", "req", ".", "body", ",", "providers", ":", "settings", ".", "providers", ",", "error", ":", "err", ".", "message", "}", ")", "}", "else", "{", "authenticator", ".", "dispatch", "(", "'password'", ",", "req", ",", "res", ",", "next", ",", "function", "(", "err", ",", "user", ",", "info", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", "}", "if", "(", "!", "user", ")", "{", "}", "else", "{", "authenticator", ".", "login", "(", "req", ",", "user", ")", "req", ".", "sendVerificationEmail", "=", "req", ".", "provider", ".", "emailVerification", ".", "enable", "req", ".", "flash", "(", "'isNewUser'", ",", "true", ")", "next", "(", ")", "}", "}", ")", "}", "}", ")", "}" ]
Password signup handler
[ "Password", "signup", "handler" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/routes/signup.js#L41-L64
13,975
anvilresearch/connect
oidc/verifyClientToken.js
verifyClientToken
function verifyClientToken (req, res, next) { var header = req.headers['authorization'] // missing header if (!header) { return next(new UnauthorizedError({ realm: 'client', error: 'unauthorized_client', error_description: 'Missing authorization header', statusCode: 403 })) // header found } else { var jwt = header.replace('Bearer ', '') var token = ClientToken.decode(jwt, settings.keys.sig.pub) // failed to decode if (!token || token instanceof Error) { next(new UnauthorizedError({ realm: 'client', error: 'unauthorized_client', error_description: 'Invalid access token', statusCode: 403 })) // decoded successfully } else { // validate token req.token = token next() } } }
javascript
function verifyClientToken (req, res, next) { var header = req.headers['authorization'] // missing header if (!header) { return next(new UnauthorizedError({ realm: 'client', error: 'unauthorized_client', error_description: 'Missing authorization header', statusCode: 403 })) // header found } else { var jwt = header.replace('Bearer ', '') var token = ClientToken.decode(jwt, settings.keys.sig.pub) // failed to decode if (!token || token instanceof Error) { next(new UnauthorizedError({ realm: 'client', error: 'unauthorized_client', error_description: 'Invalid access token', statusCode: 403 })) // decoded successfully } else { // validate token req.token = token next() } } }
[ "function", "verifyClientToken", "(", "req", ",", "res", ",", "next", ")", "{", "var", "header", "=", "req", ".", "headers", "[", "'authorization'", "]", "// missing header", "if", "(", "!", "header", ")", "{", "return", "next", "(", "new", "UnauthorizedError", "(", "{", "realm", ":", "'client'", ",", "error", ":", "'unauthorized_client'", ",", "error_description", ":", "'Missing authorization header'", ",", "statusCode", ":", "403", "}", ")", ")", "// header found", "}", "else", "{", "var", "jwt", "=", "header", ".", "replace", "(", "'Bearer '", ",", "''", ")", "var", "token", "=", "ClientToken", ".", "decode", "(", "jwt", ",", "settings", ".", "keys", ".", "sig", ".", "pub", ")", "// failed to decode", "if", "(", "!", "token", "||", "token", "instanceof", "Error", ")", "{", "next", "(", "new", "UnauthorizedError", "(", "{", "realm", ":", "'client'", ",", "error", ":", "'unauthorized_client'", ",", "error_description", ":", "'Invalid access token'", ",", "statusCode", ":", "403", "}", ")", ")", "// decoded successfully", "}", "else", "{", "// validate token", "req", ".", "token", "=", "token", "next", "(", ")", "}", "}", "}" ]
Client Bearer Token Authentication Middleware
[ "Client", "Bearer", "Token", "Authentication", "Middleware" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/oidc/verifyClientToken.js#L13-L46
13,976
anvilresearch/connect
boot/mailer.js
render
function render (template, locals, callback) { var engineExt = engineName.charAt(0) === '.' ? engineName : ('.' + engineName) var tmplPath = path.join(templatesDir, template + engineExt) var origTmplPath = path.join(origTemplatesDir, template + engineExt) function renderToText (html) { var text = htmlToText.fromString(html, { wordwrap: 72 // A little less than 80 characters per line is the de-facto // standard for e-mails to allow for some room for quoting // and e-mail client UI elements (e.g. scrollbar) }) callback(null, html, text) } engine(tmplPath, locals) .then(renderToText) .catch(function () { engine(origTmplPath, locals) .then(renderToText) .catch(function (err) { callback(err) }) }) }
javascript
function render (template, locals, callback) { var engineExt = engineName.charAt(0) === '.' ? engineName : ('.' + engineName) var tmplPath = path.join(templatesDir, template + engineExt) var origTmplPath = path.join(origTemplatesDir, template + engineExt) function renderToText (html) { var text = htmlToText.fromString(html, { wordwrap: 72 // A little less than 80 characters per line is the de-facto // standard for e-mails to allow for some room for quoting // and e-mail client UI elements (e.g. scrollbar) }) callback(null, html, text) } engine(tmplPath, locals) .then(renderToText) .catch(function () { engine(origTmplPath, locals) .then(renderToText) .catch(function (err) { callback(err) }) }) }
[ "function", "render", "(", "template", ",", "locals", ",", "callback", ")", "{", "var", "engineExt", "=", "engineName", ".", "charAt", "(", "0", ")", "===", "'.'", "?", "engineName", ":", "(", "'.'", "+", "engineName", ")", "var", "tmplPath", "=", "path", ".", "join", "(", "templatesDir", ",", "template", "+", "engineExt", ")", "var", "origTmplPath", "=", "path", ".", "join", "(", "origTemplatesDir", ",", "template", "+", "engineExt", ")", "function", "renderToText", "(", "html", ")", "{", "var", "text", "=", "htmlToText", ".", "fromString", "(", "html", ",", "{", "wordwrap", ":", "72", "// A little less than 80 characters per line is the de-facto", "// standard for e-mails to allow for some room for quoting", "// and e-mail client UI elements (e.g. scrollbar)", "}", ")", "callback", "(", "null", ",", "html", ",", "text", ")", "}", "engine", "(", "tmplPath", ",", "locals", ")", ".", "then", "(", "renderToText", ")", ".", "catch", "(", "function", "(", ")", "{", "engine", "(", "origTmplPath", ",", "locals", ")", ".", "then", "(", "renderToText", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "callback", "(", "err", ")", "}", ")", "}", ")", "}" ]
Render e-mail templates to HTML and text
[ "Render", "e", "-", "mail", "templates", "to", "HTML", "and", "text" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/boot/mailer.js#L20-L45
13,977
anvilresearch/connect
boot/mailer.js
sendMail
function sendMail (template, locals, options, callback) { var self = this this.render(template, locals, function (err, html, text) { if (err) { return callback(err) } self.transport.sendMail({ from: options.from || defaultFrom, to: options.to, subject: options.subject, html: html, text: text }, callback) }) }
javascript
function sendMail (template, locals, options, callback) { var self = this this.render(template, locals, function (err, html, text) { if (err) { return callback(err) } self.transport.sendMail({ from: options.from || defaultFrom, to: options.to, subject: options.subject, html: html, text: text }, callback) }) }
[ "function", "sendMail", "(", "template", ",", "locals", ",", "options", ",", "callback", ")", "{", "var", "self", "=", "this", "this", ".", "render", "(", "template", ",", "locals", ",", "function", "(", "err", ",", "html", ",", "text", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", "}", "self", ".", "transport", ".", "sendMail", "(", "{", "from", ":", "options", ".", "from", "||", "defaultFrom", ",", "to", ":", "options", ".", "to", ",", "subject", ":", "options", ".", "subject", ",", "html", ":", "html", ",", "text", ":", "text", "}", ",", "callback", ")", "}", ")", "}" ]
Helper function to send e-mails using templates
[ "Helper", "function", "to", "send", "e", "-", "mails", "using", "templates" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/boot/mailer.js#L51-L64
13,978
anvilresearch/connect
oidc/setSessionAmr.js
setSessionAmr
function setSessionAmr (session, amr) { if (amr) { if (!Array.isArray(amr)) { session.amr = [amr] } else if (session.amr.indexOf(amr) === -1) { session.amr.push(amr) } } }
javascript
function setSessionAmr (session, amr) { if (amr) { if (!Array.isArray(amr)) { session.amr = [amr] } else if (session.amr.indexOf(amr) === -1) { session.amr.push(amr) } } }
[ "function", "setSessionAmr", "(", "session", ",", "amr", ")", "{", "if", "(", "amr", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "amr", ")", ")", "{", "session", ".", "amr", "=", "[", "amr", "]", "}", "else", "if", "(", "session", ".", "amr", ".", "indexOf", "(", "amr", ")", "===", "-", "1", ")", "{", "session", ".", "amr", ".", "push", "(", "amr", ")", "}", "}", "}" ]
Set Session `amr` claim The `amr` claim is an OIDC ID Token property used to indicate the type(s) of authentication for the current session. This value is set when users authenticate.
[ "Set", "Session", "amr", "claim" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/oidc/setSessionAmr.js#L10-L18
13,979
anvilresearch/connect
boot/setup.js
isOOB
function isOOB (cb) { User.listByRoles('authority', function (err, users) { if (err) { return cb(err) } // return true if there are no authority users return cb(null, !users || !users.length) }) }
javascript
function isOOB (cb) { User.listByRoles('authority', function (err, users) { if (err) { return cb(err) } // return true if there are no authority users return cb(null, !users || !users.length) }) }
[ "function", "isOOB", "(", "cb", ")", "{", "User", ".", "listByRoles", "(", "'authority'", ",", "function", "(", "err", ",", "users", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", "}", "// return true if there are no authority users", "return", "cb", "(", "null", ",", "!", "users", "||", "!", "users", ".", "length", ")", "}", ")", "}" ]
Check if server is in out-of-box mode
[ "Check", "if", "server", "is", "in", "out", "-", "of", "-", "box", "mode" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/boot/setup.js#L15-L21
13,980
anvilresearch/connect
boot/setup.js
readSetupToken
function readSetupToken (cb) { var token var write = false try { // try to read setup token from filesystem token = keygen.loadSetupToken() // if token is blank, try to generate a new token and save it if (!token.trim()) { write = true } } catch (err) { // if unable to read, try to generate a new token and save it write = true } if (write) { try { token = keygen.generateSetupToken() } catch (err) { // if we can't write the token to disk, something is very wrong return cb(err) } } // return the token cb(null, token) }
javascript
function readSetupToken (cb) { var token var write = false try { // try to read setup token from filesystem token = keygen.loadSetupToken() // if token is blank, try to generate a new token and save it if (!token.trim()) { write = true } } catch (err) { // if unable to read, try to generate a new token and save it write = true } if (write) { try { token = keygen.generateSetupToken() } catch (err) { // if we can't write the token to disk, something is very wrong return cb(err) } } // return the token cb(null, token) }
[ "function", "readSetupToken", "(", "cb", ")", "{", "var", "token", "var", "write", "=", "false", "try", "{", "// try to read setup token from filesystem", "token", "=", "keygen", ".", "loadSetupToken", "(", ")", "// if token is blank, try to generate a new token and save it", "if", "(", "!", "token", ".", "trim", "(", ")", ")", "{", "write", "=", "true", "}", "}", "catch", "(", "err", ")", "{", "// if unable to read, try to generate a new token and save it", "write", "=", "true", "}", "if", "(", "write", ")", "{", "try", "{", "token", "=", "keygen", ".", "generateSetupToken", "(", ")", "}", "catch", "(", "err", ")", "{", "// if we can't write the token to disk, something is very wrong", "return", "cb", "(", "err", ")", "}", "}", "// return the token", "cb", "(", "null", ",", "token", ")", "}" ]
Read setup token from filesystem or create if missing
[ "Read", "setup", "token", "from", "filesystem", "or", "create", "if", "missing" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/boot/setup.js#L29-L56
13,981
anvilresearch/connect
oidc/verifyClientIdentifiers.js
verifyClientIdentifiers
function verifyClientIdentifiers (req, res, next) { // mismatching client identifiers if (req.token.payload.sub !== req.params.clientId) { return next(new AuthorizationError({ error: 'unauthorized_client', error_description: 'Mismatching client id', statusCode: 403 })) // all's well } else { next() } }
javascript
function verifyClientIdentifiers (req, res, next) { // mismatching client identifiers if (req.token.payload.sub !== req.params.clientId) { return next(new AuthorizationError({ error: 'unauthorized_client', error_description: 'Mismatching client id', statusCode: 403 })) // all's well } else { next() } }
[ "function", "verifyClientIdentifiers", "(", "req", ",", "res", ",", "next", ")", "{", "// mismatching client identifiers", "if", "(", "req", ".", "token", ".", "payload", ".", "sub", "!==", "req", ".", "params", ".", "clientId", ")", "{", "return", "next", "(", "new", "AuthorizationError", "(", "{", "error", ":", "'unauthorized_client'", ",", "error_description", ":", "'Mismatching client id'", ",", "statusCode", ":", "403", "}", ")", ")", "// all's well", "}", "else", "{", "next", "(", ")", "}", "}" ]
Verify Client Params
[ "Verify", "Client", "Params" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/oidc/verifyClientIdentifiers.js#L11-L24
13,982
anvilresearch/connect
oidc/verifyRedirectURI.js
verifyRedirectURI
function verifyRedirectURI (req, res, next) { var params = req.connectParams Client.get(params.client_id, { private: true }, function (err, client) { if (err) { return next(err) } // The client must be registered. if (!client || client.redirect_uris.indexOf(params.redirect_uri) === -1) { delete req.connectParams.client_id delete req.connectParams.redirect_uri delete req.connectParams.response_type delete req.connectParams.scope return next() } // Make client available to downstream middleware. req.client = client next() }) }
javascript
function verifyRedirectURI (req, res, next) { var params = req.connectParams Client.get(params.client_id, { private: true }, function (err, client) { if (err) { return next(err) } // The client must be registered. if (!client || client.redirect_uris.indexOf(params.redirect_uri) === -1) { delete req.connectParams.client_id delete req.connectParams.redirect_uri delete req.connectParams.response_type delete req.connectParams.scope return next() } // Make client available to downstream middleware. req.client = client next() }) }
[ "function", "verifyRedirectURI", "(", "req", ",", "res", ",", "next", ")", "{", "var", "params", "=", "req", ".", "connectParams", "Client", ".", "get", "(", "params", ".", "client_id", ",", "{", "private", ":", "true", "}", ",", "function", "(", "err", ",", "client", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", "}", "// The client must be registered.", "if", "(", "!", "client", "||", "client", ".", "redirect_uris", ".", "indexOf", "(", "params", ".", "redirect_uri", ")", "===", "-", "1", ")", "{", "delete", "req", ".", "connectParams", ".", "client_id", "delete", "req", ".", "connectParams", ".", "redirect_uri", "delete", "req", ".", "connectParams", ".", "response_type", "delete", "req", ".", "connectParams", ".", "scope", "return", "next", "(", ")", "}", "// Make client available to downstream middleware.", "req", ".", "client", "=", "client", "next", "(", ")", "}", ")", "}" ]
Verify Redirect URI This route-specific middleware retrieves a registered client and adds it to the request object for use downstream. It verifies that the client is registered and that the redirect_uri parameter matches the configuration of the registered client. However, unlike the verifyClient middleware, this middleware will not cause any errors, but instead remove the invalid values off of the req.connectParams object.
[ "Verify", "Redirect", "URI" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/oidc/verifyRedirectURI.js#L20-L42
13,983
anvilresearch/connect
oidc/determineUserScope.js
determineUserScope
function determineUserScope (req, res, next) { var params = req.connectParams var scope = params.scope var subject = req.user Scope.determine(scope, subject, function (err, scope, scopes) { if (err) { return next(err) } req.scope = scope req.scopes = scopes next() }) }
javascript
function determineUserScope (req, res, next) { var params = req.connectParams var scope = params.scope var subject = req.user Scope.determine(scope, subject, function (err, scope, scopes) { if (err) { return next(err) } req.scope = scope req.scopes = scopes next() }) }
[ "function", "determineUserScope", "(", "req", ",", "res", ",", "next", ")", "{", "var", "params", "=", "req", ".", "connectParams", "var", "scope", "=", "params", ".", "scope", "var", "subject", "=", "req", ".", "user", "Scope", ".", "determine", "(", "scope", ",", "subject", ",", "function", "(", "err", ",", "scope", ",", "scopes", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", "}", "req", ".", "scope", "=", "scope", "req", ".", "scopes", "=", "scopes", "next", "(", ")", "}", ")", "}" ]
Determine user scope
[ "Determine", "user", "scope" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/oidc/determineUserScope.js#L11-L22
13,984
anvilresearch/connect
oidc/promptToAuthorize.js
promptToAuthorize
function promptToAuthorize (req, res, next) { var params = req.connectParams var client = req.client var user = req.user var scopes = req.scopes // The client is not trusted and the user has yet to decide on consent if (client.trusted !== true && typeof params.authorize === 'undefined') { // check for pre-existing consent AccessToken.exists(user._id, client._id, function (err, exists) { if (err) { return next(err) } // if there's an existin authorization, // reuse it and continue if (exists) { params.authorize = 'true' next() // otherwise, prompt for consent } else { // render the consent view if (req.path === '/authorize') { res.render('authorize', { request: params, client: client, user: user, scopes: scopes }) // redirect to the authorize endpoint } else { res.redirect('/authorize?' + qs.stringify(params)) } } }) // The client is trusted and consent is implied. } else if (client.trusted === true) { params.authorize = 'true' next() // The client is not trusted and consent is decided } else { next() } }
javascript
function promptToAuthorize (req, res, next) { var params = req.connectParams var client = req.client var user = req.user var scopes = req.scopes // The client is not trusted and the user has yet to decide on consent if (client.trusted !== true && typeof params.authorize === 'undefined') { // check for pre-existing consent AccessToken.exists(user._id, client._id, function (err, exists) { if (err) { return next(err) } // if there's an existin authorization, // reuse it and continue if (exists) { params.authorize = 'true' next() // otherwise, prompt for consent } else { // render the consent view if (req.path === '/authorize') { res.render('authorize', { request: params, client: client, user: user, scopes: scopes }) // redirect to the authorize endpoint } else { res.redirect('/authorize?' + qs.stringify(params)) } } }) // The client is trusted and consent is implied. } else if (client.trusted === true) { params.authorize = 'true' next() // The client is not trusted and consent is decided } else { next() } }
[ "function", "promptToAuthorize", "(", "req", ",", "res", ",", "next", ")", "{", "var", "params", "=", "req", ".", "connectParams", "var", "client", "=", "req", ".", "client", "var", "user", "=", "req", ".", "user", "var", "scopes", "=", "req", ".", "scopes", "// The client is not trusted and the user has yet to decide on consent", "if", "(", "client", ".", "trusted", "!==", "true", "&&", "typeof", "params", ".", "authorize", "===", "'undefined'", ")", "{", "// check for pre-existing consent", "AccessToken", ".", "exists", "(", "user", ".", "_id", ",", "client", ".", "_id", ",", "function", "(", "err", ",", "exists", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", "}", "// if there's an existin authorization,", "// reuse it and continue", "if", "(", "exists", ")", "{", "params", ".", "authorize", "=", "'true'", "next", "(", ")", "// otherwise, prompt for consent", "}", "else", "{", "// render the consent view", "if", "(", "req", ".", "path", "===", "'/authorize'", ")", "{", "res", ".", "render", "(", "'authorize'", ",", "{", "request", ":", "params", ",", "client", ":", "client", ",", "user", ":", "user", ",", "scopes", ":", "scopes", "}", ")", "// redirect to the authorize endpoint", "}", "else", "{", "res", ".", "redirect", "(", "'/authorize?'", "+", "qs", ".", "stringify", "(", "params", ")", ")", "}", "}", "}", ")", "// The client is trusted and consent is implied.", "}", "else", "if", "(", "client", ".", "trusted", "===", "true", ")", "{", "params", ".", "authorize", "=", "'true'", "next", "(", ")", "// The client is not trusted and consent is decided", "}", "else", "{", "next", "(", ")", "}", "}" ]
Prompt to authorize
[ "Prompt", "to", "authorize" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/oidc/promptToAuthorize.js#L12-L57
13,985
anvilresearch/connect
oidc/verifyClientRegistration.js
verifyClientRegistration
function verifyClientRegistration (req, res, next) { // check if we have a token and a token is required var registration = req.body var claims = req.claims var clientRegType = settings.client_registration var required = (registration.trusted || clientRegType !== 'dynamic') var trustedRegScope = settings.trusted_registration_scope var regScope = settings.registration_scope // can't continue because we don't have a token if (!(claims && claims.sub) && required) { return next(new UnauthorizedError({ realm: 'user', error: 'invalid_request', error_description: 'Missing access token', statusCode: 400 })) } // we have a token, so let's verify it if (claims && claims.sub) { // verify the trusted registration scope if (registration.trusted && !hasScope(claims, trustedRegScope)) { return next(new UnauthorizedError({ realm: 'user', error: 'insufficient_scope', error_description: 'User does not have permission', statusCode: 403 })) } // verify the registration scope if (!registration.trusted && clientRegType === 'scoped' && !hasScope(claims, regScope)) { return next(new UnauthorizedError({ realm: 'user', error: 'insufficient_scope', error_description: 'User does not have permission', statusCode: 403 })) } next() // authorization not required/provided } else { next() } }
javascript
function verifyClientRegistration (req, res, next) { // check if we have a token and a token is required var registration = req.body var claims = req.claims var clientRegType = settings.client_registration var required = (registration.trusted || clientRegType !== 'dynamic') var trustedRegScope = settings.trusted_registration_scope var regScope = settings.registration_scope // can't continue because we don't have a token if (!(claims && claims.sub) && required) { return next(new UnauthorizedError({ realm: 'user', error: 'invalid_request', error_description: 'Missing access token', statusCode: 400 })) } // we have a token, so let's verify it if (claims && claims.sub) { // verify the trusted registration scope if (registration.trusted && !hasScope(claims, trustedRegScope)) { return next(new UnauthorizedError({ realm: 'user', error: 'insufficient_scope', error_description: 'User does not have permission', statusCode: 403 })) } // verify the registration scope if (!registration.trusted && clientRegType === 'scoped' && !hasScope(claims, regScope)) { return next(new UnauthorizedError({ realm: 'user', error: 'insufficient_scope', error_description: 'User does not have permission', statusCode: 403 })) } next() // authorization not required/provided } else { next() } }
[ "function", "verifyClientRegistration", "(", "req", ",", "res", ",", "next", ")", "{", "// check if we have a token and a token is required", "var", "registration", "=", "req", ".", "body", "var", "claims", "=", "req", ".", "claims", "var", "clientRegType", "=", "settings", ".", "client_registration", "var", "required", "=", "(", "registration", ".", "trusted", "||", "clientRegType", "!==", "'dynamic'", ")", "var", "trustedRegScope", "=", "settings", ".", "trusted_registration_scope", "var", "regScope", "=", "settings", ".", "registration_scope", "// can't continue because we don't have a token", "if", "(", "!", "(", "claims", "&&", "claims", ".", "sub", ")", "&&", "required", ")", "{", "return", "next", "(", "new", "UnauthorizedError", "(", "{", "realm", ":", "'user'", ",", "error", ":", "'invalid_request'", ",", "error_description", ":", "'Missing access token'", ",", "statusCode", ":", "400", "}", ")", ")", "}", "// we have a token, so let's verify it", "if", "(", "claims", "&&", "claims", ".", "sub", ")", "{", "// verify the trusted registration scope", "if", "(", "registration", ".", "trusted", "&&", "!", "hasScope", "(", "claims", ",", "trustedRegScope", ")", ")", "{", "return", "next", "(", "new", "UnauthorizedError", "(", "{", "realm", ":", "'user'", ",", "error", ":", "'insufficient_scope'", ",", "error_description", ":", "'User does not have permission'", ",", "statusCode", ":", "403", "}", ")", ")", "}", "// verify the registration scope", "if", "(", "!", "registration", ".", "trusted", "&&", "clientRegType", "===", "'scoped'", "&&", "!", "hasScope", "(", "claims", ",", "regScope", ")", ")", "{", "return", "next", "(", "new", "UnauthorizedError", "(", "{", "realm", ":", "'user'", ",", "error", ":", "'insufficient_scope'", ",", "error_description", ":", "'User does not have permission'", ",", "statusCode", ":", "403", "}", ")", ")", "}", "next", "(", ")", "// authorization not required/provided", "}", "else", "{", "next", "(", ")", "}", "}" ]
Verify Client Registration NOTE: verifyAccessToken and its dependencies should be used upstream. This middleware assumes that if a token is present, it has already been verified. It will invoke the error handler if any of the following are true 1. a token is required, but not present 2. registration contains the "trusted" property 3. specific scope is required to register a client
[ "Verify", "Client", "Registration" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/oidc/verifyClientRegistration.js#L22-L70
13,986
anvilresearch/connect
oidc/validateTokenParams.js
validateTokenParams
function validateTokenParams (req, res, next) { var params = req.body // missing grant type if (!params.grant_type) { return next(new AuthorizationError({ error: 'invalid_request', error_description: 'Missing grant type', statusCode: 400 })) } // unsupported grant type if (grantTypes.indexOf(params.grant_type) === -1) { return next(new AuthorizationError({ error: 'unsupported_grant_type', error_description: 'Unsupported grant type', statusCode: 400 })) } // missing authorization code if (params.grant_type === 'authorization_code' && !params.code) { return next(new AuthorizationError({ error: 'invalid_request', error_description: 'Missing authorization code', statusCode: 400 })) } // missing redirect uri if (params.grant_type === 'authorization_code' && !params.redirect_uri) { return next(new AuthorizationError({ error: 'invalid_request', error_description: 'Missing redirect uri', statusCode: 400 })) } // missing refresh token if (params.grant_type === 'refresh_token' && !params.refresh_token) { return next(new AuthorizationError({ error: 'invalid_request', error_description: 'Missing refresh token', statusCode: 400 })) } next() }
javascript
function validateTokenParams (req, res, next) { var params = req.body // missing grant type if (!params.grant_type) { return next(new AuthorizationError({ error: 'invalid_request', error_description: 'Missing grant type', statusCode: 400 })) } // unsupported grant type if (grantTypes.indexOf(params.grant_type) === -1) { return next(new AuthorizationError({ error: 'unsupported_grant_type', error_description: 'Unsupported grant type', statusCode: 400 })) } // missing authorization code if (params.grant_type === 'authorization_code' && !params.code) { return next(new AuthorizationError({ error: 'invalid_request', error_description: 'Missing authorization code', statusCode: 400 })) } // missing redirect uri if (params.grant_type === 'authorization_code' && !params.redirect_uri) { return next(new AuthorizationError({ error: 'invalid_request', error_description: 'Missing redirect uri', statusCode: 400 })) } // missing refresh token if (params.grant_type === 'refresh_token' && !params.refresh_token) { return next(new AuthorizationError({ error: 'invalid_request', error_description: 'Missing refresh token', statusCode: 400 })) } next() }
[ "function", "validateTokenParams", "(", "req", ",", "res", ",", "next", ")", "{", "var", "params", "=", "req", ".", "body", "// missing grant type", "if", "(", "!", "params", ".", "grant_type", ")", "{", "return", "next", "(", "new", "AuthorizationError", "(", "{", "error", ":", "'invalid_request'", ",", "error_description", ":", "'Missing grant type'", ",", "statusCode", ":", "400", "}", ")", ")", "}", "// unsupported grant type", "if", "(", "grantTypes", ".", "indexOf", "(", "params", ".", "grant_type", ")", "===", "-", "1", ")", "{", "return", "next", "(", "new", "AuthorizationError", "(", "{", "error", ":", "'unsupported_grant_type'", ",", "error_description", ":", "'Unsupported grant type'", ",", "statusCode", ":", "400", "}", ")", ")", "}", "// missing authorization code", "if", "(", "params", ".", "grant_type", "===", "'authorization_code'", "&&", "!", "params", ".", "code", ")", "{", "return", "next", "(", "new", "AuthorizationError", "(", "{", "error", ":", "'invalid_request'", ",", "error_description", ":", "'Missing authorization code'", ",", "statusCode", ":", "400", "}", ")", ")", "}", "// missing redirect uri", "if", "(", "params", ".", "grant_type", "===", "'authorization_code'", "&&", "!", "params", ".", "redirect_uri", ")", "{", "return", "next", "(", "new", "AuthorizationError", "(", "{", "error", ":", "'invalid_request'", ",", "error_description", ":", "'Missing redirect uri'", ",", "statusCode", ":", "400", "}", ")", ")", "}", "// missing refresh token", "if", "(", "params", ".", "grant_type", "===", "'refresh_token'", "&&", "!", "params", ".", "refresh_token", ")", "{", "return", "next", "(", "new", "AuthorizationError", "(", "{", "error", ":", "'invalid_request'", ",", "error_description", ":", "'Missing refresh token'", ",", "statusCode", ":", "400", "}", ")", ")", "}", "next", "(", ")", "}" ]
Validate token parameters
[ "Validate", "token", "parameters" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/oidc/validateTokenParams.js#L19-L68
13,987
anvilresearch/connect
oidc/stashParams.js
stashParams
function stashParams (req, res, next) { var id = crypto.randomBytes(10).toString('hex') var key = 'authorization:' + id var ttl = 1200 // 20 minutes var params = JSON.stringify(req.connectParams) var multi = client.multi() req.session.state = id req.authorizationId = id multi.set(key, params) multi.expire(key, ttl) multi.exec(function (err) { return next(err) }) }
javascript
function stashParams (req, res, next) { var id = crypto.randomBytes(10).toString('hex') var key = 'authorization:' + id var ttl = 1200 // 20 minutes var params = JSON.stringify(req.connectParams) var multi = client.multi() req.session.state = id req.authorizationId = id multi.set(key, params) multi.expire(key, ttl) multi.exec(function (err) { return next(err) }) }
[ "function", "stashParams", "(", "req", ",", "res", ",", "next", ")", "{", "var", "id", "=", "crypto", ".", "randomBytes", "(", "10", ")", ".", "toString", "(", "'hex'", ")", "var", "key", "=", "'authorization:'", "+", "id", "var", "ttl", "=", "1200", "// 20 minutes", "var", "params", "=", "JSON", ".", "stringify", "(", "req", ".", "connectParams", ")", "var", "multi", "=", "client", ".", "multi", "(", ")", "req", ".", "session", ".", "state", "=", "id", "req", ".", "authorizationId", "=", "id", "multi", ".", "set", "(", "key", ",", "params", ")", "multi", ".", "expire", "(", "key", ",", "ttl", ")", "multi", ".", "exec", "(", "function", "(", "err", ")", "{", "return", "next", "(", "err", ")", "}", ")", "}" ]
Stash authorization params
[ "Stash", "authorization", "params" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/oidc/stashParams.js#L12-L27
13,988
anvilresearch/connect
oidc/getAuthorizedScopes.js
getAuthorizedScopes
function getAuthorizedScopes (req, res, next) { // Get the scopes authorized for the verified and decoded token var scopeNames = req.claims.scope && req.claims.scope.split(' ') Scope.get(scopeNames, function (err, scopes) { if (err) { return next(err) } req.scopes = scopes next() }) }
javascript
function getAuthorizedScopes (req, res, next) { // Get the scopes authorized for the verified and decoded token var scopeNames = req.claims.scope && req.claims.scope.split(' ') Scope.get(scopeNames, function (err, scopes) { if (err) { return next(err) } req.scopes = scopes next() }) }
[ "function", "getAuthorizedScopes", "(", "req", ",", "res", ",", "next", ")", "{", "// Get the scopes authorized for the verified and decoded token", "var", "scopeNames", "=", "req", ".", "claims", ".", "scope", "&&", "req", ".", "claims", ".", "scope", ".", "split", "(", "' '", ")", "Scope", ".", "get", "(", "scopeNames", ",", "function", "(", "err", ",", "scopes", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", "}", "req", ".", "scopes", "=", "scopes", "next", "(", ")", "}", ")", "}" ]
Get Authorized Scopes Rename this to disambiguate from determineUserScope
[ "Get", "Authorized", "Scopes", "Rename", "this", "to", "disambiguate", "from", "determineUserScope" ]
23bbde151e24df14c20d2e3a209fa46ac46fd751
https://github.com/anvilresearch/connect/blob/23bbde151e24df14c20d2e3a209fa46ac46fd751/oidc/getAuthorizedScopes.js#L12-L21
13,989
maxogden/websocket-stream
stream.js
writev
function writev (chunks, cb) { var buffers = new Array(chunks.length) for (var i = 0; i < chunks.length; i++) { if (typeof chunks[i].chunk === 'string') { buffers[i] = Buffer.from(chunks[i], 'utf8') } else { buffers[i] = chunks[i].chunk } } this._write(Buffer.concat(buffers), 'binary', cb) }
javascript
function writev (chunks, cb) { var buffers = new Array(chunks.length) for (var i = 0; i < chunks.length; i++) { if (typeof chunks[i].chunk === 'string') { buffers[i] = Buffer.from(chunks[i], 'utf8') } else { buffers[i] = chunks[i].chunk } } this._write(Buffer.concat(buffers), 'binary', cb) }
[ "function", "writev", "(", "chunks", ",", "cb", ")", "{", "var", "buffers", "=", "new", "Array", "(", "chunks", ".", "length", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "chunks", ".", "length", ";", "i", "++", ")", "{", "if", "(", "typeof", "chunks", "[", "i", "]", ".", "chunk", "===", "'string'", ")", "{", "buffers", "[", "i", "]", "=", "Buffer", ".", "from", "(", "chunks", "[", "i", "]", ",", "'utf8'", ")", "}", "else", "{", "buffers", "[", "i", "]", "=", "chunks", "[", "i", "]", ".", "chunk", "}", "}", "this", ".", "_write", "(", "Buffer", ".", "concat", "(", "buffers", ")", ",", "'binary'", ",", "cb", ")", "}" ]
this is to be enabled only if objectMode is false
[ "this", "is", "to", "be", "enabled", "only", "if", "objectMode", "is", "false" ]
55fe5450a54700ebf2be0eae6464981ef929a555
https://github.com/maxogden/websocket-stream/blob/55fe5450a54700ebf2be0eae6464981ef929a555/stream.js#L158-L169
13,990
dequelabs/pattern-library
lib/composites/menu/events/main.js
onTriggerClick
function onTriggerClick(e, noFocus) { toggleSubmenu(elements.trigger, (_, done) => { Classlist(elements.trigger).toggle(ACTIVE_CLASS); const wasActive = Classlist(elements.menu).contains(ACTIVE_CLASS); const first = wasActive ? ACTIVE_CLASS : 'dqpl-show'; const second = first === ACTIVE_CLASS ? 'dqpl-show' : ACTIVE_CLASS; Classlist(elements.menu).toggle(first); if (elements.scrim) { Classlist(elements.scrim).toggle('dqpl-scrim-show'); } setTimeout(() => { Classlist(elements.menu).toggle(second); if (elements.scrim) { Classlist(elements.scrim).toggle('dqpl-scrim-fade-in'); } setTimeout(() => done(noFocus)); }, 100); }); }
javascript
function onTriggerClick(e, noFocus) { toggleSubmenu(elements.trigger, (_, done) => { Classlist(elements.trigger).toggle(ACTIVE_CLASS); const wasActive = Classlist(elements.menu).contains(ACTIVE_CLASS); const first = wasActive ? ACTIVE_CLASS : 'dqpl-show'; const second = first === ACTIVE_CLASS ? 'dqpl-show' : ACTIVE_CLASS; Classlist(elements.menu).toggle(first); if (elements.scrim) { Classlist(elements.scrim).toggle('dqpl-scrim-show'); } setTimeout(() => { Classlist(elements.menu).toggle(second); if (elements.scrim) { Classlist(elements.scrim).toggle('dqpl-scrim-fade-in'); } setTimeout(() => done(noFocus)); }, 100); }); }
[ "function", "onTriggerClick", "(", "e", ",", "noFocus", ")", "{", "toggleSubmenu", "(", "elements", ".", "trigger", ",", "(", "_", ",", "done", ")", "=>", "{", "Classlist", "(", "elements", ".", "trigger", ")", ".", "toggle", "(", "ACTIVE_CLASS", ")", ";", "const", "wasActive", "=", "Classlist", "(", "elements", ".", "menu", ")", ".", "contains", "(", "ACTIVE_CLASS", ")", ";", "const", "first", "=", "wasActive", "?", "ACTIVE_CLASS", ":", "'dqpl-show'", ";", "const", "second", "=", "first", "===", "ACTIVE_CLASS", "?", "'dqpl-show'", ":", "ACTIVE_CLASS", ";", "Classlist", "(", "elements", ".", "menu", ")", ".", "toggle", "(", "first", ")", ";", "if", "(", "elements", ".", "scrim", ")", "{", "Classlist", "(", "elements", ".", "scrim", ")", ".", "toggle", "(", "'dqpl-scrim-show'", ")", ";", "}", "setTimeout", "(", "(", ")", "=>", "{", "Classlist", "(", "elements", ".", "menu", ")", ".", "toggle", "(", "second", ")", ";", "if", "(", "elements", ".", "scrim", ")", "{", "Classlist", "(", "elements", ".", "scrim", ")", ".", "toggle", "(", "'dqpl-scrim-fade-in'", ")", ";", "}", "setTimeout", "(", "(", ")", "=>", "done", "(", "noFocus", ")", ")", ";", "}", ",", "100", ")", ";", "}", ")", ";", "}" ]
Handles clicks on trigger - toggles classes - handles animation
[ "Handles", "clicks", "on", "trigger", "-", "toggles", "classes", "-", "handles", "animation" ]
d02a4979eafbc35e3ffdb1505dc25b38fab6861f
https://github.com/dequelabs/pattern-library/blob/d02a4979eafbc35e3ffdb1505dc25b38fab6861f/lib/composites/menu/events/main.js#L268-L287
13,991
dequelabs/pattern-library
lib/composites/menu/events/main.js
toggleSubmenu
function toggleSubmenu(trigger, toggleFn) { const droplet = document.getElementById(trigger.getAttribute('aria-controls')); if (!droplet) { return; } toggleFn(droplet, (noFocus, focusTarget) => { const prevExpanded = droplet.getAttribute('aria-expanded'); const wasCollapsed = !prevExpanded || prevExpanded === 'false'; droplet.setAttribute('aria-expanded', wasCollapsed ? 'true' : 'false'); if (focusTarget) { focusTarget.focus(); } else if (!noFocus) { let active = queryAll('.dqpl-menuitem-selected', droplet).filter(isVisible); active = active.length ? active : queryAll('[role="menuitem"][tabindex="0"]', droplet).filter(isVisible); let focusMe = wasCollapsed ? active[0] : closest(droplet, '[aria-controls][role="menuitem"]'); focusMe = focusMe || elements.trigger; if (focusMe) { focusMe.focus(); } } }); }
javascript
function toggleSubmenu(trigger, toggleFn) { const droplet = document.getElementById(trigger.getAttribute('aria-controls')); if (!droplet) { return; } toggleFn(droplet, (noFocus, focusTarget) => { const prevExpanded = droplet.getAttribute('aria-expanded'); const wasCollapsed = !prevExpanded || prevExpanded === 'false'; droplet.setAttribute('aria-expanded', wasCollapsed ? 'true' : 'false'); if (focusTarget) { focusTarget.focus(); } else if (!noFocus) { let active = queryAll('.dqpl-menuitem-selected', droplet).filter(isVisible); active = active.length ? active : queryAll('[role="menuitem"][tabindex="0"]', droplet).filter(isVisible); let focusMe = wasCollapsed ? active[0] : closest(droplet, '[aria-controls][role="menuitem"]'); focusMe = focusMe || elements.trigger; if (focusMe) { focusMe.focus(); } } }); }
[ "function", "toggleSubmenu", "(", "trigger", ",", "toggleFn", ")", "{", "const", "droplet", "=", "document", ".", "getElementById", "(", "trigger", ".", "getAttribute", "(", "'aria-controls'", ")", ")", ";", "if", "(", "!", "droplet", ")", "{", "return", ";", "}", "toggleFn", "(", "droplet", ",", "(", "noFocus", ",", "focusTarget", ")", "=>", "{", "const", "prevExpanded", "=", "droplet", ".", "getAttribute", "(", "'aria-expanded'", ")", ";", "const", "wasCollapsed", "=", "!", "prevExpanded", "||", "prevExpanded", "===", "'false'", ";", "droplet", ".", "setAttribute", "(", "'aria-expanded'", ",", "wasCollapsed", "?", "'true'", ":", "'false'", ")", ";", "if", "(", "focusTarget", ")", "{", "focusTarget", ".", "focus", "(", ")", ";", "}", "else", "if", "(", "!", "noFocus", ")", "{", "let", "active", "=", "queryAll", "(", "'.dqpl-menuitem-selected'", ",", "droplet", ")", ".", "filter", "(", "isVisible", ")", ";", "active", "=", "active", ".", "length", "?", "active", ":", "queryAll", "(", "'[role=\"menuitem\"][tabindex=\"0\"]'", ",", "droplet", ")", ".", "filter", "(", "isVisible", ")", ";", "let", "focusMe", "=", "wasCollapsed", "?", "active", "[", "0", "]", ":", "closest", "(", "droplet", ",", "'[aria-controls][role=\"menuitem\"]'", ")", ";", "focusMe", "=", "focusMe", "||", "elements", ".", "trigger", ";", "if", "(", "focusMe", ")", "{", "focusMe", ".", "focus", "(", ")", ";", "}", "}", "}", ")", ";", "}" ]
Toggles a menu or submenu
[ "Toggles", "a", "menu", "or", "submenu" ]
d02a4979eafbc35e3ffdb1505dc25b38fab6861f
https://github.com/dequelabs/pattern-library/blob/d02a4979eafbc35e3ffdb1505dc25b38fab6861f/lib/composites/menu/events/main.js#L293-L315
13,992
dequelabs/pattern-library
lib/commons/rndid/index.js
rndid
function rndid(len) { len = len || 8; const id = rndm(len); if (document.getElementById(id)) { return rndid(len); } return id; }
javascript
function rndid(len) { len = len || 8; const id = rndm(len); if (document.getElementById(id)) { return rndid(len); } return id; }
[ "function", "rndid", "(", "len", ")", "{", "len", "=", "len", "||", "8", ";", "const", "id", "=", "rndm", "(", "len", ")", ";", "if", "(", "document", ".", "getElementById", "(", "id", ")", ")", "{", "return", "rndid", "(", "len", ")", ";", "}", "return", "id", ";", "}" ]
Returns a unique dom element id
[ "Returns", "a", "unique", "dom", "element", "id" ]
d02a4979eafbc35e3ffdb1505dc25b38fab6861f
https://github.com/dequelabs/pattern-library/blob/d02a4979eafbc35e3ffdb1505dc25b38fab6861f/lib/commons/rndid/index.js#L8-L17
13,993
ilearnio/module-alias
index.js
init
function init (options) { if (typeof options === 'string') { options = { base: options } } options = options || {} // There is probably 99% chance that the project root directory in located // above the node_modules directory var base = nodePath.resolve( options.base || nodePath.join(__dirname, '../..') ) var packagePath = base.replace(/\/package\.json$/, '') + '/package.json' try { var npmPackage = require(packagePath) } catch (e) { // Do nothing } if (typeof npmPackage !== 'object') { throw new Error('Unable to read ' + packagePath) } // // Import aliases // var aliases = npmPackage._moduleAliases || {} for (var alias in aliases) { if (aliases[alias][0] !== '/') { aliases[alias] = nodePath.join(base, aliases[alias]) } } addAliases(aliases) // // Register custom module directories (like node_modules) // if (npmPackage._moduleDirectories instanceof Array) { npmPackage._moduleDirectories.forEach(function (dir) { if (dir === 'node_modules') return var modulePath = nodePath.join(base, dir) addPath(modulePath) }) } }
javascript
function init (options) { if (typeof options === 'string') { options = { base: options } } options = options || {} // There is probably 99% chance that the project root directory in located // above the node_modules directory var base = nodePath.resolve( options.base || nodePath.join(__dirname, '../..') ) var packagePath = base.replace(/\/package\.json$/, '') + '/package.json' try { var npmPackage = require(packagePath) } catch (e) { // Do nothing } if (typeof npmPackage !== 'object') { throw new Error('Unable to read ' + packagePath) } // // Import aliases // var aliases = npmPackage._moduleAliases || {} for (var alias in aliases) { if (aliases[alias][0] !== '/') { aliases[alias] = nodePath.join(base, aliases[alias]) } } addAliases(aliases) // // Register custom module directories (like node_modules) // if (npmPackage._moduleDirectories instanceof Array) { npmPackage._moduleDirectories.forEach(function (dir) { if (dir === 'node_modules') return var modulePath = nodePath.join(base, dir) addPath(modulePath) }) } }
[ "function", "init", "(", "options", ")", "{", "if", "(", "typeof", "options", "===", "'string'", ")", "{", "options", "=", "{", "base", ":", "options", "}", "}", "options", "=", "options", "||", "{", "}", "// There is probably 99% chance that the project root directory in located", "// above the node_modules directory", "var", "base", "=", "nodePath", ".", "resolve", "(", "options", ".", "base", "||", "nodePath", ".", "join", "(", "__dirname", ",", "'../..'", ")", ")", "var", "packagePath", "=", "base", ".", "replace", "(", "/", "\\/package\\.json$", "/", ",", "''", ")", "+", "'/package.json'", "try", "{", "var", "npmPackage", "=", "require", "(", "packagePath", ")", "}", "catch", "(", "e", ")", "{", "// Do nothing", "}", "if", "(", "typeof", "npmPackage", "!==", "'object'", ")", "{", "throw", "new", "Error", "(", "'Unable to read '", "+", "packagePath", ")", "}", "//", "// Import aliases", "//", "var", "aliases", "=", "npmPackage", ".", "_moduleAliases", "||", "{", "}", "for", "(", "var", "alias", "in", "aliases", ")", "{", "if", "(", "aliases", "[", "alias", "]", "[", "0", "]", "!==", "'/'", ")", "{", "aliases", "[", "alias", "]", "=", "nodePath", ".", "join", "(", "base", ",", "aliases", "[", "alias", "]", ")", "}", "}", "addAliases", "(", "aliases", ")", "//", "// Register custom module directories (like node_modules)", "//", "if", "(", "npmPackage", ".", "_moduleDirectories", "instanceof", "Array", ")", "{", "npmPackage", ".", "_moduleDirectories", ".", "forEach", "(", "function", "(", "dir", ")", "{", "if", "(", "dir", "===", "'node_modules'", ")", "return", "var", "modulePath", "=", "nodePath", ".", "join", "(", "base", ",", "dir", ")", "addPath", "(", "modulePath", ")", "}", ")", "}", "}" ]
Import aliases from package.json @param {object} options
[ "Import", "aliases", "from", "package", ".", "json" ]
a2db1e6e3785adea0c0f9a837eec518ddb49b360
https://github.com/ilearnio/module-alias/blob/a2db1e6e3785adea0c0f9a837eec518ddb49b360/index.js#L134-L184
13,994
MariaDB/mariadb-connector-nodejs
benchmarks/common_benchmarks.js
function() { console.log('start : init test : ' + bench.initFcts.length); for (let i = 0; i < bench.initFcts.length; i++) { console.log( 'initializing test data ' + (i + 1) + '/' + bench.initFcts.length ); if (bench.initFcts[i]) { bench.initFcts[i].call(this, bench.CONN.MARIADB.drv); } } this.currentNb = 0; console.log('initializing test data done'); }
javascript
function() { console.log('start : init test : ' + bench.initFcts.length); for (let i = 0; i < bench.initFcts.length; i++) { console.log( 'initializing test data ' + (i + 1) + '/' + bench.initFcts.length ); if (bench.initFcts[i]) { bench.initFcts[i].call(this, bench.CONN.MARIADB.drv); } } this.currentNb = 0; console.log('initializing test data done'); }
[ "function", "(", ")", "{", "console", ".", "log", "(", "'start : init test : '", "+", "bench", ".", "initFcts", ".", "length", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "bench", ".", "initFcts", ".", "length", ";", "i", "++", ")", "{", "console", ".", "log", "(", "'initializing test data '", "+", "(", "i", "+", "1", ")", "+", "'/'", "+", "bench", ".", "initFcts", ".", "length", ")", ";", "if", "(", "bench", ".", "initFcts", "[", "i", "]", ")", "{", "bench", ".", "initFcts", "[", "i", "]", ".", "call", "(", "this", ",", "bench", ".", "CONN", ".", "MARIADB", ".", "drv", ")", ";", "}", "}", "this", ".", "currentNb", "=", "0", ";", "console", ".", "log", "(", "'initializing test data done'", ")", ";", "}" ]
called when the suite starts running
[ "called", "when", "the", "suite", "starts", "running" ]
a596445fcfb5c39a6861b65cff3b6cd83a84a359
https://github.com/MariaDB/mariadb-connector-nodejs/blob/a596445fcfb5c39a6861b65cff3b6cd83a84a359/benchmarks/common_benchmarks.js#L201-L213
13,995
MariaDB/mariadb-connector-nodejs
benchmarks/common_benchmarks.js
function(event) { this.currentNb++; if (this.currentNb < this.length) pingAll(connList); //to avoid mysql2 taking all the server memory if (promiseMysql2 && promiseMysql2.clearParserCache) promiseMysql2.clearParserCache(); if (mysql2 && mysql2.clearParserCache) mysql2.clearParserCache(); console.log(event.target.toString()); const drvType = event.target.options.drvType; const benchTitle = event.target.options.benchTitle + ' ( sql: ' + event.target.options.displaySql + ' )'; const iteration = 1 / event.target.times.period; const variation = event.target.stats.rme; if (!bench.reportData[benchTitle]) { bench.reportData[benchTitle] = []; } if (drvType !== 'warmup') { bench.reportData[benchTitle].push({ drvType: drvType, iteration: iteration, variation: variation }); } }
javascript
function(event) { this.currentNb++; if (this.currentNb < this.length) pingAll(connList); //to avoid mysql2 taking all the server memory if (promiseMysql2 && promiseMysql2.clearParserCache) promiseMysql2.clearParserCache(); if (mysql2 && mysql2.clearParserCache) mysql2.clearParserCache(); console.log(event.target.toString()); const drvType = event.target.options.drvType; const benchTitle = event.target.options.benchTitle + ' ( sql: ' + event.target.options.displaySql + ' )'; const iteration = 1 / event.target.times.period; const variation = event.target.stats.rme; if (!bench.reportData[benchTitle]) { bench.reportData[benchTitle] = []; } if (drvType !== 'warmup') { bench.reportData[benchTitle].push({ drvType: drvType, iteration: iteration, variation: variation }); } }
[ "function", "(", "event", ")", "{", "this", ".", "currentNb", "++", ";", "if", "(", "this", ".", "currentNb", "<", "this", ".", "length", ")", "pingAll", "(", "connList", ")", ";", "//to avoid mysql2 taking all the server memory", "if", "(", "promiseMysql2", "&&", "promiseMysql2", ".", "clearParserCache", ")", "promiseMysql2", ".", "clearParserCache", "(", ")", ";", "if", "(", "mysql2", "&&", "mysql2", ".", "clearParserCache", ")", "mysql2", ".", "clearParserCache", "(", ")", ";", "console", ".", "log", "(", "event", ".", "target", ".", "toString", "(", ")", ")", ";", "const", "drvType", "=", "event", ".", "target", ".", "options", ".", "drvType", ";", "const", "benchTitle", "=", "event", ".", "target", ".", "options", ".", "benchTitle", "+", "' ( sql: '", "+", "event", ".", "target", ".", "options", ".", "displaySql", "+", "' )'", ";", "const", "iteration", "=", "1", "/", "event", ".", "target", ".", "times", ".", "period", ";", "const", "variation", "=", "event", ".", "target", ".", "stats", ".", "rme", ";", "if", "(", "!", "bench", ".", "reportData", "[", "benchTitle", "]", ")", "{", "bench", ".", "reportData", "[", "benchTitle", "]", "=", "[", "]", ";", "}", "if", "(", "drvType", "!==", "'warmup'", ")", "{", "bench", ".", "reportData", "[", "benchTitle", "]", ".", "push", "(", "{", "drvType", ":", "drvType", ",", "iteration", ":", "iteration", ",", "variation", ":", "variation", "}", ")", ";", "}", "}" ]
called between running benchmarks
[ "called", "between", "running", "benchmarks" ]
a596445fcfb5c39a6861b65cff3b6cd83a84a359
https://github.com/MariaDB/mariadb-connector-nodejs/blob/a596445fcfb5c39a6861b65cff3b6cd83a84a359/benchmarks/common_benchmarks.js#L216-L243
13,996
MariaDB/mariadb-connector-nodejs
lib/pool-base.js
function(pool, iteration, timeoutEnd) { return new Promise(function(resolve, reject) { const creationTryout = function(resolve, reject) { if (closed) { reject( Errors.createError( 'Cannot create new connection to pool, pool closed', true, null, '08S01', Errors.ER_ADD_CONNECTION_CLOSED_POOL, null ) ); return; } iteration++; createConnectionPool(pool) .then(conn => { resolve(conn); }) .catch(err => { //if timeout is reached or authentication fail return error if ( closed || (err.errno && (err.errno === 1524 || err.errno === 1045 || err.errno === 1698)) || timeoutEnd < Date.now() ) { reject(err); return; } setTimeout(creationTryout.bind(null, resolve, reject), 500); }); }; //initial without timeout creationTryout(resolve, reject); }); }
javascript
function(pool, iteration, timeoutEnd) { return new Promise(function(resolve, reject) { const creationTryout = function(resolve, reject) { if (closed) { reject( Errors.createError( 'Cannot create new connection to pool, pool closed', true, null, '08S01', Errors.ER_ADD_CONNECTION_CLOSED_POOL, null ) ); return; } iteration++; createConnectionPool(pool) .then(conn => { resolve(conn); }) .catch(err => { //if timeout is reached or authentication fail return error if ( closed || (err.errno && (err.errno === 1524 || err.errno === 1045 || err.errno === 1698)) || timeoutEnd < Date.now() ) { reject(err); return; } setTimeout(creationTryout.bind(null, resolve, reject), 500); }); }; //initial without timeout creationTryout(resolve, reject); }); }
[ "function", "(", "pool", ",", "iteration", ",", "timeoutEnd", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "const", "creationTryout", "=", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "closed", ")", "{", "reject", "(", "Errors", ".", "createError", "(", "'Cannot create new connection to pool, pool closed'", ",", "true", ",", "null", ",", "'08S01'", ",", "Errors", ".", "ER_ADD_CONNECTION_CLOSED_POOL", ",", "null", ")", ")", ";", "return", ";", "}", "iteration", "++", ";", "createConnectionPool", "(", "pool", ")", ".", "then", "(", "conn", "=>", "{", "resolve", "(", "conn", ")", ";", "}", ")", ".", "catch", "(", "err", "=>", "{", "//if timeout is reached or authentication fail return error", "if", "(", "closed", "||", "(", "err", ".", "errno", "&&", "(", "err", ".", "errno", "===", "1524", "||", "err", ".", "errno", "===", "1045", "||", "err", ".", "errno", "===", "1698", ")", ")", "||", "timeoutEnd", "<", "Date", ".", "now", "(", ")", ")", "{", "reject", "(", "err", ")", ";", "return", ";", "}", "setTimeout", "(", "creationTryout", ".", "bind", "(", "null", ",", "resolve", ",", "reject", ")", ",", "500", ")", ";", "}", ")", ";", "}", ";", "//initial without timeout", "creationTryout", "(", "resolve", ",", "reject", ")", ";", "}", ")", ";", "}" ]
Loop for connection creation. This permits to wait before next try after a connection fail. @param pool current pool @param iteration current iteration @param timeoutEnd ending timeout @returns {Promise<any>} Connection if found, error if not
[ "Loop", "for", "connection", "creation", ".", "This", "permits", "to", "wait", "before", "next", "try", "after", "a", "connection", "fail", "." ]
a596445fcfb5c39a6861b65cff3b6cd83a84a359
https://github.com/MariaDB/mariadb-connector-nodejs/blob/a596445fcfb5c39a6861b65cff3b6cd83a84a359/lib/pool-base.js#L305-L346
13,997
MariaDB/mariadb-connector-nodejs
lib/pool-base.js
function(pool) { if ( !connectionInCreation && pool.idleConnections() < opts.minimumIdle && pool.totalConnections() < opts.connectionLimit && !closed ) { connectionInCreation = true; process.nextTick(() => { const timeoutEnd = Date.now() + opts.initializationTimeout; if (!closed) { connectionCreationLoop(pool, 0, timeoutEnd) .then(conn => { if (closed) { return conn.forceEnd().catch(err => {}); } addPoolConnection(pool, conn); }) .catch(err => { if (pool.totalConnections() === 0) { const task = taskQueue.shift(); if (task) { firstTaskTimeout = clearTimeout(firstTaskTimeout); process.nextTick(task.reject, err); resetTimeoutToNextTask(); } } else if (!closed) { console.error( `pool fail to create connection (${err.message})` ); } //delay next try setTimeout(() => { connectionInCreation = false; if (taskQueue.size() > 0) { ensurePoolSize(pool); } }, 500); }); } }); } }
javascript
function(pool) { if ( !connectionInCreation && pool.idleConnections() < opts.minimumIdle && pool.totalConnections() < opts.connectionLimit && !closed ) { connectionInCreation = true; process.nextTick(() => { const timeoutEnd = Date.now() + opts.initializationTimeout; if (!closed) { connectionCreationLoop(pool, 0, timeoutEnd) .then(conn => { if (closed) { return conn.forceEnd().catch(err => {}); } addPoolConnection(pool, conn); }) .catch(err => { if (pool.totalConnections() === 0) { const task = taskQueue.shift(); if (task) { firstTaskTimeout = clearTimeout(firstTaskTimeout); process.nextTick(task.reject, err); resetTimeoutToNextTask(); } } else if (!closed) { console.error( `pool fail to create connection (${err.message})` ); } //delay next try setTimeout(() => { connectionInCreation = false; if (taskQueue.size() > 0) { ensurePoolSize(pool); } }, 500); }); } }); } }
[ "function", "(", "pool", ")", "{", "if", "(", "!", "connectionInCreation", "&&", "pool", ".", "idleConnections", "(", ")", "<", "opts", ".", "minimumIdle", "&&", "pool", ".", "totalConnections", "(", ")", "<", "opts", ".", "connectionLimit", "&&", "!", "closed", ")", "{", "connectionInCreation", "=", "true", ";", "process", ".", "nextTick", "(", "(", ")", "=>", "{", "const", "timeoutEnd", "=", "Date", ".", "now", "(", ")", "+", "opts", ".", "initializationTimeout", ";", "if", "(", "!", "closed", ")", "{", "connectionCreationLoop", "(", "pool", ",", "0", ",", "timeoutEnd", ")", ".", "then", "(", "conn", "=>", "{", "if", "(", "closed", ")", "{", "return", "conn", ".", "forceEnd", "(", ")", ".", "catch", "(", "err", "=>", "{", "}", ")", ";", "}", "addPoolConnection", "(", "pool", ",", "conn", ")", ";", "}", ")", ".", "catch", "(", "err", "=>", "{", "if", "(", "pool", ".", "totalConnections", "(", ")", "===", "0", ")", "{", "const", "task", "=", "taskQueue", ".", "shift", "(", ")", ";", "if", "(", "task", ")", "{", "firstTaskTimeout", "=", "clearTimeout", "(", "firstTaskTimeout", ")", ";", "process", ".", "nextTick", "(", "task", ".", "reject", ",", "err", ")", ";", "resetTimeoutToNextTask", "(", ")", ";", "}", "}", "else", "if", "(", "!", "closed", ")", "{", "console", ".", "error", "(", "`", "${", "err", ".", "message", "}", "`", ")", ";", "}", "//delay next try", "setTimeout", "(", "(", ")", "=>", "{", "connectionInCreation", "=", "false", ";", "if", "(", "taskQueue", ".", "size", "(", ")", ">", "0", ")", "{", "ensurePoolSize", "(", "pool", ")", ";", "}", "}", ",", "500", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}", "}" ]
Grow pool connections until reaching connection limit.
[ "Grow", "pool", "connections", "until", "reaching", "connection", "limit", "." ]
a596445fcfb5c39a6861b65cff3b6cd83a84a359
https://github.com/MariaDB/mariadb-connector-nodejs/blob/a596445fcfb5c39a6861b65cff3b6cd83a84a359/lib/pool-base.js#L404-L447
13,998
MariaDB/mariadb-connector-nodejs
lib/pool-base.js
function(pool) { let toRemove = Math.max(1, pool.idleConnections() - opts.minimumIdle); while (toRemove > 0) { const conn = idleConnections.peek(); --toRemove; if (conn && conn.lastUse + opts.idleTimeout * 1000 < Date.now()) { idleConnections.shift(); conn.forceEnd().catch(err => {}); conn.releaseWithoutError(); continue; } break; } ensurePoolSize(pool); }
javascript
function(pool) { let toRemove = Math.max(1, pool.idleConnections() - opts.minimumIdle); while (toRemove > 0) { const conn = idleConnections.peek(); --toRemove; if (conn && conn.lastUse + opts.idleTimeout * 1000 < Date.now()) { idleConnections.shift(); conn.forceEnd().catch(err => {}); conn.releaseWithoutError(); continue; } break; } ensurePoolSize(pool); }
[ "function", "(", "pool", ")", "{", "let", "toRemove", "=", "Math", ".", "max", "(", "1", ",", "pool", ".", "idleConnections", "(", ")", "-", "opts", ".", "minimumIdle", ")", ";", "while", "(", "toRemove", ">", "0", ")", "{", "const", "conn", "=", "idleConnections", ".", "peek", "(", ")", ";", "--", "toRemove", ";", "if", "(", "conn", "&&", "conn", ".", "lastUse", "+", "opts", ".", "idleTimeout", "*", "1000", "<", "Date", ".", "now", "(", ")", ")", "{", "idleConnections", ".", "shift", "(", ")", ";", "conn", ".", "forceEnd", "(", ")", ".", "catch", "(", "err", "=>", "{", "}", ")", ";", "conn", ".", "releaseWithoutError", "(", ")", ";", "continue", ";", "}", "break", ";", "}", "ensurePoolSize", "(", "pool", ")", ";", "}" ]
Permit to remove idle connection if unused for some time. @param pool current pool
[ "Permit", "to", "remove", "idle", "connection", "if", "unused", "for", "some", "time", "." ]
a596445fcfb5c39a6861b65cff3b6cd83a84a359
https://github.com/MariaDB/mariadb-connector-nodejs/blob/a596445fcfb5c39a6861b65cff3b6cd83a84a359/lib/pool-base.js#L471-L485
13,999
MariaDB/mariadb-connector-nodejs
lib/pool-base.js
function() { firstTaskTimeout = clearTimeout(firstTaskTimeout); const task = taskQueue.shift(); if (task) { const conn = idleConnections.shift(); if (conn) { activeConnections[conn.threadId] = conn; resetTimeoutToNextTask(); processTask(conn, task.sql, task.values, task.isBatch) .then(task.resolve) .catch(task.reject); } else { taskQueue.unshift(task); } } }
javascript
function() { firstTaskTimeout = clearTimeout(firstTaskTimeout); const task = taskQueue.shift(); if (task) { const conn = idleConnections.shift(); if (conn) { activeConnections[conn.threadId] = conn; resetTimeoutToNextTask(); processTask(conn, task.sql, task.values, task.isBatch) .then(task.resolve) .catch(task.reject); } else { taskQueue.unshift(task); } } }
[ "function", "(", ")", "{", "firstTaskTimeout", "=", "clearTimeout", "(", "firstTaskTimeout", ")", ";", "const", "task", "=", "taskQueue", ".", "shift", "(", ")", ";", "if", "(", "task", ")", "{", "const", "conn", "=", "idleConnections", ".", "shift", "(", ")", ";", "if", "(", "conn", ")", "{", "activeConnections", "[", "conn", ".", "threadId", "]", "=", "conn", ";", "resetTimeoutToNextTask", "(", ")", ";", "processTask", "(", "conn", ",", "task", ".", "sql", ",", "task", ".", "values", ",", "task", ".", "isBatch", ")", ".", "then", "(", "task", ".", "resolve", ")", ".", "catch", "(", "task", ".", "reject", ")", ";", "}", "else", "{", "taskQueue", ".", "unshift", "(", "task", ")", ";", "}", "}", "}" ]
Launch next waiting task request if available connections.
[ "Launch", "next", "waiting", "task", "request", "if", "available", "connections", "." ]
a596445fcfb5c39a6861b65cff3b6cd83a84a359
https://github.com/MariaDB/mariadb-connector-nodejs/blob/a596445fcfb5c39a6861b65cff3b6cd83a84a359/lib/pool-base.js#L496-L512