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
9,800
roman01la/html-to-react-components
lib/html2jsx.js
function (node) { var parentTag = node.parentNode && jsxTagName(node.parentNode.tagName); if (parentTag === 'textarea' || parentTag === 'style') { // Ignore text content of textareas and styles, as it will have already been moved // to a "defaultValue" attribute and "dangerouslySetInnerHTML" attribute respectively. return; } var text = escapeSpecialChars(node.textContent); if (this._inPreTag) { // If this text is contained within a <pre>, we need to ensure the JSX // whitespace coalescing rules don't eat the whitespace. This means // wrapping newlines and sequences of two or more spaces in variables. text = text .replace(/\r/g, '') .replace(/( {2,}|\n|\t|\{|\})/g, function (whitespace) { return '{' + JSON.stringify(whitespace) + '}'; }); } else { // Handle any curly braces. text = text .replace(/(\{|\})/g, function (brace) { return '{\'' + brace + '\'}'; }); // If there's a newline in the text, adjust the indent level if (text.indexOf('\n') > -1) { text = text.replace(/\n\s*/g, this._getIndentedNewline()); } } this.output += text; }
javascript
function (node) { var parentTag = node.parentNode && jsxTagName(node.parentNode.tagName); if (parentTag === 'textarea' || parentTag === 'style') { // Ignore text content of textareas and styles, as it will have already been moved // to a "defaultValue" attribute and "dangerouslySetInnerHTML" attribute respectively. return; } var text = escapeSpecialChars(node.textContent); if (this._inPreTag) { // If this text is contained within a <pre>, we need to ensure the JSX // whitespace coalescing rules don't eat the whitespace. This means // wrapping newlines and sequences of two or more spaces in variables. text = text .replace(/\r/g, '') .replace(/( {2,}|\n|\t|\{|\})/g, function (whitespace) { return '{' + JSON.stringify(whitespace) + '}'; }); } else { // Handle any curly braces. text = text .replace(/(\{|\})/g, function (brace) { return '{\'' + brace + '\'}'; }); // If there's a newline in the text, adjust the indent level if (text.indexOf('\n') > -1) { text = text.replace(/\n\s*/g, this._getIndentedNewline()); } } this.output += text; }
[ "function", "(", "node", ")", "{", "var", "parentTag", "=", "node", ".", "parentNode", "&&", "jsxTagName", "(", "node", ".", "parentNode", ".", "tagName", ")", ";", "if", "(", "parentTag", "===", "'textarea'", "||", "parentTag", "===", "'style'", ")", "{", "// Ignore text content of textareas and styles, as it will have already been moved", "// to a \"defaultValue\" attribute and \"dangerouslySetInnerHTML\" attribute respectively.", "return", ";", "}", "var", "text", "=", "escapeSpecialChars", "(", "node", ".", "textContent", ")", ";", "if", "(", "this", ".", "_inPreTag", ")", "{", "// If this text is contained within a <pre>, we need to ensure the JSX", "// whitespace coalescing rules don't eat the whitespace. This means", "// wrapping newlines and sequences of two or more spaces in variables.", "text", "=", "text", ".", "replace", "(", "/", "\\r", "/", "g", ",", "''", ")", ".", "replace", "(", "/", "( {2,}|\\n|\\t|\\{|\\})", "/", "g", ",", "function", "(", "whitespace", ")", "{", "return", "'{'", "+", "JSON", ".", "stringify", "(", "whitespace", ")", "+", "'}'", ";", "}", ")", ";", "}", "else", "{", "// Handle any curly braces.", "text", "=", "text", ".", "replace", "(", "/", "(\\{|\\})", "/", "g", ",", "function", "(", "brace", ")", "{", "return", "'{\\''", "+", "brace", "+", "'\\'}'", ";", "}", ")", ";", "// If there's a newline in the text, adjust the indent level", "if", "(", "text", ".", "indexOf", "(", "'\\n'", ")", ">", "-", "1", ")", "{", "text", "=", "text", ".", "replace", "(", "/", "\\n\\s*", "/", "g", ",", "this", ".", "_getIndentedNewline", "(", ")", ")", ";", "}", "}", "this", ".", "output", "+=", "text", ";", "}" ]
Handles processing of the specified text node @param {TextNode} node
[ "Handles", "processing", "of", "the", "specified", "text", "node" ]
74b76fafbd0728f77c2bbe32a0b26a94e604442b
https://github.com/roman01la/html-to-react-components/blob/74b76fafbd0728f77c2bbe32a0b26a94e604442b/lib/html2jsx.js#L563-L594
9,801
roman01la/html-to-react-components
lib/html2jsx.js
function (node, attribute) { switch (attribute.name) { case 'style': return this._getStyleAttribute(attribute.value); default: var tagName = jsxTagName(node.tagName); var name = (ELEMENT_ATTRIBUTE_MAPPING[tagName] && ELEMENT_ATTRIBUTE_MAPPING[tagName][attribute.name]) || ATTRIBUTE_MAPPING[attribute.name] || attribute.name; var result = name; // Numeric values should be output as {123} not "123" if (isNumeric(attribute.value)) { result += '={' + attribute.value + '}'; } else if (attribute.value.length > 0) { result += '="' + attribute.value.replace(/"/gm, '&quot;') + '"'; } return result; } }
javascript
function (node, attribute) { switch (attribute.name) { case 'style': return this._getStyleAttribute(attribute.value); default: var tagName = jsxTagName(node.tagName); var name = (ELEMENT_ATTRIBUTE_MAPPING[tagName] && ELEMENT_ATTRIBUTE_MAPPING[tagName][attribute.name]) || ATTRIBUTE_MAPPING[attribute.name] || attribute.name; var result = name; // Numeric values should be output as {123} not "123" if (isNumeric(attribute.value)) { result += '={' + attribute.value + '}'; } else if (attribute.value.length > 0) { result += '="' + attribute.value.replace(/"/gm, '&quot;') + '"'; } return result; } }
[ "function", "(", "node", ",", "attribute", ")", "{", "switch", "(", "attribute", ".", "name", ")", "{", "case", "'style'", ":", "return", "this", ".", "_getStyleAttribute", "(", "attribute", ".", "value", ")", ";", "default", ":", "var", "tagName", "=", "jsxTagName", "(", "node", ".", "tagName", ")", ";", "var", "name", "=", "(", "ELEMENT_ATTRIBUTE_MAPPING", "[", "tagName", "]", "&&", "ELEMENT_ATTRIBUTE_MAPPING", "[", "tagName", "]", "[", "attribute", ".", "name", "]", ")", "||", "ATTRIBUTE_MAPPING", "[", "attribute", ".", "name", "]", "||", "attribute", ".", "name", ";", "var", "result", "=", "name", ";", "// Numeric values should be output as {123} not \"123\"", "if", "(", "isNumeric", "(", "attribute", ".", "value", ")", ")", "{", "result", "+=", "'={'", "+", "attribute", ".", "value", "+", "'}'", ";", "}", "else", "if", "(", "attribute", ".", "value", ".", "length", ">", "0", ")", "{", "result", "+=", "'=\"'", "+", "attribute", ".", "value", ".", "replace", "(", "/", "\"", "/", "gm", ",", "'&quot;'", ")", "+", "'\"'", ";", "}", "return", "result", ";", "}", "}" ]
Gets a JSX formatted version of the specified attribute from the node @param {DOMElement} node @param {object} attribute @return {string}
[ "Gets", "a", "JSX", "formatted", "version", "of", "the", "specified", "attribute", "from", "the", "node" ]
74b76fafbd0728f77c2bbe32a0b26a94e604442b
https://github.com/roman01la/html-to-react-components/blob/74b76fafbd0728f77c2bbe32a0b26a94e604442b/lib/html2jsx.js#L612-L633
9,802
roman01la/html-to-react-components
lib/html2jsx.js
function (output, indent) { var classIndention = new RegExp('\\n' + indent + indent + indent, 'g'); return output.replace(classIndention, '\n'); }
javascript
function (output, indent) { var classIndention = new RegExp('\\n' + indent + indent + indent, 'g'); return output.replace(classIndention, '\n'); }
[ "function", "(", "output", ",", "indent", ")", "{", "var", "classIndention", "=", "new", "RegExp", "(", "'\\\\n'", "+", "indent", "+", "indent", "+", "indent", ",", "'g'", ")", ";", "return", "output", ".", "replace", "(", "classIndention", ",", "'\\n'", ")", ";", "}" ]
Removes class-level indention in the JSX output. To be used when the JSX output is configured to not contain a class deifinition. @param {string} output JSX output with class-level indention @param {string} indent Configured indention @return {string} JSX output wihtout class-level indention
[ "Removes", "class", "-", "level", "indention", "in", "the", "JSX", "output", ".", "To", "be", "used", "when", "the", "JSX", "output", "is", "configured", "to", "not", "contain", "a", "class", "deifinition", "." ]
74b76fafbd0728f77c2bbe32a0b26a94e604442b
https://github.com/roman01la/html-to-react-components/blob/74b76fafbd0728f77c2bbe32a0b26a94e604442b/lib/html2jsx.js#L654-L657
9,803
roman01la/html-to-react-components
lib/html2jsx.js
function (rawStyle) { this.styles = {}; rawStyle.split(';').forEach(function (style) { style = style.trim(); var firstColon = style.indexOf(':'); var key = style.substr(0, firstColon); var value = style.substr(firstColon + 1).trim(); if (key !== '') { // Style key should be case insensitive key = key.toLowerCase(); this.styles[key] = value; } }, this); }
javascript
function (rawStyle) { this.styles = {}; rawStyle.split(';').forEach(function (style) { style = style.trim(); var firstColon = style.indexOf(':'); var key = style.substr(0, firstColon); var value = style.substr(firstColon + 1).trim(); if (key !== '') { // Style key should be case insensitive key = key.toLowerCase(); this.styles[key] = value; } }, this); }
[ "function", "(", "rawStyle", ")", "{", "this", ".", "styles", "=", "{", "}", ";", "rawStyle", ".", "split", "(", "';'", ")", ".", "forEach", "(", "function", "(", "style", ")", "{", "style", "=", "style", ".", "trim", "(", ")", ";", "var", "firstColon", "=", "style", ".", "indexOf", "(", "':'", ")", ";", "var", "key", "=", "style", ".", "substr", "(", "0", ",", "firstColon", ")", ";", "var", "value", "=", "style", ".", "substr", "(", "firstColon", "+", "1", ")", ".", "trim", "(", ")", ";", "if", "(", "key", "!==", "''", ")", "{", "// Style key should be case insensitive", "key", "=", "key", ".", "toLowerCase", "(", ")", ";", "this", ".", "styles", "[", "key", "]", "=", "value", ";", "}", "}", ",", "this", ")", ";", "}" ]
Parse the specified inline style attribute value @param {string} rawStyle Raw style attribute
[ "Parse", "the", "specified", "inline", "style", "attribute", "value" ]
74b76fafbd0728f77c2bbe32a0b26a94e604442b
https://github.com/roman01la/html-to-react-components/blob/74b76fafbd0728f77c2bbe32a0b26a94e604442b/lib/html2jsx.js#L674-L687
9,804
roman01la/html-to-react-components
lib/html2jsx.js
function () { var output = []; eachObj(this.styles, function (key, value) { output.push(this.toJSXKey(key) + ': ' + this.toJSXValue(value)); }, this); return output.join(', '); }
javascript
function () { var output = []; eachObj(this.styles, function (key, value) { output.push(this.toJSXKey(key) + ': ' + this.toJSXValue(value)); }, this); return output.join(', '); }
[ "function", "(", ")", "{", "var", "output", "=", "[", "]", ";", "eachObj", "(", "this", ".", "styles", ",", "function", "(", "key", ",", "value", ")", "{", "output", ".", "push", "(", "this", ".", "toJSXKey", "(", "key", ")", "+", "': '", "+", "this", ".", "toJSXValue", "(", "value", ")", ")", ";", "}", ",", "this", ")", ";", "return", "output", ".", "join", "(", "', '", ")", ";", "}" ]
Convert the style information represented by this parser into a JSX string @return {string}
[ "Convert", "the", "style", "information", "represented", "by", "this", "parser", "into", "a", "JSX", "string" ]
74b76fafbd0728f77c2bbe32a0b26a94e604442b
https://github.com/roman01la/html-to-react-components/blob/74b76fafbd0728f77c2bbe32a0b26a94e604442b/lib/html2jsx.js#L695-L701
9,805
roman01la/html-to-react-components
lib/html2jsx.js
function (value) { if (isNumeric(value)) { return value } else if (value.startsWith("'") || value.startsWith("\"")) { return value } else { return '\'' + value.replace(/'/g, '"') + '\''; } }
javascript
function (value) { if (isNumeric(value)) { return value } else if (value.startsWith("'") || value.startsWith("\"")) { return value } else { return '\'' + value.replace(/'/g, '"') + '\''; } }
[ "function", "(", "value", ")", "{", "if", "(", "isNumeric", "(", "value", ")", ")", "{", "return", "value", "}", "else", "if", "(", "value", ".", "startsWith", "(", "\"'\"", ")", "||", "value", ".", "startsWith", "(", "\"\\\"\"", ")", ")", "{", "return", "value", "}", "else", "{", "return", "'\\''", "+", "value", ".", "replace", "(", "/", "'", "/", "g", ",", "'\"'", ")", "+", "'\\''", ";", "}", "}" ]
Convert the CSS style value to a JSX style value @param {string} value CSS style value @return {string} JSX style value
[ "Convert", "the", "CSS", "style", "value", "to", "a", "JSX", "style", "value" ]
74b76fafbd0728f77c2bbe32a0b26a94e604442b
https://github.com/roman01la/html-to-react-components/blob/74b76fafbd0728f77c2bbe32a0b26a94e604442b/lib/html2jsx.js#L723-L731
9,806
snorpey/glitch-canvas
dist/glitch-canvas-browser.es6.js
imageToImageData
function imageToImageData ( image ) { if ( image instanceof HTMLImageElement ) { // http://stackoverflow.com/a/3016076/229189 if ( ! image.naturalWidth || ! image.naturalHeight || image.complete === false ) { throw new Error( "This this image hasn't finished loading: " + image.src ); } const canvas = new Canvas( image.naturalWidth, image.naturalHeight ); const ctx = canvas.getContext( '2d' ); ctx.drawImage( image, 0, 0, canvas.width, canvas.height ); const imageData = ctx.getImageData( 0, 0, canvas.width, canvas.height ); if ( imageData.data && imageData.data.length ) { if ( typeof imageData.width === 'undefined' ) { imageData.width = image.naturalWidth; } if ( typeof imageData.height === 'undefined' ) { imageData.height = image.naturalHeight; } } return imageData; } else { throw new Error( 'This object does not seem to be an image.' ); return; } }
javascript
function imageToImageData ( image ) { if ( image instanceof HTMLImageElement ) { // http://stackoverflow.com/a/3016076/229189 if ( ! image.naturalWidth || ! image.naturalHeight || image.complete === false ) { throw new Error( "This this image hasn't finished loading: " + image.src ); } const canvas = new Canvas( image.naturalWidth, image.naturalHeight ); const ctx = canvas.getContext( '2d' ); ctx.drawImage( image, 0, 0, canvas.width, canvas.height ); const imageData = ctx.getImageData( 0, 0, canvas.width, canvas.height ); if ( imageData.data && imageData.data.length ) { if ( typeof imageData.width === 'undefined' ) { imageData.width = image.naturalWidth; } if ( typeof imageData.height === 'undefined' ) { imageData.height = image.naturalHeight; } } return imageData; } else { throw new Error( 'This object does not seem to be an image.' ); return; } }
[ "function", "imageToImageData", "(", "image", ")", "{", "if", "(", "image", "instanceof", "HTMLImageElement", ")", "{", "// http://stackoverflow.com/a/3016076/229189", "if", "(", "!", "image", ".", "naturalWidth", "||", "!", "image", ".", "naturalHeight", "||", "image", ".", "complete", "===", "false", ")", "{", "throw", "new", "Error", "(", "\"This this image hasn't finished loading: \"", "+", "image", ".", "src", ")", ";", "}", "const", "canvas", "=", "new", "Canvas", "(", "image", ".", "naturalWidth", ",", "image", ".", "naturalHeight", ")", ";", "const", "ctx", "=", "canvas", ".", "getContext", "(", "'2d'", ")", ";", "ctx", ".", "drawImage", "(", "image", ",", "0", ",", "0", ",", "canvas", ".", "width", ",", "canvas", ".", "height", ")", ";", "const", "imageData", "=", "ctx", ".", "getImageData", "(", "0", ",", "0", ",", "canvas", ".", "width", ",", "canvas", ".", "height", ")", ";", "if", "(", "imageData", ".", "data", "&&", "imageData", ".", "data", ".", "length", ")", "{", "if", "(", "typeof", "imageData", ".", "width", "===", "'undefined'", ")", "{", "imageData", ".", "width", "=", "image", ".", "naturalWidth", ";", "}", "if", "(", "typeof", "imageData", ".", "height", "===", "'undefined'", ")", "{", "imageData", ".", "height", "=", "image", ".", "naturalHeight", ";", "}", "}", "return", "imageData", ";", "}", "else", "{", "throw", "new", "Error", "(", "'This object does not seem to be an image.'", ")", ";", "return", ";", "}", "}" ]
import Canvas from 'canvas';
[ "import", "Canvas", "from", "canvas", ";" ]
d9012df97cfdb888dddc16b5f5c775a134d4b151
https://github.com/snorpey/glitch-canvas/blob/d9012df97cfdb888dddc16b5f5c775a134d4b151/dist/glitch-canvas-browser.es6.js#L105-L134
9,807
substance/substance
model/annotationHelpers.js
transferAnnotations
function transferAnnotations (doc, path, offset, newPath, newOffset) { var index = doc.getIndex('annotations') var annotations = index.get(path, offset) for (let i = 0; i < annotations.length; i++) { let a = annotations[i] var isInside = (offset > a.start.offset && offset < a.end.offset) var start = a.start.offset var end = a.end.offset // 1. if the cursor is inside an annotation it gets either split or truncated if (isInside) { // create a new annotation if the annotation is splittable if (a.canSplit()) { let newAnno = a.toJSON() newAnno.id = uuid(a.type + '_') newAnno.start.path = newPath newAnno.start.offset = newOffset newAnno.end.path = newPath newAnno.end.offset = newOffset + a.end.offset - offset doc.create(newAnno) } // in either cases truncate the first part let newStartOffset = a.start.offset let newEndOffset = offset // if after truncate the anno is empty, delete it if (newEndOffset === newStartOffset) { doc.delete(a.id) // ... otherwise update the range } else { // TODO: Use coordintate ops! if (newStartOffset !== start) { doc.set([a.id, 'start', 'offset'], newStartOffset) } if (newEndOffset !== end) { doc.set([a.id, 'end', 'offset'], newEndOffset) } } // 2. if the cursor is before an annotation then simply transfer the annotation to the new node } else if (a.start.offset >= offset) { // TODO: Use coordintate ops! // Note: we are preserving the annotation so that anything which is connected to the annotation // remains valid. doc.set([a.id, 'start', 'path'], newPath) doc.set([a.id, 'start', 'offset'], newOffset + a.start.offset - offset) doc.set([a.id, 'end', 'path'], newPath) doc.set([a.id, 'end', 'offset'], newOffset + a.end.offset - offset) } } // TODO: fix support for container annotations // // same for container annotation anchors // index = doc.getIndex('container-annotation-anchors'); // var anchors = index.get(path); // var containerAnnoIds = []; // forEach(anchors, function(anchor) { // containerAnnoIds.push(anchor.id); // var start = anchor.offset; // if (offset <= start) { // // TODO: Use coordintate ops! // let coor = anchor.isStart?'start':'end' // doc.set([anchor.id, coor, 'path'], newPath); // doc.set([anchor.id, coor, 'offset'], newOffset + anchor.offset - offset); // } // }); // // check all anchors after that if they have collapsed and remove the annotation in that case // forEach(uniq(containerAnnoIds), function(id) { // var anno = doc.get(id); // var annoSel = anno.getSelection(); // if(annoSel.isCollapsed()) { // // console.log("...deleting container annotation because it has collapsed" + id); // doc.delete(id); // } // }); }
javascript
function transferAnnotations (doc, path, offset, newPath, newOffset) { var index = doc.getIndex('annotations') var annotations = index.get(path, offset) for (let i = 0; i < annotations.length; i++) { let a = annotations[i] var isInside = (offset > a.start.offset && offset < a.end.offset) var start = a.start.offset var end = a.end.offset // 1. if the cursor is inside an annotation it gets either split or truncated if (isInside) { // create a new annotation if the annotation is splittable if (a.canSplit()) { let newAnno = a.toJSON() newAnno.id = uuid(a.type + '_') newAnno.start.path = newPath newAnno.start.offset = newOffset newAnno.end.path = newPath newAnno.end.offset = newOffset + a.end.offset - offset doc.create(newAnno) } // in either cases truncate the first part let newStartOffset = a.start.offset let newEndOffset = offset // if after truncate the anno is empty, delete it if (newEndOffset === newStartOffset) { doc.delete(a.id) // ... otherwise update the range } else { // TODO: Use coordintate ops! if (newStartOffset !== start) { doc.set([a.id, 'start', 'offset'], newStartOffset) } if (newEndOffset !== end) { doc.set([a.id, 'end', 'offset'], newEndOffset) } } // 2. if the cursor is before an annotation then simply transfer the annotation to the new node } else if (a.start.offset >= offset) { // TODO: Use coordintate ops! // Note: we are preserving the annotation so that anything which is connected to the annotation // remains valid. doc.set([a.id, 'start', 'path'], newPath) doc.set([a.id, 'start', 'offset'], newOffset + a.start.offset - offset) doc.set([a.id, 'end', 'path'], newPath) doc.set([a.id, 'end', 'offset'], newOffset + a.end.offset - offset) } } // TODO: fix support for container annotations // // same for container annotation anchors // index = doc.getIndex('container-annotation-anchors'); // var anchors = index.get(path); // var containerAnnoIds = []; // forEach(anchors, function(anchor) { // containerAnnoIds.push(anchor.id); // var start = anchor.offset; // if (offset <= start) { // // TODO: Use coordintate ops! // let coor = anchor.isStart?'start':'end' // doc.set([anchor.id, coor, 'path'], newPath); // doc.set([anchor.id, coor, 'offset'], newOffset + anchor.offset - offset); // } // }); // // check all anchors after that if they have collapsed and remove the annotation in that case // forEach(uniq(containerAnnoIds), function(id) { // var anno = doc.get(id); // var annoSel = anno.getSelection(); // if(annoSel.isCollapsed()) { // // console.log("...deleting container annotation because it has collapsed" + id); // doc.delete(id); // } // }); }
[ "function", "transferAnnotations", "(", "doc", ",", "path", ",", "offset", ",", "newPath", ",", "newOffset", ")", "{", "var", "index", "=", "doc", ".", "getIndex", "(", "'annotations'", ")", "var", "annotations", "=", "index", ".", "get", "(", "path", ",", "offset", ")", "for", "(", "let", "i", "=", "0", ";", "i", "<", "annotations", ".", "length", ";", "i", "++", ")", "{", "let", "a", "=", "annotations", "[", "i", "]", "var", "isInside", "=", "(", "offset", ">", "a", ".", "start", ".", "offset", "&&", "offset", "<", "a", ".", "end", ".", "offset", ")", "var", "start", "=", "a", ".", "start", ".", "offset", "var", "end", "=", "a", ".", "end", ".", "offset", "// 1. if the cursor is inside an annotation it gets either split or truncated", "if", "(", "isInside", ")", "{", "// create a new annotation if the annotation is splittable", "if", "(", "a", ".", "canSplit", "(", ")", ")", "{", "let", "newAnno", "=", "a", ".", "toJSON", "(", ")", "newAnno", ".", "id", "=", "uuid", "(", "a", ".", "type", "+", "'_'", ")", "newAnno", ".", "start", ".", "path", "=", "newPath", "newAnno", ".", "start", ".", "offset", "=", "newOffset", "newAnno", ".", "end", ".", "path", "=", "newPath", "newAnno", ".", "end", ".", "offset", "=", "newOffset", "+", "a", ".", "end", ".", "offset", "-", "offset", "doc", ".", "create", "(", "newAnno", ")", "}", "// in either cases truncate the first part", "let", "newStartOffset", "=", "a", ".", "start", ".", "offset", "let", "newEndOffset", "=", "offset", "// if after truncate the anno is empty, delete it", "if", "(", "newEndOffset", "===", "newStartOffset", ")", "{", "doc", ".", "delete", "(", "a", ".", "id", ")", "// ... otherwise update the range", "}", "else", "{", "// TODO: Use coordintate ops!", "if", "(", "newStartOffset", "!==", "start", ")", "{", "doc", ".", "set", "(", "[", "a", ".", "id", ",", "'start'", ",", "'offset'", "]", ",", "newStartOffset", ")", "}", "if", "(", "newEndOffset", "!==", "end", ")", "{", "doc", ".", "set", "(", "[", "a", ".", "id", ",", "'end'", ",", "'offset'", "]", ",", "newEndOffset", ")", "}", "}", "// 2. if the cursor is before an annotation then simply transfer the annotation to the new node", "}", "else", "if", "(", "a", ".", "start", ".", "offset", ">=", "offset", ")", "{", "// TODO: Use coordintate ops!", "// Note: we are preserving the annotation so that anything which is connected to the annotation", "// remains valid.", "doc", ".", "set", "(", "[", "a", ".", "id", ",", "'start'", ",", "'path'", "]", ",", "newPath", ")", "doc", ".", "set", "(", "[", "a", ".", "id", ",", "'start'", ",", "'offset'", "]", ",", "newOffset", "+", "a", ".", "start", ".", "offset", "-", "offset", ")", "doc", ".", "set", "(", "[", "a", ".", "id", ",", "'end'", ",", "'path'", "]", ",", "newPath", ")", "doc", ".", "set", "(", "[", "a", ".", "id", ",", "'end'", ",", "'offset'", "]", ",", "newOffset", "+", "a", ".", "end", ".", "offset", "-", "offset", ")", "}", "}", "// TODO: fix support for container annotations", "// // same for container annotation anchors", "// index = doc.getIndex('container-annotation-anchors');", "// var anchors = index.get(path);", "// var containerAnnoIds = [];", "// forEach(anchors, function(anchor) {", "// containerAnnoIds.push(anchor.id);", "// var start = anchor.offset;", "// if (offset <= start) {", "// // TODO: Use coordintate ops!", "// let coor = anchor.isStart?'start':'end'", "// doc.set([anchor.id, coor, 'path'], newPath);", "// doc.set([anchor.id, coor, 'offset'], newOffset + anchor.offset - offset);", "// }", "// });", "// // check all anchors after that if they have collapsed and remove the annotation in that case", "// forEach(uniq(containerAnnoIds), function(id) {", "// var anno = doc.get(id);", "// var annoSel = anno.getSelection();", "// if(annoSel.isCollapsed()) {", "// // console.log(\"...deleting container annotation because it has collapsed\" + id);", "// doc.delete(id);", "// }", "// });", "}" ]
used when breaking a node to transfer annotations to the new property
[ "used", "when", "breaking", "a", "node", "to", "transfer", "annotations", "to", "the", "new", "property" ]
b4310f24b4466a96af7fe313e8f615d56cda3a84
https://github.com/substance/substance/blob/b4310f24b4466a96af7fe313e8f615d56cda3a84/model/annotationHelpers.js#L148-L220
9,808
substance/substance
util/EventEmitter.js
_disconnect
function _disconnect (context) { /* eslint-disable no-invalid-this */ // Remove all connections to the context forEach(this.__events__, (bindings, event) => { for (let i = bindings.length - 1; i >= 0; i--) { // bindings[i] may have been removed by the previous steps // so check it still exists if (bindings[i] && bindings[i].context === context) { _off.call(this, event, bindings[i].method, context) } } }) return this /* eslint-enable no-invalid-this */ }
javascript
function _disconnect (context) { /* eslint-disable no-invalid-this */ // Remove all connections to the context forEach(this.__events__, (bindings, event) => { for (let i = bindings.length - 1; i >= 0; i--) { // bindings[i] may have been removed by the previous steps // so check it still exists if (bindings[i] && bindings[i].context === context) { _off.call(this, event, bindings[i].method, context) } } }) return this /* eslint-enable no-invalid-this */ }
[ "function", "_disconnect", "(", "context", ")", "{", "/* eslint-disable no-invalid-this */", "// Remove all connections to the context", "forEach", "(", "this", ".", "__events__", ",", "(", "bindings", ",", "event", ")", "=>", "{", "for", "(", "let", "i", "=", "bindings", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "// bindings[i] may have been removed by the previous steps", "// so check it still exists", "if", "(", "bindings", "[", "i", "]", "&&", "bindings", "[", "i", "]", ".", "context", "===", "context", ")", "{", "_off", ".", "call", "(", "this", ",", "event", ",", "bindings", "[", "i", "]", ".", "method", ",", "context", ")", "}", "}", "}", ")", "return", "this", "/* eslint-enable no-invalid-this */", "}" ]
removes a listener from all events
[ "removes", "a", "listener", "from", "all", "events" ]
b4310f24b4466a96af7fe313e8f615d56cda3a84
https://github.com/substance/substance/blob/b4310f24b4466a96af7fe313e8f615d56cda3a84/util/EventEmitter.js#L177-L191
9,809
substance/substance
ui/RenderingEngine.js
_create
function _create (state, vel) { let comp = vel._comp console.assert(!comp, 'Component instance should not exist when this method is used.') let parent = vel.parent._comp // making sure the parent components have been instantiated if (!parent) { parent = _create(state, vel.parent) } // TODO: probably we should do something with forwarded/forwarding components here? if (vel._isVirtualComponent) { console.assert(parent, 'A Component should have a parent.') comp = state.componentFactory.createComponent(vel.ComponentClass, parent, vel.props) // HACK: making sure that we have the right props // TODO: instead of HACK add an assertion, and make otherwise sure that vel.props is set correctly vel.props = comp.props if (vel._forwardedEl) { let forwardedEl = vel._forwardedEl let forwardedComp = state.componentFactory.createComponent(forwardedEl.ComponentClass, comp, forwardedEl.props) // HACK same as before forwardedEl.props = forwardedComp.props comp._forwardedComp = forwardedComp } } else if (vel._isVirtualHTMLElement) { comp = state.componentFactory.createElementComponent(parent, vel) } else if (vel._isVirtualTextNode) { comp = state.componentFactory.createTextNodeComponent(parent, vel) } if (vel._ref) { comp._ref = vel._ref } if (vel._owner) { comp._owner = vel._owner._comp } vel._comp = comp return comp }
javascript
function _create (state, vel) { let comp = vel._comp console.assert(!comp, 'Component instance should not exist when this method is used.') let parent = vel.parent._comp // making sure the parent components have been instantiated if (!parent) { parent = _create(state, vel.parent) } // TODO: probably we should do something with forwarded/forwarding components here? if (vel._isVirtualComponent) { console.assert(parent, 'A Component should have a parent.') comp = state.componentFactory.createComponent(vel.ComponentClass, parent, vel.props) // HACK: making sure that we have the right props // TODO: instead of HACK add an assertion, and make otherwise sure that vel.props is set correctly vel.props = comp.props if (vel._forwardedEl) { let forwardedEl = vel._forwardedEl let forwardedComp = state.componentFactory.createComponent(forwardedEl.ComponentClass, comp, forwardedEl.props) // HACK same as before forwardedEl.props = forwardedComp.props comp._forwardedComp = forwardedComp } } else if (vel._isVirtualHTMLElement) { comp = state.componentFactory.createElementComponent(parent, vel) } else if (vel._isVirtualTextNode) { comp = state.componentFactory.createTextNodeComponent(parent, vel) } if (vel._ref) { comp._ref = vel._ref } if (vel._owner) { comp._owner = vel._owner._comp } vel._comp = comp return comp }
[ "function", "_create", "(", "state", ",", "vel", ")", "{", "let", "comp", "=", "vel", ".", "_comp", "console", ".", "assert", "(", "!", "comp", ",", "'Component instance should not exist when this method is used.'", ")", "let", "parent", "=", "vel", ".", "parent", ".", "_comp", "// making sure the parent components have been instantiated", "if", "(", "!", "parent", ")", "{", "parent", "=", "_create", "(", "state", ",", "vel", ".", "parent", ")", "}", "// TODO: probably we should do something with forwarded/forwarding components here?", "if", "(", "vel", ".", "_isVirtualComponent", ")", "{", "console", ".", "assert", "(", "parent", ",", "'A Component should have a parent.'", ")", "comp", "=", "state", ".", "componentFactory", ".", "createComponent", "(", "vel", ".", "ComponentClass", ",", "parent", ",", "vel", ".", "props", ")", "// HACK: making sure that we have the right props", "// TODO: instead of HACK add an assertion, and make otherwise sure that vel.props is set correctly", "vel", ".", "props", "=", "comp", ".", "props", "if", "(", "vel", ".", "_forwardedEl", ")", "{", "let", "forwardedEl", "=", "vel", ".", "_forwardedEl", "let", "forwardedComp", "=", "state", ".", "componentFactory", ".", "createComponent", "(", "forwardedEl", ".", "ComponentClass", ",", "comp", ",", "forwardedEl", ".", "props", ")", "// HACK same as before", "forwardedEl", ".", "props", "=", "forwardedComp", ".", "props", "comp", ".", "_forwardedComp", "=", "forwardedComp", "}", "}", "else", "if", "(", "vel", ".", "_isVirtualHTMLElement", ")", "{", "comp", "=", "state", ".", "componentFactory", ".", "createElementComponent", "(", "parent", ",", "vel", ")", "}", "else", "if", "(", "vel", ".", "_isVirtualTextNode", ")", "{", "comp", "=", "state", ".", "componentFactory", ".", "createTextNodeComponent", "(", "parent", ",", "vel", ")", "}", "if", "(", "vel", ".", "_ref", ")", "{", "comp", ".", "_ref", "=", "vel", ".", "_ref", "}", "if", "(", "vel", ".", "_owner", ")", "{", "comp", ".", "_owner", "=", "vel", ".", "_owner", ".", "_comp", "}", "vel", ".", "_comp", "=", "comp", "return", "comp", "}" ]
called to initialize a captured component, i.e. creating a Component instance from a VirtualElement
[ "called", "to", "initialize", "a", "captured", "component", "i", ".", "e", ".", "creating", "a", "Component", "instance", "from", "a", "VirtualElement" ]
b4310f24b4466a96af7fe313e8f615d56cda3a84
https://github.com/substance/substance/blob/b4310f24b4466a96af7fe313e8f615d56cda3a84/ui/RenderingEngine.js#L372-L407
9,810
liquality/chainabstractionlayer
packages/bitcoin-utils/lib/index.js
compressPubKey
function compressPubKey (pubKey) { const x = pubKey.substring(2, 66) const y = pubKey.substring(66, 130) const even = parseInt(y.substring(62, 64), 16) % 2 === 0 const prefix = even ? '02' : '03' return prefix + x }
javascript
function compressPubKey (pubKey) { const x = pubKey.substring(2, 66) const y = pubKey.substring(66, 130) const even = parseInt(y.substring(62, 64), 16) % 2 === 0 const prefix = even ? '02' : '03' return prefix + x }
[ "function", "compressPubKey", "(", "pubKey", ")", "{", "const", "x", "=", "pubKey", ".", "substring", "(", "2", ",", "66", ")", "const", "y", "=", "pubKey", ".", "substring", "(", "66", ",", "130", ")", "const", "even", "=", "parseInt", "(", "y", ".", "substring", "(", "62", ",", "64", ")", ",", "16", ")", "%", "2", "===", "0", "const", "prefix", "=", "even", "?", "'02'", ":", "'03'", "return", "prefix", "+", "x", "}" ]
Get compressed pubKey from pubKey. @param {!string} pubKey - 65 byte string with prefix, x, y. @return {string} Returns the compressed pubKey of uncompressed pubKey.
[ "Get", "compressed", "pubKey", "from", "pubKey", "." ]
2c402490422fa0ffe4fee6aac1e54083f7fb9ff4
https://github.com/liquality/chainabstractionlayer/blob/2c402490422fa0ffe4fee6aac1e54083f7fb9ff4/packages/bitcoin-utils/lib/index.js#L21-L28
9,811
liquality/chainabstractionlayer
packages/bitcoin-utils/lib/index.js
pubKeyToAddress
function pubKeyToAddress (pubKey, network, type) { pubKey = ensureBuffer(pubKey) const pubKeyHash = hash160(pubKey) const addr = pubKeyHashToAddress(pubKeyHash, network, type) return addr }
javascript
function pubKeyToAddress (pubKey, network, type) { pubKey = ensureBuffer(pubKey) const pubKeyHash = hash160(pubKey) const addr = pubKeyHashToAddress(pubKeyHash, network, type) return addr }
[ "function", "pubKeyToAddress", "(", "pubKey", ",", "network", ",", "type", ")", "{", "pubKey", "=", "ensureBuffer", "(", "pubKey", ")", "const", "pubKeyHash", "=", "hash160", "(", "pubKey", ")", "const", "addr", "=", "pubKeyHashToAddress", "(", "pubKeyHash", ",", "network", ",", "type", ")", "return", "addr", "}" ]
Get address from pubKey. @param {!string|Buffer} pubKey - 65 byte uncompressed pubKey or 33 byte compressed pubKey. @param {!string} network - bitcoin, testnet, or litecoin. @param {!string} type - pubKeyHash or scriptHash. @return {string} Returns the address of pubKey.
[ "Get", "address", "from", "pubKey", "." ]
2c402490422fa0ffe4fee6aac1e54083f7fb9ff4
https://github.com/liquality/chainabstractionlayer/blob/2c402490422fa0ffe4fee6aac1e54083f7fb9ff4/packages/bitcoin-utils/lib/index.js#L37-L42
9,812
liquality/chainabstractionlayer
packages/bitcoin-utils/lib/index.js
pubKeyHashToAddress
function pubKeyHashToAddress (pubKeyHash, network, type) { pubKeyHash = ensureBuffer(pubKeyHash) const prefixHash = Buffer.concat([Buffer.from(networks[network][type], 'hex'), pubKeyHash]) const checksum = Buffer.from(sha256(sha256(prefixHash)).slice(0, 8), 'hex') const addr = base58.encode(Buffer.concat([prefixHash, checksum]).slice(0, 25)) return addr }
javascript
function pubKeyHashToAddress (pubKeyHash, network, type) { pubKeyHash = ensureBuffer(pubKeyHash) const prefixHash = Buffer.concat([Buffer.from(networks[network][type], 'hex'), pubKeyHash]) const checksum = Buffer.from(sha256(sha256(prefixHash)).slice(0, 8), 'hex') const addr = base58.encode(Buffer.concat([prefixHash, checksum]).slice(0, 25)) return addr }
[ "function", "pubKeyHashToAddress", "(", "pubKeyHash", ",", "network", ",", "type", ")", "{", "pubKeyHash", "=", "ensureBuffer", "(", "pubKeyHash", ")", "const", "prefixHash", "=", "Buffer", ".", "concat", "(", "[", "Buffer", ".", "from", "(", "networks", "[", "network", "]", "[", "type", "]", ",", "'hex'", ")", ",", "pubKeyHash", "]", ")", "const", "checksum", "=", "Buffer", ".", "from", "(", "sha256", "(", "sha256", "(", "prefixHash", ")", ")", ".", "slice", "(", "0", ",", "8", ")", ",", "'hex'", ")", "const", "addr", "=", "base58", ".", "encode", "(", "Buffer", ".", "concat", "(", "[", "prefixHash", ",", "checksum", "]", ")", ".", "slice", "(", "0", ",", "25", ")", ")", "return", "addr", "}" ]
Get address from pubKeyHash. @param {!string} pubKeyHash - hash160 of pubKey. @param {!string} network - bitcoin, testnet, or litecoin. @param {!string} type - pubKeyHash or scriptHash. @return {string} Returns the address derived from pubKeyHash.
[ "Get", "address", "from", "pubKeyHash", "." ]
2c402490422fa0ffe4fee6aac1e54083f7fb9ff4
https://github.com/liquality/chainabstractionlayer/blob/2c402490422fa0ffe4fee6aac1e54083f7fb9ff4/packages/bitcoin-utils/lib/index.js#L51-L57
9,813
liquality/chainabstractionlayer
packages/bitcoin-utils/lib/index.js
getAddressNetwork
function getAddressNetwork (address) { const prefix = base58.decode(address).toString('hex').substring(0, 2).toUpperCase() const networkKey = findKey(networks, network => [network.pubKeyHash, network.scriptHash].includes(prefix)) return networks[networkKey] }
javascript
function getAddressNetwork (address) { const prefix = base58.decode(address).toString('hex').substring(0, 2).toUpperCase() const networkKey = findKey(networks, network => [network.pubKeyHash, network.scriptHash].includes(prefix)) return networks[networkKey] }
[ "function", "getAddressNetwork", "(", "address", ")", "{", "const", "prefix", "=", "base58", ".", "decode", "(", "address", ")", ".", "toString", "(", "'hex'", ")", ".", "substring", "(", "0", ",", "2", ")", ".", "toUpperCase", "(", ")", "const", "networkKey", "=", "findKey", "(", "networks", ",", "network", "=>", "[", "network", ".", "pubKeyHash", ",", "network", ".", "scriptHash", "]", ".", "includes", "(", "prefix", ")", ")", "return", "networks", "[", "networkKey", "]", "}" ]
Get a network object from an address @param {string} address The bitcoin address @return {Network}
[ "Get", "a", "network", "object", "from", "an", "address" ]
2c402490422fa0ffe4fee6aac1e54083f7fb9ff4
https://github.com/liquality/chainabstractionlayer/blob/2c402490422fa0ffe4fee6aac1e54083f7fb9ff4/packages/bitcoin-utils/lib/index.js#L126-L131
9,814
liquality/chainabstractionlayer
packages/crypto/lib/index.js
ensureBuffer
function ensureBuffer (message) { if (Buffer.isBuffer(message)) return message switch (typeof message) { case 'string': message = isHex(message) ? Buffer.from(message, 'hex') : Buffer.from(message) break case 'object': message = Buffer.from(JSON.stringify(message)) break } return Buffer.isBuffer(message) ? message : false }
javascript
function ensureBuffer (message) { if (Buffer.isBuffer(message)) return message switch (typeof message) { case 'string': message = isHex(message) ? Buffer.from(message, 'hex') : Buffer.from(message) break case 'object': message = Buffer.from(JSON.stringify(message)) break } return Buffer.isBuffer(message) ? message : false }
[ "function", "ensureBuffer", "(", "message", ")", "{", "if", "(", "Buffer", ".", "isBuffer", "(", "message", ")", ")", "return", "message", "switch", "(", "typeof", "message", ")", "{", "case", "'string'", ":", "message", "=", "isHex", "(", "message", ")", "?", "Buffer", ".", "from", "(", "message", ",", "'hex'", ")", ":", "Buffer", ".", "from", "(", "message", ")", "break", "case", "'object'", ":", "message", "=", "Buffer", ".", "from", "(", "JSON", ".", "stringify", "(", "message", ")", ")", "break", "}", "return", "Buffer", ".", "isBuffer", "(", "message", ")", "?", "message", ":", "false", "}" ]
Ensure message is in buffer format. @param {string} message - any string. @return {string} Returns Buffer of string.
[ "Ensure", "message", "is", "in", "buffer", "format", "." ]
2c402490422fa0ffe4fee6aac1e54083f7fb9ff4
https://github.com/liquality/chainabstractionlayer/blob/2c402490422fa0ffe4fee6aac1e54083f7fb9ff4/packages/crypto/lib/index.js#L18-L31
9,815
liquality/chainabstractionlayer
packages/crypto/lib/index.js
padHexStart
function padHexStart (hex, length) { let len = length || hex.length len += len % 2 return hex.padStart(len, '0') }
javascript
function padHexStart (hex, length) { let len = length || hex.length len += len % 2 return hex.padStart(len, '0') }
[ "function", "padHexStart", "(", "hex", ",", "length", ")", "{", "let", "len", "=", "length", "||", "hex", ".", "length", "len", "+=", "len", "%", "2", "return", "hex", ".", "padStart", "(", "len", ",", "'0'", ")", "}" ]
Pad a hex string with '0' @param {string} hex - The hex string to pad. @param {number} [length] - The length of the final string. @return Returns a padded string with length greater or equal to the given length rounded up to the nearest even number.
[ "Pad", "a", "hex", "string", "with", "0" ]
2c402490422fa0ffe4fee6aac1e54083f7fb9ff4
https://github.com/liquality/chainabstractionlayer/blob/2c402490422fa0ffe4fee6aac1e54083f7fb9ff4/packages/crypto/lib/index.js#L77-L82
9,816
apache/cordova-osx
bin/templates/scripts/cordova/lib/run.js
runApp
function runApp (appDir, appName) { var binPath = path.join(appDir, 'Contents', 'MacOS', appName); events.emit('log', 'Starting: ' + binPath); return spawn(binPath); }
javascript
function runApp (appDir, appName) { var binPath = path.join(appDir, 'Contents', 'MacOS', appName); events.emit('log', 'Starting: ' + binPath); return spawn(binPath); }
[ "function", "runApp", "(", "appDir", ",", "appName", ")", "{", "var", "binPath", "=", "path", ".", "join", "(", "appDir", ",", "'Contents'", ",", "'MacOS'", ",", "appName", ")", ";", "events", ".", "emit", "(", "'log'", ",", "'Starting: '", "+", "binPath", ")", ";", "return", "spawn", "(", "binPath", ")", ";", "}" ]
runs the app @return {Promise} Resolves when run succeeds otherwise rejects
[ "runs", "the", "app" ]
ea2d3c7482a4baf6ba3906dd2d0d929101ed7843
https://github.com/apache/cordova-osx/blob/ea2d3c7482a4baf6ba3906dd2d0d929101ed7843/bin/templates/scripts/cordova/lib/run.js#L50-L54
9,817
instructure/instructure-ui
packages/babel-plugin-transform-class-display-name/lib/index.js
isReactClass
function isReactClass (node) { if (!node || !t.isCallExpression(node)) return false // not _createClass call if (!node.callee || node.callee.name !== '_createClass') return false // no call arguments const args = node.arguments if (!args || args.length !== 2) return false if (!t.isIdentifier(args[0])) return false if (!t.isArrayExpression(args[1])) return false // no render method if (!args[1].elements || !args[1].elements.some((el) => { return isRenderMethod(el.properties) })) return false return true }
javascript
function isReactClass (node) { if (!node || !t.isCallExpression(node)) return false // not _createClass call if (!node.callee || node.callee.name !== '_createClass') return false // no call arguments const args = node.arguments if (!args || args.length !== 2) return false if (!t.isIdentifier(args[0])) return false if (!t.isArrayExpression(args[1])) return false // no render method if (!args[1].elements || !args[1].elements.some((el) => { return isRenderMethod(el.properties) })) return false return true }
[ "function", "isReactClass", "(", "node", ")", "{", "if", "(", "!", "node", "||", "!", "t", ".", "isCallExpression", "(", "node", ")", ")", "return", "false", "// not _createClass call", "if", "(", "!", "node", ".", "callee", "||", "node", ".", "callee", ".", "name", "!==", "'_createClass'", ")", "return", "false", "// no call arguments", "const", "args", "=", "node", ".", "arguments", "if", "(", "!", "args", "||", "args", ".", "length", "!==", "2", ")", "return", "false", "if", "(", "!", "t", ".", "isIdentifier", "(", "args", "[", "0", "]", ")", ")", "return", "false", "if", "(", "!", "t", ".", "isArrayExpression", "(", "args", "[", "1", "]", ")", ")", "return", "false", "// no render method", "if", "(", "!", "args", "[", "1", "]", ".", "elements", "||", "!", "args", "[", "1", "]", ".", "elements", ".", "some", "(", "(", "el", ")", "=>", "{", "return", "isRenderMethod", "(", "el", ".", "properties", ")", "}", ")", ")", "return", "false", "return", "true", "}" ]
Determine if an AST node is likely a class extending React.Component
[ "Determine", "if", "an", "AST", "node", "is", "likely", "a", "class", "extending", "React", ".", "Component" ]
7cee93b56f34679824b49d79e0d5821e4c9b5ea7
https://github.com/instructure/instructure-ui/blob/7cee93b56f34679824b49d79e0d5821e4c9b5ea7/packages/babel-plugin-transform-class-display-name/lib/index.js#L29-L47
9,818
instructure/instructure-ui
packages/babel-plugin-transform-class-display-name/lib/index.js
isRenderMethod
function isRenderMethod (props) { return props.some((prop) => { return prop.key.name === 'key' && prop.value.value === 'render' }) && props.some((prop) => { return prop.key.name === 'value' && t.isFunctionExpression(prop.value) }) }
javascript
function isRenderMethod (props) { return props.some((prop) => { return prop.key.name === 'key' && prop.value.value === 'render' }) && props.some((prop) => { return prop.key.name === 'value' && t.isFunctionExpression(prop.value) }) }
[ "function", "isRenderMethod", "(", "props", ")", "{", "return", "props", ".", "some", "(", "(", "prop", ")", "=>", "{", "return", "prop", ".", "key", ".", "name", "===", "'key'", "&&", "prop", ".", "value", ".", "value", "===", "'render'", "}", ")", "&&", "props", ".", "some", "(", "(", "prop", ")", "=>", "{", "return", "prop", ".", "key", ".", "name", "===", "'value'", "&&", "t", ".", "isFunctionExpression", "(", "prop", ".", "value", ")", "}", ")", "}" ]
Determine if a property definition is for a render method
[ "Determine", "if", "a", "property", "definition", "is", "for", "a", "render", "method" ]
7cee93b56f34679824b49d79e0d5821e4c9b5ea7
https://github.com/instructure/instructure-ui/blob/7cee93b56f34679824b49d79e0d5821e4c9b5ea7/packages/babel-plugin-transform-class-display-name/lib/index.js#L52-L58
9,819
instructure/instructure-ui
packages/babel-plugin-transform-class-display-name/lib/index.js
insertDisplayName
function insertDisplayName(path, id) { const assignment = t.assignmentExpression( '=', t.memberExpression( t.identifier(id), t.identifier('displayName') ), t.stringLiteral(id) ) // Put in the assignment expression and a semicolon path.insertAfter([assignment, t.emptyStatement()]) }
javascript
function insertDisplayName(path, id) { const assignment = t.assignmentExpression( '=', t.memberExpression( t.identifier(id), t.identifier('displayName') ), t.stringLiteral(id) ) // Put in the assignment expression and a semicolon path.insertAfter([assignment, t.emptyStatement()]) }
[ "function", "insertDisplayName", "(", "path", ",", "id", ")", "{", "const", "assignment", "=", "t", ".", "assignmentExpression", "(", "'='", ",", "t", ".", "memberExpression", "(", "t", ".", "identifier", "(", "id", ")", ",", "t", ".", "identifier", "(", "'displayName'", ")", ")", ",", "t", ".", "stringLiteral", "(", "id", ")", ")", "// Put in the assignment expression and a semicolon", "path", ".", "insertAfter", "(", "[", "assignment", ",", "t", ".", "emptyStatement", "(", ")", "]", ")", "}" ]
Insert a static displayName for the identifier
[ "Insert", "a", "static", "displayName", "for", "the", "identifier" ]
7cee93b56f34679824b49d79e0d5821e4c9b5ea7
https://github.com/instructure/instructure-ui/blob/7cee93b56f34679824b49d79e0d5821e4c9b5ea7/packages/babel-plugin-transform-class-display-name/lib/index.js#L63-L74
9,820
instructure/instructure-ui
packages/ui-i18n/src/DateTime.js
parse
function parse (dateString, locale, timezone) { _checkParams(locale, timezone) // list all available localized formats, from most specific to least return moment.tz(dateString, [moment.ISO_8601, 'llll', 'LLLL', 'lll', 'LLL', 'll', 'LL', 'l', 'L'], locale, timezone) }
javascript
function parse (dateString, locale, timezone) { _checkParams(locale, timezone) // list all available localized formats, from most specific to least return moment.tz(dateString, [moment.ISO_8601, 'llll', 'LLLL', 'lll', 'LLL', 'll', 'LL', 'l', 'L'], locale, timezone) }
[ "function", "parse", "(", "dateString", ",", "locale", ",", "timezone", ")", "{", "_checkParams", "(", "locale", ",", "timezone", ")", "// list all available localized formats, from most specific to least", "return", "moment", ".", "tz", "(", "dateString", ",", "[", "moment", ".", "ISO_8601", ",", "'llll'", ",", "'LLLL'", ",", "'lll'", ",", "'LLL'", ",", "'ll'", ",", "'LL'", ",", "'l'", ",", "'L'", "]", ",", "locale", ",", "timezone", ")", "}" ]
Parses a string into a localized ISO 8601 string with timezone @param {String} dateString @param {String} locale @param {String} timezone @returns {String} ISO 8601 string
[ "Parses", "a", "string", "into", "a", "localized", "ISO", "8601", "string", "with", "timezone" ]
7cee93b56f34679824b49d79e0d5821e4c9b5ea7
https://github.com/instructure/instructure-ui/blob/7cee93b56f34679824b49d79e0d5821e4c9b5ea7/packages/ui-i18n/src/DateTime.js#L53-L57
9,821
instructure/instructure-ui
packages/ui-themeable/src/mirrorShorthand.js
mirrorShorthandCorners
function mirrorShorthandCorners (values) { if (typeof values !== 'string') { return } const valuesArr = values.split(' ') if (valuesArr.length === 2) { // swap the 1st and 2nd values [ valuesArr[0], valuesArr[1] ] = [ valuesArr[1], valuesArr[0] ] } if (valuesArr.length === 3) { // convert 3 value syntax to 4 value syntax valuesArr.push(valuesArr[1]) } if (valuesArr.length === 4) { [ valuesArr[0], valuesArr[1], valuesArr[2], valuesArr[3] ] = [ valuesArr[1], valuesArr[0], valuesArr[3], valuesArr[2] ] } return valuesArr.join(' ') }
javascript
function mirrorShorthandCorners (values) { if (typeof values !== 'string') { return } const valuesArr = values.split(' ') if (valuesArr.length === 2) { // swap the 1st and 2nd values [ valuesArr[0], valuesArr[1] ] = [ valuesArr[1], valuesArr[0] ] } if (valuesArr.length === 3) { // convert 3 value syntax to 4 value syntax valuesArr.push(valuesArr[1]) } if (valuesArr.length === 4) { [ valuesArr[0], valuesArr[1], valuesArr[2], valuesArr[3] ] = [ valuesArr[1], valuesArr[0], valuesArr[3], valuesArr[2] ] } return valuesArr.join(' ') }
[ "function", "mirrorShorthandCorners", "(", "values", ")", "{", "if", "(", "typeof", "values", "!==", "'string'", ")", "{", "return", "}", "const", "valuesArr", "=", "values", ".", "split", "(", "' '", ")", "if", "(", "valuesArr", ".", "length", "===", "2", ")", "{", "// swap the 1st and 2nd values", "[", "valuesArr", "[", "0", "]", ",", "valuesArr", "[", "1", "]", "]", "=", "[", "valuesArr", "[", "1", "]", ",", "valuesArr", "[", "0", "]", "]", "}", "if", "(", "valuesArr", ".", "length", "===", "3", ")", "{", "// convert 3 value syntax to 4 value syntax", "valuesArr", ".", "push", "(", "valuesArr", "[", "1", "]", ")", "}", "if", "(", "valuesArr", ".", "length", "===", "4", ")", "{", "[", "valuesArr", "[", "0", "]", ",", "valuesArr", "[", "1", "]", ",", "valuesArr", "[", "2", "]", ",", "valuesArr", "[", "3", "]", "]", "=", "[", "valuesArr", "[", "1", "]", ",", "valuesArr", "[", "0", "]", ",", "valuesArr", "[", "3", "]", ",", "valuesArr", "[", "2", "]", "]", "}", "return", "valuesArr", ".", "join", "(", "' '", ")", "}" ]
Convert shorthand CSS properties for corners to rtl Given a string representing a CSS shorthand for corners, swaps the values such that 2,3 and 4 value syntax is rtl instead of ltr. See the following for further reference: https://developer.mozilla.org/en-US/docs/Web/CSS/Shorthand_properties @param {String} values - space delimited string values representing a CSS shorthand @returns {String} a space delimited CSS shorthand string converted to RTL
[ "Convert", "shorthand", "CSS", "properties", "for", "corners", "to", "rtl" ]
7cee93b56f34679824b49d79e0d5821e4c9b5ea7
https://github.com/instructure/instructure-ui/blob/7cee93b56f34679824b49d79e0d5821e4c9b5ea7/packages/ui-themeable/src/mirrorShorthand.js#L73-L96
9,822
instructure/instructure-ui
packages/ui-layout/src/mirrorPlacement.js
mirrorHorizontalPlacement
function mirrorHorizontalPlacement (placement, delimiter) { return executeMirrorFunction(placement, (first, second) => { return [first, second].map(value => { return (value === 'start' || value === 'end') ? mirror[value] : value }) }, delimiter) }
javascript
function mirrorHorizontalPlacement (placement, delimiter) { return executeMirrorFunction(placement, (first, second) => { return [first, second].map(value => { return (value === 'start' || value === 'end') ? mirror[value] : value }) }, delimiter) }
[ "function", "mirrorHorizontalPlacement", "(", "placement", ",", "delimiter", ")", "{", "return", "executeMirrorFunction", "(", "placement", ",", "(", "first", ",", "second", ")", "=>", "{", "return", "[", "first", ",", "second", "]", ".", "map", "(", "value", "=>", "{", "return", "(", "value", "===", "'start'", "||", "value", "===", "'end'", ")", "?", "mirror", "[", "value", "]", ":", "value", "}", ")", "}", ",", "delimiter", ")", "}" ]
Given a string or array of one or two placement values, mirrors the placement horizontally. Examples ```js mirrorHorizontalPlacement('top start') // input ['top', 'end'] // output mirrorPlacement('top start', ' ') // input 'top end' //output ``` @param {string|Array} placement - a string of the form '<value> <value>' or array [<value>, <value>] @param {string} delimiter - when provided, a value with which the result array will be joined @returns {string|Array} - an array of values or, if the delimiter was supplied, a string of delimiter separated values
[ "Given", "a", "string", "or", "array", "of", "one", "or", "two", "placement", "values", "mirrors", "the", "placement", "horizontally", "." ]
7cee93b56f34679824b49d79e0d5821e4c9b5ea7
https://github.com/instructure/instructure-ui/blob/7cee93b56f34679824b49d79e0d5821e4c9b5ea7/packages/ui-layout/src/mirrorPlacement.js#L80-L86
9,823
instructure/instructure-ui
packages/ui-react-utils/src/windowMessageListener.js
origin
function origin (node) { const ownWindow = ownerWindow(node) const { location } = ownWindow if (location.protocol === 'file:') { return '*' } else if (location.origin) { return location.origin } else if (location.port) { return `${location.protocol}//${location.hostname}:${location.port}` } else { return `${location.protocol}//${location.hostname}` } }
javascript
function origin (node) { const ownWindow = ownerWindow(node) const { location } = ownWindow if (location.protocol === 'file:') { return '*' } else if (location.origin) { return location.origin } else if (location.port) { return `${location.protocol}//${location.hostname}:${location.port}` } else { return `${location.protocol}//${location.hostname}` } }
[ "function", "origin", "(", "node", ")", "{", "const", "ownWindow", "=", "ownerWindow", "(", "node", ")", "const", "{", "location", "}", "=", "ownWindow", "if", "(", "location", ".", "protocol", "===", "'file:'", ")", "{", "return", "'*'", "}", "else", "if", "(", "location", ".", "origin", ")", "{", "return", "location", ".", "origin", "}", "else", "if", "(", "location", ".", "port", ")", "{", "return", "`", "${", "location", ".", "protocol", "}", "${", "location", ".", "hostname", "}", "${", "location", ".", "port", "}", "`", "}", "else", "{", "return", "`", "${", "location", ".", "protocol", "}", "${", "location", ".", "hostname", "}", "`", "}", "}" ]
Return the origin of the owner window of the DOM element see https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage @param {DOMElement} node @returns {String} the origin
[ "Return", "the", "origin", "of", "the", "owner", "window", "of", "the", "DOM", "element" ]
7cee93b56f34679824b49d79e0d5821e4c9b5ea7
https://github.com/instructure/instructure-ui/blob/7cee93b56f34679824b49d79e0d5821e4c9b5ea7/packages/ui-react-utils/src/windowMessageListener.js#L94-L109
9,824
instructure/instructure-ui
packages/ui-i18n/src/Decimal.js
_format
function _format (input, locale) { locale = locale || Locale.browserLocale() // eslint-disable-line no-param-reassign let result = input const { thousands, decimal } = Decimal.getDelimiters(locale) const isNegative = (result[0] === '-') // remove all characters except for digits and decimal delimiters result = result.replace(new RegExp(`[^\\d\\${decimal}]`, 'g'), '') // remove all decimal delimiters except for the last one if present result = result.replace(new RegExp(`[${decimal}](?=.*[${decimal}])`, 'g'), '') // remove the leading zeros using positive lookahead result = result.replace(new RegExp(`^[0${thousands}]+(?=\\d|0${decimal})`, ''), '') // add leading zero to decimal, if not present result = result.charAt(0) === decimal ? result.replace(/^/, '0') : result const parts = result.split(decimal) const thousandSections = [] let curr = parts[0] while (curr.length > 0) { thousandSections.unshift(curr.substr(Math.max(0, curr.length - 3), 3)) curr = curr.substr(0, curr.length - 3) } result = thousandSections.join(thousands) if (parts[1]) { result = `${result}${decimal}${parts[1]}` } if (isNegative && result) { result = `-${result}` } return result }
javascript
function _format (input, locale) { locale = locale || Locale.browserLocale() // eslint-disable-line no-param-reassign let result = input const { thousands, decimal } = Decimal.getDelimiters(locale) const isNegative = (result[0] === '-') // remove all characters except for digits and decimal delimiters result = result.replace(new RegExp(`[^\\d\\${decimal}]`, 'g'), '') // remove all decimal delimiters except for the last one if present result = result.replace(new RegExp(`[${decimal}](?=.*[${decimal}])`, 'g'), '') // remove the leading zeros using positive lookahead result = result.replace(new RegExp(`^[0${thousands}]+(?=\\d|0${decimal})`, ''), '') // add leading zero to decimal, if not present result = result.charAt(0) === decimal ? result.replace(/^/, '0') : result const parts = result.split(decimal) const thousandSections = [] let curr = parts[0] while (curr.length > 0) { thousandSections.unshift(curr.substr(Math.max(0, curr.length - 3), 3)) curr = curr.substr(0, curr.length - 3) } result = thousandSections.join(thousands) if (parts[1]) { result = `${result}${decimal}${parts[1]}` } if (isNegative && result) { result = `-${result}` } return result }
[ "function", "_format", "(", "input", ",", "locale", ")", "{", "locale", "=", "locale", "||", "Locale", ".", "browserLocale", "(", ")", "// eslint-disable-line no-param-reassign", "let", "result", "=", "input", "const", "{", "thousands", ",", "decimal", "}", "=", "Decimal", ".", "getDelimiters", "(", "locale", ")", "const", "isNegative", "=", "(", "result", "[", "0", "]", "===", "'-'", ")", "// remove all characters except for digits and decimal delimiters", "result", "=", "result", ".", "replace", "(", "new", "RegExp", "(", "`", "\\\\", "\\\\", "${", "decimal", "}", "`", ",", "'g'", ")", ",", "''", ")", "// remove all decimal delimiters except for the last one if present", "result", "=", "result", ".", "replace", "(", "new", "RegExp", "(", "`", "${", "decimal", "}", "${", "decimal", "}", "`", ",", "'g'", ")", ",", "''", ")", "// remove the leading zeros using positive lookahead", "result", "=", "result", ".", "replace", "(", "new", "RegExp", "(", "`", "${", "thousands", "}", "\\\\", "${", "decimal", "}", "`", ",", "''", ")", ",", "''", ")", "// add leading zero to decimal, if not present", "result", "=", "result", ".", "charAt", "(", "0", ")", "===", "decimal", "?", "result", ".", "replace", "(", "/", "^", "/", ",", "'0'", ")", ":", "result", "const", "parts", "=", "result", ".", "split", "(", "decimal", ")", "const", "thousandSections", "=", "[", "]", "let", "curr", "=", "parts", "[", "0", "]", "while", "(", "curr", ".", "length", ">", "0", ")", "{", "thousandSections", ".", "unshift", "(", "curr", ".", "substr", "(", "Math", ".", "max", "(", "0", ",", "curr", ".", "length", "-", "3", ")", ",", "3", ")", ")", "curr", "=", "curr", ".", "substr", "(", "0", ",", "curr", ".", "length", "-", "3", ")", "}", "result", "=", "thousandSections", ".", "join", "(", "thousands", ")", "if", "(", "parts", "[", "1", "]", ")", "{", "result", "=", "`", "${", "result", "}", "${", "decimal", "}", "${", "parts", "[", "1", "]", "}", "`", "}", "if", "(", "isNegative", "&&", "result", ")", "{", "result", "=", "`", "${", "result", "}", "`", "}", "return", "result", "}" ]
Cleans up the string given and applies the thousands delimiter Doesn't take into account chinese and indian locales with non-standard grouping This will be addressed in INSTUI-996
[ "Cleans", "up", "the", "string", "given", "and", "applies", "the", "thousands", "delimiter", "Doesn", "t", "take", "into", "account", "chinese", "and", "indian", "locales", "with", "non", "-", "standard", "grouping", "This", "will", "be", "addressed", "in", "INSTUI", "-", "996" ]
7cee93b56f34679824b49d79e0d5821e4c9b5ea7
https://github.com/instructure/instructure-ui/blob/7cee93b56f34679824b49d79e0d5821e4c9b5ea7/packages/ui-i18n/src/Decimal.js#L138-L178
9,825
instructure/instructure-ui
packages/ui-themeable/src/scopeStylesToNode.js
scopeCssText
function scopeCssText (cssText, scope) { return transformCss(cssText, (rule) => { const transformed = {...rule} if (!rule.isScoped) { transformed.selector = scopeRule(rule, scope) transformed.isScoped = true } return transformed }) }
javascript
function scopeCssText (cssText, scope) { return transformCss(cssText, (rule) => { const transformed = {...rule} if (!rule.isScoped) { transformed.selector = scopeRule(rule, scope) transformed.isScoped = true } return transformed }) }
[ "function", "scopeCssText", "(", "cssText", ",", "scope", ")", "{", "return", "transformCss", "(", "cssText", ",", "(", "rule", ")", "=>", "{", "const", "transformed", "=", "{", "...", "rule", "}", "if", "(", "!", "rule", ".", "isScoped", ")", "{", "transformed", ".", "selector", "=", "scopeRule", "(", "rule", ",", "scope", ")", "transformed", ".", "isScoped", "=", "true", "}", "return", "transformed", "}", ")", "}" ]
Transforms a CSS string to add a scoping selector to each rule @param {String} cssText @param {String} scope a unique identifier to use to scope the styles
[ "Transforms", "a", "CSS", "string", "to", "add", "a", "scoping", "selector", "to", "each", "rule" ]
7cee93b56f34679824b49d79e0d5821e4c9b5ea7
https://github.com/instructure/instructure-ui/blob/7cee93b56f34679824b49d79e0d5821e4c9b5ea7/packages/ui-themeable/src/scopeStylesToNode.js#L82-L91
9,826
saebekassebil/teoria
lib/note.js
function(oneaccidental) { var key = this.key(), limit = oneaccidental ? 2 : 3; return ['m3', 'm2', 'm-2', 'm-3'] .map(this.interval.bind(this)) .filter(function(note) { var acc = note.accidentalValue(); var diff = key - (note.key() - acc); if (diff < limit && diff > -limit) { var product = vector.mul(knowledge.sharp, diff - acc); note.coord = vector.add(note.coord, product); return true; } }); }
javascript
function(oneaccidental) { var key = this.key(), limit = oneaccidental ? 2 : 3; return ['m3', 'm2', 'm-2', 'm-3'] .map(this.interval.bind(this)) .filter(function(note) { var acc = note.accidentalValue(); var diff = key - (note.key() - acc); if (diff < limit && diff > -limit) { var product = vector.mul(knowledge.sharp, diff - acc); note.coord = vector.add(note.coord, product); return true; } }); }
[ "function", "(", "oneaccidental", ")", "{", "var", "key", "=", "this", ".", "key", "(", ")", ",", "limit", "=", "oneaccidental", "?", "2", ":", "3", ";", "return", "[", "'m3'", ",", "'m2'", ",", "'m-2'", ",", "'m-3'", "]", ".", "map", "(", "this", ".", "interval", ".", "bind", "(", "this", ")", ")", ".", "filter", "(", "function", "(", "note", ")", "{", "var", "acc", "=", "note", ".", "accidentalValue", "(", ")", ";", "var", "diff", "=", "key", "-", "(", "note", ".", "key", "(", ")", "-", "acc", ")", ";", "if", "(", "diff", "<", "limit", "&&", "diff", ">", "-", "limit", ")", "{", "var", "product", "=", "vector", ".", "mul", "(", "knowledge", ".", "sharp", ",", "diff", "-", "acc", ")", ";", "note", ".", "coord", "=", "vector", ".", "add", "(", "note", ".", "coord", ",", "product", ")", ";", "return", "true", ";", "}", "}", ")", ";", "}" ]
Returns notes that are enharmonic with this note.
[ "Returns", "notes", "that", "are", "enharmonic", "with", "this", "note", "." ]
0f4bbe8fb0d6a43fd9c96a309ce781c3841114d2
https://github.com/saebekassebil/teoria/blob/0f4bbe8fb0d6a43fd9c96a309ce781c3841114d2/lib/note.js#L116-L131
9,827
aliyun/aliyun-tablestore-nodejs-sdk
lib/config.js
set
function set(property, value, defaultValue) { if (value === undefined) { if (defaultValue === undefined) { defaultValue = this.keys[property]; } if (typeof defaultValue === 'function') { this[property] = defaultValue.call(this); } else { this[property] = defaultValue; } } else { this[property] = value; } }
javascript
function set(property, value, defaultValue) { if (value === undefined) { if (defaultValue === undefined) { defaultValue = this.keys[property]; } if (typeof defaultValue === 'function') { this[property] = defaultValue.call(this); } else { this[property] = defaultValue; } } else { this[property] = value; } }
[ "function", "set", "(", "property", ",", "value", ",", "defaultValue", ")", "{", "if", "(", "value", "===", "undefined", ")", "{", "if", "(", "defaultValue", "===", "undefined", ")", "{", "defaultValue", "=", "this", ".", "keys", "[", "property", "]", ";", "}", "if", "(", "typeof", "defaultValue", "===", "'function'", ")", "{", "this", "[", "property", "]", "=", "defaultValue", ".", "call", "(", "this", ")", ";", "}", "else", "{", "this", "[", "property", "]", "=", "defaultValue", ";", "}", "}", "else", "{", "this", "[", "property", "]", "=", "value", ";", "}", "}" ]
Sets a property on the configuration object, allowing for a default value @api private
[ "Sets", "a", "property", "on", "the", "configuration", "object", "allowing", "for", "a", "default", "value" ]
33cb123d8e5b3e79fbad3cb13f7bed7b2361b620
https://github.com/aliyun/aliyun-tablestore-nodejs-sdk/blob/33cb123d8e5b3e79fbad3cb13f7bed7b2361b620/lib/config.js#L41-L54
9,828
aliyun/aliyun-tablestore-nodejs-sdk
lib/util-browser.js
function (buffers) { var length = 0, offset = 0, buffer = null, i; for (i = 0; i < buffers.length; i++) { length += buffers[i].length; } buffer = new TableStore.util.Buffer(length); for (i = 0; i < buffers.length; i++) { buffers[i].copy(buffer, offset); offset += buffers[i].length; } return buffer; }
javascript
function (buffers) { var length = 0, offset = 0, buffer = null, i; for (i = 0; i < buffers.length; i++) { length += buffers[i].length; } buffer = new TableStore.util.Buffer(length); for (i = 0; i < buffers.length; i++) { buffers[i].copy(buffer, offset); offset += buffers[i].length; } return buffer; }
[ "function", "(", "buffers", ")", "{", "var", "length", "=", "0", ",", "offset", "=", "0", ",", "buffer", "=", "null", ",", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "buffers", ".", "length", ";", "i", "++", ")", "{", "length", "+=", "buffers", "[", "i", "]", ".", "length", ";", "}", "buffer", "=", "new", "TableStore", ".", "util", ".", "Buffer", "(", "length", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "buffers", ".", "length", ";", "i", "++", ")", "{", "buffers", "[", "i", "]", ".", "copy", "(", "buffer", ",", "offset", ")", ";", "offset", "+=", "buffers", "[", "i", "]", ".", "length", ";", "}", "return", "buffer", ";", "}" ]
Concatenates a list of Buffer objects.
[ "Concatenates", "a", "list", "of", "Buffer", "objects", "." ]
33cb123d8e5b3e79fbad3cb13f7bed7b2361b620
https://github.com/aliyun/aliyun-tablestore-nodejs-sdk/blob/33cb123d8e5b3e79fbad3cb13f7bed7b2361b620/lib/util-browser.js#L199-L216
9,829
aliyun/aliyun-tablestore-nodejs-sdk
lib/util-browser.js
top
function top(date, fmt) { fmt = fmt || '%Y-%M-%dT%H:%m:%sZ'; function pad(value) { return (value.toString().length < 2) ? '0' + value : value; }; return fmt.replace(/%([a-zA-Z])/g, function (_, fmtCode) { switch (fmtCode) { case 'Y': return date.getUTCFullYear(); case 'M': return pad(date.getUTCMonth() + 1); case 'd': return pad(date.getUTCDate()); case 'H': return pad(date.getUTCHours()); case 'm': return pad(date.getUTCMinutes()); case 's': return pad(date.getUTCSeconds()); default: throw new Error('Unsupported format code: ' + fmtCode); } }); }
javascript
function top(date, fmt) { fmt = fmt || '%Y-%M-%dT%H:%m:%sZ'; function pad(value) { return (value.toString().length < 2) ? '0' + value : value; }; return fmt.replace(/%([a-zA-Z])/g, function (_, fmtCode) { switch (fmtCode) { case 'Y': return date.getUTCFullYear(); case 'M': return pad(date.getUTCMonth() + 1); case 'd': return pad(date.getUTCDate()); case 'H': return pad(date.getUTCHours()); case 'm': return pad(date.getUTCMinutes()); case 's': return pad(date.getUTCSeconds()); default: throw new Error('Unsupported format code: ' + fmtCode); } }); }
[ "function", "top", "(", "date", ",", "fmt", ")", "{", "fmt", "=", "fmt", "||", "'%Y-%M-%dT%H:%m:%sZ'", ";", "function", "pad", "(", "value", ")", "{", "return", "(", "value", ".", "toString", "(", ")", ".", "length", "<", "2", ")", "?", "'0'", "+", "value", ":", "value", ";", "}", ";", "return", "fmt", ".", "replace", "(", "/", "%([a-zA-Z])", "/", "g", ",", "function", "(", "_", ",", "fmtCode", ")", "{", "switch", "(", "fmtCode", ")", "{", "case", "'Y'", ":", "return", "date", ".", "getUTCFullYear", "(", ")", ";", "case", "'M'", ":", "return", "pad", "(", "date", ".", "getUTCMonth", "(", ")", "+", "1", ")", ";", "case", "'d'", ":", "return", "pad", "(", "date", ".", "getUTCDate", "(", ")", ")", ";", "case", "'H'", ":", "return", "pad", "(", "date", ".", "getUTCHours", "(", ")", ")", ";", "case", "'m'", ":", "return", "pad", "(", "date", ".", "getUTCMinutes", "(", ")", ")", ";", "case", "'s'", ":", "return", "pad", "(", "date", ".", "getUTCSeconds", "(", ")", ")", ";", "default", ":", "throw", "new", "Error", "(", "'Unsupported format code: '", "+", "fmtCode", ")", ";", "}", "}", ")", ";", "}" ]
for taobao open platform
[ "for", "taobao", "open", "platform" ]
33cb123d8e5b3e79fbad3cb13f7bed7b2361b620
https://github.com/aliyun/aliyun-tablestore-nodejs-sdk/blob/33cb123d8e5b3e79fbad3cb13f7bed7b2361b620/lib/util-browser.js#L329-L354
9,830
aliyun/aliyun-tablestore-nodejs-sdk
lib/util-browser.js
format
function format(date, formatter) { if (!formatter) formatter = 'unixSeconds'; return TableStore.util.date[formatter](TableStore.util.date.from(date)); }
javascript
function format(date, formatter) { if (!formatter) formatter = 'unixSeconds'; return TableStore.util.date[formatter](TableStore.util.date.from(date)); }
[ "function", "format", "(", "date", ",", "formatter", ")", "{", "if", "(", "!", "formatter", ")", "formatter", "=", "'unixSeconds'", ";", "return", "TableStore", ".", "util", ".", "date", "[", "formatter", "]", "(", "TableStore", ".", "util", ".", "date", ".", "from", "(", "date", ")", ")", ";", "}" ]
Given a Date or date-like value, this function formats the date into a string of the requested value. @param [String,number,Date] date @param [String] formatter Valid formats are: # * 'iso8601' # * 'rfc822' # * 'unixSeconds' # * 'unixMilliseconds' @return [String]
[ "Given", "a", "Date", "or", "date", "-", "like", "value", "this", "function", "formats", "the", "date", "into", "a", "string", "of", "the", "requested", "value", "." ]
33cb123d8e5b3e79fbad3cb13f7bed7b2361b620
https://github.com/aliyun/aliyun-tablestore-nodejs-sdk/blob/33cb123d8e5b3e79fbad3cb13f7bed7b2361b620/lib/util-browser.js#L412-L415
9,831
aliyun/aliyun-tablestore-nodejs-sdk
lib/request.js
Request
function Request(config, operation, params) { var endpoint = new TableStore.Endpoint(config.endpoint); var region = config.region; this.config = config; if (config.maxRetries !== undefined) { TableStore.DefaultRetryPolicy.maxRetryTimes = config.maxRetries; } //如果在sdk外部包装了一层domain,就把它传到this.domain this.domain = domain && domain.active; this.operation = operation; this.params = params || {}; this.httpRequest = new TableStore.HttpRequest(endpoint, region); this.startTime = TableStore.util.date.getDate(); this.response = new TableStore.Response(this); this.restartCount = 0; this._asm = new AcceptorStateMachine(fsm.states, 'build'); TableStore.SequentialExecutor.call(this); this.emit = this.emitEvent; }
javascript
function Request(config, operation, params) { var endpoint = new TableStore.Endpoint(config.endpoint); var region = config.region; this.config = config; if (config.maxRetries !== undefined) { TableStore.DefaultRetryPolicy.maxRetryTimes = config.maxRetries; } //如果在sdk外部包装了一层domain,就把它传到this.domain this.domain = domain && domain.active; this.operation = operation; this.params = params || {}; this.httpRequest = new TableStore.HttpRequest(endpoint, region); this.startTime = TableStore.util.date.getDate(); this.response = new TableStore.Response(this); this.restartCount = 0; this._asm = new AcceptorStateMachine(fsm.states, 'build'); TableStore.SequentialExecutor.call(this); this.emit = this.emitEvent; }
[ "function", "Request", "(", "config", ",", "operation", ",", "params", ")", "{", "var", "endpoint", "=", "new", "TableStore", ".", "Endpoint", "(", "config", ".", "endpoint", ")", ";", "var", "region", "=", "config", ".", "region", ";", "this", ".", "config", "=", "config", ";", "if", "(", "config", ".", "maxRetries", "!==", "undefined", ")", "{", "TableStore", ".", "DefaultRetryPolicy", ".", "maxRetryTimes", "=", "config", ".", "maxRetries", ";", "}", "//如果在sdk外部包装了一层domain,就把它传到this.domain", "this", ".", "domain", "=", "domain", "&&", "domain", ".", "active", ";", "this", ".", "operation", "=", "operation", ";", "this", ".", "params", "=", "params", "||", "{", "}", ";", "this", ".", "httpRequest", "=", "new", "TableStore", ".", "HttpRequest", "(", "endpoint", ",", "region", ")", ";", "this", ".", "startTime", "=", "TableStore", ".", "util", ".", "date", ".", "getDate", "(", ")", ";", "this", ".", "response", "=", "new", "TableStore", ".", "Response", "(", "this", ")", ";", "this", ".", "restartCount", "=", "0", ";", "this", ".", "_asm", "=", "new", "AcceptorStateMachine", "(", "fsm", ".", "states", ",", "'build'", ")", ";", "TableStore", ".", "SequentialExecutor", ".", "call", "(", "this", ")", ";", "this", ".", "emit", "=", "this", ".", "emitEvent", ";", "}" ]
Creates a request for an operation on a given service with a set of input parameters. @param config [TableStore.Config] the config to perform the operation on @param operation [String] the operation to perform on the service @param params [Object] parameters to send to the operation. See the operation's documentation for the format of the parameters.
[ "Creates", "a", "request", "for", "an", "operation", "on", "a", "given", "service", "with", "a", "set", "of", "input", "parameters", "." ]
33cb123d8e5b3e79fbad3cb13f7bed7b2361b620
https://github.com/aliyun/aliyun-tablestore-nodejs-sdk/blob/33cb123d8e5b3e79fbad3cb13f7bed7b2361b620/lib/request.js#L118-L138
9,832
keeweb/kdbxweb
lib/format/kdbx-uuid.js
KdbxUuid
function KdbxUuid(ab) { if (ab === undefined) { ab = new ArrayBuffer(UuidLength); } if (typeof ab === 'string') { ab = ByteUtils.base64ToBytes(ab); } this.id = ab.byteLength === 16 ? ByteUtils.bytesToBase64(ab) : undefined; this.empty = true; if (ab) { var bytes = new Uint8Array(ab); for (var i = 0, len = bytes.length; i < len; i++) { if (bytes[i] !== 0) { this.empty = false; return; } } } }
javascript
function KdbxUuid(ab) { if (ab === undefined) { ab = new ArrayBuffer(UuidLength); } if (typeof ab === 'string') { ab = ByteUtils.base64ToBytes(ab); } this.id = ab.byteLength === 16 ? ByteUtils.bytesToBase64(ab) : undefined; this.empty = true; if (ab) { var bytes = new Uint8Array(ab); for (var i = 0, len = bytes.length; i < len; i++) { if (bytes[i] !== 0) { this.empty = false; return; } } } }
[ "function", "KdbxUuid", "(", "ab", ")", "{", "if", "(", "ab", "===", "undefined", ")", "{", "ab", "=", "new", "ArrayBuffer", "(", "UuidLength", ")", ";", "}", "if", "(", "typeof", "ab", "===", "'string'", ")", "{", "ab", "=", "ByteUtils", ".", "base64ToBytes", "(", "ab", ")", ";", "}", "this", ".", "id", "=", "ab", ".", "byteLength", "===", "16", "?", "ByteUtils", ".", "bytesToBase64", "(", "ab", ")", ":", "undefined", ";", "this", ".", "empty", "=", "true", ";", "if", "(", "ab", ")", "{", "var", "bytes", "=", "new", "Uint8Array", "(", "ab", ")", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "bytes", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "bytes", "[", "i", "]", "!==", "0", ")", "{", "this", ".", "empty", "=", "false", ";", "return", ";", "}", "}", "}", "}" ]
Uuid for passwords @param {ArrayBuffer|string} ab - ArrayBuffer with data @constructor
[ "Uuid", "for", "passwords" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/format/kdbx-uuid.js#L13-L31
9,833
keeweb/kdbxweb
lib/utils/binary-stream.js
BinaryStream
function BinaryStream(arrayBuffer) { this._arrayBuffer = arrayBuffer || new ArrayBuffer(1024); this._dataView = new DataView(this._arrayBuffer); this._pos = 0; this._canExpand = !arrayBuffer; }
javascript
function BinaryStream(arrayBuffer) { this._arrayBuffer = arrayBuffer || new ArrayBuffer(1024); this._dataView = new DataView(this._arrayBuffer); this._pos = 0; this._canExpand = !arrayBuffer; }
[ "function", "BinaryStream", "(", "arrayBuffer", ")", "{", "this", ".", "_arrayBuffer", "=", "arrayBuffer", "||", "new", "ArrayBuffer", "(", "1024", ")", ";", "this", ".", "_dataView", "=", "new", "DataView", "(", "this", ".", "_arrayBuffer", ")", ";", "this", ".", "_pos", "=", "0", ";", "this", ".", "_canExpand", "=", "!", "arrayBuffer", ";", "}" ]
Stream for accessing array buffer with auto-advanced position @param {ArrayBuffer} [arrayBuffer] @constructor
[ "Stream", "for", "accessing", "array", "buffer", "with", "auto", "-", "advanced", "position" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/binary-stream.js#L8-L13
9,834
keeweb/kdbxweb
lib/crypto/random.js
getBytes
function getBytes(len) { if (!len) { return new Uint8Array(0); } algo.getBytes(Math.round(Math.random() * len) + 1); var result = algo.getBytes(len); var cryptoBytes = CryptoEngine.random(len); for (var i = cryptoBytes.length - 1; i >= 0; --i) { result[i] ^= cryptoBytes[i]; } return result; }
javascript
function getBytes(len) { if (!len) { return new Uint8Array(0); } algo.getBytes(Math.round(Math.random() * len) + 1); var result = algo.getBytes(len); var cryptoBytes = CryptoEngine.random(len); for (var i = cryptoBytes.length - 1; i >= 0; --i) { result[i] ^= cryptoBytes[i]; } return result; }
[ "function", "getBytes", "(", "len", ")", "{", "if", "(", "!", "len", ")", "{", "return", "new", "Uint8Array", "(", "0", ")", ";", "}", "algo", ".", "getBytes", "(", "Math", ".", "round", "(", "Math", ".", "random", "(", ")", "*", "len", ")", "+", "1", ")", ";", "var", "result", "=", "algo", ".", "getBytes", "(", "len", ")", ";", "var", "cryptoBytes", "=", "CryptoEngine", ".", "random", "(", "len", ")", ";", "for", "(", "var", "i", "=", "cryptoBytes", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "--", "i", ")", "{", "result", "[", "i", "]", "^=", "cryptoBytes", "[", "i", "]", ";", "}", "return", "result", ";", "}" ]
Gets random bytes @param {number} len - bytes count @return {Uint8Array} - random bytes
[ "Gets", "random", "bytes" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/crypto/random.js#L20-L31
9,835
keeweb/kdbxweb
lib/crypto/key-encryptor-kdf.js
encrypt
function encrypt(key, kdfParams) { var uuid = kdfParams.get('$UUID'); if (!uuid || !(uuid instanceof ArrayBuffer)) { return Promise.reject(new KdbxError(Consts.ErrorCodes.FileCorrupt, 'no kdf uuid')); } var kdfUuid = ByteUtils.bytesToBase64(uuid); switch (kdfUuid) { case Consts.KdfId.Argon2: return encryptArgon2(key, kdfParams); case Consts.KdfId.Aes: return encryptAes(key, kdfParams); default: return Promise.reject(new KdbxError(Consts.ErrorCodes.Unsupported, 'bad kdf')); } }
javascript
function encrypt(key, kdfParams) { var uuid = kdfParams.get('$UUID'); if (!uuid || !(uuid instanceof ArrayBuffer)) { return Promise.reject(new KdbxError(Consts.ErrorCodes.FileCorrupt, 'no kdf uuid')); } var kdfUuid = ByteUtils.bytesToBase64(uuid); switch (kdfUuid) { case Consts.KdfId.Argon2: return encryptArgon2(key, kdfParams); case Consts.KdfId.Aes: return encryptAes(key, kdfParams); default: return Promise.reject(new KdbxError(Consts.ErrorCodes.Unsupported, 'bad kdf')); } }
[ "function", "encrypt", "(", "key", ",", "kdfParams", ")", "{", "var", "uuid", "=", "kdfParams", ".", "get", "(", "'$UUID'", ")", ";", "if", "(", "!", "uuid", "||", "!", "(", "uuid", "instanceof", "ArrayBuffer", ")", ")", "{", "return", "Promise", ".", "reject", "(", "new", "KdbxError", "(", "Consts", ".", "ErrorCodes", ".", "FileCorrupt", ",", "'no kdf uuid'", ")", ")", ";", "}", "var", "kdfUuid", "=", "ByteUtils", ".", "bytesToBase64", "(", "uuid", ")", ";", "switch", "(", "kdfUuid", ")", "{", "case", "Consts", ".", "KdfId", ".", "Argon2", ":", "return", "encryptArgon2", "(", "key", ",", "kdfParams", ")", ";", "case", "Consts", ".", "KdfId", ".", "Aes", ":", "return", "encryptAes", "(", "key", ",", "kdfParams", ")", ";", "default", ":", "return", "Promise", ".", "reject", "(", "new", "KdbxError", "(", "Consts", ".", "ErrorCodes", ".", "Unsupported", ",", "'bad kdf'", ")", ")", ";", "}", "}" ]
Derives key from seed using KDF parameters @param {ArrayBuffer} key @param {VarDictionary} kdfParams
[ "Derives", "key", "from", "seed", "using", "KDF", "parameters" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/crypto/key-encryptor-kdf.js#L27-L41
9,836
keeweb/kdbxweb
lib/utils/byte-utils.js
arrayBufferEquals
function arrayBufferEquals(ab1, ab2) { if (ab1.byteLength !== ab2.byteLength) { return false; } var arr1 = new Uint8Array(ab1); var arr2 = new Uint8Array(ab2); for (var i = 0, len = arr1.length; i < len; i++) { if (arr1[i] !== arr2[i]) { return false; } } return true; }
javascript
function arrayBufferEquals(ab1, ab2) { if (ab1.byteLength !== ab2.byteLength) { return false; } var arr1 = new Uint8Array(ab1); var arr2 = new Uint8Array(ab2); for (var i = 0, len = arr1.length; i < len; i++) { if (arr1[i] !== arr2[i]) { return false; } } return true; }
[ "function", "arrayBufferEquals", "(", "ab1", ",", "ab2", ")", "{", "if", "(", "ab1", ".", "byteLength", "!==", "ab2", ".", "byteLength", ")", "{", "return", "false", ";", "}", "var", "arr1", "=", "new", "Uint8Array", "(", "ab1", ")", ";", "var", "arr2", "=", "new", "Uint8Array", "(", "ab2", ")", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "arr1", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "arr1", "[", "i", "]", "!==", "arr2", "[", "i", "]", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Checks if two ArrayBuffers are equal @param {ArrayBuffer} ab1 @param {ArrayBuffer} ab2 @returns {boolean}
[ "Checks", "if", "two", "ArrayBuffers", "are", "equal" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/byte-utils.js#L21-L33
9,837
keeweb/kdbxweb
lib/utils/byte-utils.js
bytesToString
function bytesToString(arr) { if (arr instanceof ArrayBuffer) { arr = new Uint8Array(arr); } return textDecoder.decode(arr); }
javascript
function bytesToString(arr) { if (arr instanceof ArrayBuffer) { arr = new Uint8Array(arr); } return textDecoder.decode(arr); }
[ "function", "bytesToString", "(", "arr", ")", "{", "if", "(", "arr", "instanceof", "ArrayBuffer", ")", "{", "arr", "=", "new", "Uint8Array", "(", "arr", ")", ";", "}", "return", "textDecoder", ".", "decode", "(", "arr", ")", ";", "}" ]
Converts Array or ArrayBuffer to string @param {Array|Uint8Array|ArrayBuffer} arr @return {string}
[ "Converts", "Array", "or", "ArrayBuffer", "to", "string" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/byte-utils.js#L40-L45
9,838
keeweb/kdbxweb
lib/utils/byte-utils.js
base64ToBytes
function base64ToBytes(str) { if (typeof atob === 'undefined' && typeof Buffer === 'function') { // node.js doesn't have atob var buffer = Buffer.from(str, 'base64'); return new Uint8Array(buffer); } var byteStr = atob(str); var arr = new Uint8Array(byteStr.length); for (var i = 0; i < byteStr.length; i++) { arr[i] = byteStr.charCodeAt(i); } return arr; }
javascript
function base64ToBytes(str) { if (typeof atob === 'undefined' && typeof Buffer === 'function') { // node.js doesn't have atob var buffer = Buffer.from(str, 'base64'); return new Uint8Array(buffer); } var byteStr = atob(str); var arr = new Uint8Array(byteStr.length); for (var i = 0; i < byteStr.length; i++) { arr[i] = byteStr.charCodeAt(i); } return arr; }
[ "function", "base64ToBytes", "(", "str", ")", "{", "if", "(", "typeof", "atob", "===", "'undefined'", "&&", "typeof", "Buffer", "===", "'function'", ")", "{", "// node.js doesn't have atob", "var", "buffer", "=", "Buffer", ".", "from", "(", "str", ",", "'base64'", ")", ";", "return", "new", "Uint8Array", "(", "buffer", ")", ";", "}", "var", "byteStr", "=", "atob", "(", "str", ")", ";", "var", "arr", "=", "new", "Uint8Array", "(", "byteStr", ".", "length", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "byteStr", ".", "length", ";", "i", "++", ")", "{", "arr", "[", "i", "]", "=", "byteStr", ".", "charCodeAt", "(", "i", ")", ";", "}", "return", "arr", ";", "}" ]
Converts base64 string to array @param {string} str @return {Uint8Array}
[ "Converts", "base64", "string", "to", "array" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/byte-utils.js#L61-L73
9,839
keeweb/kdbxweb
lib/utils/byte-utils.js
bytesToBase64
function bytesToBase64(arr) { if (arr instanceof ArrayBuffer) { arr = new Uint8Array(arr); } if (typeof btoa === 'undefined' && typeof Buffer === 'function') { // node.js doesn't have btoa var buffer = Buffer.from(arr); return buffer.toString('base64'); } var str = ''; for (var i = 0; i < arr.length; i++) { str += String.fromCharCode(arr[i]); } return btoa(str); }
javascript
function bytesToBase64(arr) { if (arr instanceof ArrayBuffer) { arr = new Uint8Array(arr); } if (typeof btoa === 'undefined' && typeof Buffer === 'function') { // node.js doesn't have btoa var buffer = Buffer.from(arr); return buffer.toString('base64'); } var str = ''; for (var i = 0; i < arr.length; i++) { str += String.fromCharCode(arr[i]); } return btoa(str); }
[ "function", "bytesToBase64", "(", "arr", ")", "{", "if", "(", "arr", "instanceof", "ArrayBuffer", ")", "{", "arr", "=", "new", "Uint8Array", "(", "arr", ")", ";", "}", "if", "(", "typeof", "btoa", "===", "'undefined'", "&&", "typeof", "Buffer", "===", "'function'", ")", "{", "// node.js doesn't have btoa", "var", "buffer", "=", "Buffer", ".", "from", "(", "arr", ")", ";", "return", "buffer", ".", "toString", "(", "'base64'", ")", ";", "}", "var", "str", "=", "''", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arr", ".", "length", ";", "i", "++", ")", "{", "str", "+=", "String", ".", "fromCharCode", "(", "arr", "[", "i", "]", ")", ";", "}", "return", "btoa", "(", "str", ")", ";", "}" ]
Converts Array or ArrayBuffer to base64-string @param {Array|Uint8Array|ArrayBuffer} arr @return {string}
[ "Converts", "Array", "or", "ArrayBuffer", "to", "base64", "-", "string" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/byte-utils.js#L80-L94
9,840
keeweb/kdbxweb
lib/utils/byte-utils.js
arrayToBuffer
function arrayToBuffer(arr) { if (arr instanceof ArrayBuffer) { return arr; } var ab = arr.buffer; if (arr.byteOffset === 0 && arr.byteLength === ab.byteLength) { return ab; } return arr.buffer.slice(arr.byteOffset, arr.byteOffset + arr.byteLength); }
javascript
function arrayToBuffer(arr) { if (arr instanceof ArrayBuffer) { return arr; } var ab = arr.buffer; if (arr.byteOffset === 0 && arr.byteLength === ab.byteLength) { return ab; } return arr.buffer.slice(arr.byteOffset, arr.byteOffset + arr.byteLength); }
[ "function", "arrayToBuffer", "(", "arr", ")", "{", "if", "(", "arr", "instanceof", "ArrayBuffer", ")", "{", "return", "arr", ";", "}", "var", "ab", "=", "arr", ".", "buffer", ";", "if", "(", "arr", ".", "byteOffset", "===", "0", "&&", "arr", ".", "byteLength", "===", "ab", ".", "byteLength", ")", "{", "return", "ab", ";", "}", "return", "arr", ".", "buffer", ".", "slice", "(", "arr", ".", "byteOffset", ",", "arr", ".", "byteOffset", "+", "arr", ".", "byteLength", ")", ";", "}" ]
Converts byte array to array buffer @param {Uint8Array|ArrayBuffer} arr @returns {ArrayBuffer}
[ "Converts", "byte", "array", "to", "array", "buffer" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/byte-utils.js#L134-L143
9,841
keeweb/kdbxweb
lib/crypto/crypto-engine.js
sha256
function sha256(data) { if (!data.byteLength) { return Promise.resolve(ByteUtils.arrayToBuffer(ByteUtils.hexToBytes(EmptySha256))); } if (subtle) { return subtle.digest({ name: 'SHA-256' }, data); } else if (nodeCrypto) { return new Promise(function(resolve) { var sha = nodeCrypto.createHash('sha256'); var hash = sha.update(Buffer.from(data)).digest(); resolve(hash.buffer); }); } else { return Promise.reject(new KdbxError(Consts.ErrorCodes.NotImplemented, 'SHA256 not implemented')); } }
javascript
function sha256(data) { if (!data.byteLength) { return Promise.resolve(ByteUtils.arrayToBuffer(ByteUtils.hexToBytes(EmptySha256))); } if (subtle) { return subtle.digest({ name: 'SHA-256' }, data); } else if (nodeCrypto) { return new Promise(function(resolve) { var sha = nodeCrypto.createHash('sha256'); var hash = sha.update(Buffer.from(data)).digest(); resolve(hash.buffer); }); } else { return Promise.reject(new KdbxError(Consts.ErrorCodes.NotImplemented, 'SHA256 not implemented')); } }
[ "function", "sha256", "(", "data", ")", "{", "if", "(", "!", "data", ".", "byteLength", ")", "{", "return", "Promise", ".", "resolve", "(", "ByteUtils", ".", "arrayToBuffer", "(", "ByteUtils", ".", "hexToBytes", "(", "EmptySha256", ")", ")", ")", ";", "}", "if", "(", "subtle", ")", "{", "return", "subtle", ".", "digest", "(", "{", "name", ":", "'SHA-256'", "}", ",", "data", ")", ";", "}", "else", "if", "(", "nodeCrypto", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "var", "sha", "=", "nodeCrypto", ".", "createHash", "(", "'sha256'", ")", ";", "var", "hash", "=", "sha", ".", "update", "(", "Buffer", ".", "from", "(", "data", ")", ")", ".", "digest", "(", ")", ";", "resolve", "(", "hash", ".", "buffer", ")", ";", "}", ")", ";", "}", "else", "{", "return", "Promise", ".", "reject", "(", "new", "KdbxError", "(", "Consts", ".", "ErrorCodes", ".", "NotImplemented", ",", "'SHA256 not implemented'", ")", ")", ";", "}", "}" ]
SHA-256 hash @param {ArrayBuffer} data @returns {Promise.<ArrayBuffer>}
[ "SHA", "-", "256", "hash" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/crypto/crypto-engine.js#L25-L40
9,842
keeweb/kdbxweb
lib/crypto/crypto-engine.js
hmacSha256
function hmacSha256(key, data) { if (subtle) { var algo = { name: 'HMAC', hash: { name: 'SHA-256' } }; return subtle.importKey('raw', key, algo, false, ['sign']) .then(function(subtleKey) { return subtle.sign(algo, subtleKey, data); }); } else if (nodeCrypto) { return new Promise(function(resolve) { var hmac = nodeCrypto.createHmac('sha256', Buffer.from(key)); var hash = hmac.update(Buffer.from(data)).digest(); resolve(hash.buffer); }); } else { return Promise.reject(new KdbxError(Consts.ErrorCodes.NotImplemented, 'HMAC-SHA256 not implemented')); } }
javascript
function hmacSha256(key, data) { if (subtle) { var algo = { name: 'HMAC', hash: { name: 'SHA-256' } }; return subtle.importKey('raw', key, algo, false, ['sign']) .then(function(subtleKey) { return subtle.sign(algo, subtleKey, data); }); } else if (nodeCrypto) { return new Promise(function(resolve) { var hmac = nodeCrypto.createHmac('sha256', Buffer.from(key)); var hash = hmac.update(Buffer.from(data)).digest(); resolve(hash.buffer); }); } else { return Promise.reject(new KdbxError(Consts.ErrorCodes.NotImplemented, 'HMAC-SHA256 not implemented')); } }
[ "function", "hmacSha256", "(", "key", ",", "data", ")", "{", "if", "(", "subtle", ")", "{", "var", "algo", "=", "{", "name", ":", "'HMAC'", ",", "hash", ":", "{", "name", ":", "'SHA-256'", "}", "}", ";", "return", "subtle", ".", "importKey", "(", "'raw'", ",", "key", ",", "algo", ",", "false", ",", "[", "'sign'", "]", ")", ".", "then", "(", "function", "(", "subtleKey", ")", "{", "return", "subtle", ".", "sign", "(", "algo", ",", "subtleKey", ",", "data", ")", ";", "}", ")", ";", "}", "else", "if", "(", "nodeCrypto", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "var", "hmac", "=", "nodeCrypto", ".", "createHmac", "(", "'sha256'", ",", "Buffer", ".", "from", "(", "key", ")", ")", ";", "var", "hash", "=", "hmac", ".", "update", "(", "Buffer", ".", "from", "(", "data", ")", ")", ".", "digest", "(", ")", ";", "resolve", "(", "hash", ".", "buffer", ")", ";", "}", ")", ";", "}", "else", "{", "return", "Promise", ".", "reject", "(", "new", "KdbxError", "(", "Consts", ".", "ErrorCodes", ".", "NotImplemented", ",", "'HMAC-SHA256 not implemented'", ")", ")", ";", "}", "}" ]
HMAC-SHA-256 hash @param {ArrayBuffer} key @param {ArrayBuffer} data @returns {Promise.<ArrayBuffer>}
[ "HMAC", "-", "SHA", "-", "256", "hash" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/crypto/crypto-engine.js#L70-L86
9,843
keeweb/kdbxweb
lib/crypto/crypto-engine.js
safeRandom
function safeRandom(len) { var randomBytes = new Uint8Array(len); while (len > 0) { var segmentSize = len % maxRandomQuota; segmentSize = segmentSize > 0 ? segmentSize : maxRandomQuota; var randomBytesSegment = new Uint8Array(segmentSize); webCrypto.getRandomValues(randomBytesSegment); len -= segmentSize; randomBytes.set(randomBytesSegment, len); } return randomBytes; }
javascript
function safeRandom(len) { var randomBytes = new Uint8Array(len); while (len > 0) { var segmentSize = len % maxRandomQuota; segmentSize = segmentSize > 0 ? segmentSize : maxRandomQuota; var randomBytesSegment = new Uint8Array(segmentSize); webCrypto.getRandomValues(randomBytesSegment); len -= segmentSize; randomBytes.set(randomBytesSegment, len); } return randomBytes; }
[ "function", "safeRandom", "(", "len", ")", "{", "var", "randomBytes", "=", "new", "Uint8Array", "(", "len", ")", ";", "while", "(", "len", ">", "0", ")", "{", "var", "segmentSize", "=", "len", "%", "maxRandomQuota", ";", "segmentSize", "=", "segmentSize", ">", "0", "?", "segmentSize", ":", "maxRandomQuota", ";", "var", "randomBytesSegment", "=", "new", "Uint8Array", "(", "segmentSize", ")", ";", "webCrypto", ".", "getRandomValues", "(", "randomBytesSegment", ")", ";", "len", "-=", "segmentSize", ";", "randomBytes", ".", "set", "(", "randomBytesSegment", ",", "len", ")", ";", "}", "return", "randomBytes", ";", "}" ]
Gets random bytes from the CryptoEngine @param {number} len - bytes count @return {Uint8Array} - random bytes
[ "Gets", "random", "bytes", "from", "the", "CryptoEngine" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/crypto/crypto-engine.js#L159-L170
9,844
keeweb/kdbxweb
lib/crypto/crypto-engine.js
random
function random(len) { if (subtle) { return safeRandom(len); } else if (nodeCrypto) { return new Uint8Array(nodeCrypto.randomBytes(len)); } else { throw new KdbxError(Consts.ErrorCodes.NotImplemented, 'Random not implemented'); } }
javascript
function random(len) { if (subtle) { return safeRandom(len); } else if (nodeCrypto) { return new Uint8Array(nodeCrypto.randomBytes(len)); } else { throw new KdbxError(Consts.ErrorCodes.NotImplemented, 'Random not implemented'); } }
[ "function", "random", "(", "len", ")", "{", "if", "(", "subtle", ")", "{", "return", "safeRandom", "(", "len", ")", ";", "}", "else", "if", "(", "nodeCrypto", ")", "{", "return", "new", "Uint8Array", "(", "nodeCrypto", ".", "randomBytes", "(", "len", ")", ")", ";", "}", "else", "{", "throw", "new", "KdbxError", "(", "Consts", ".", "ErrorCodes", ".", "NotImplemented", ",", "'Random not implemented'", ")", ";", "}", "}" ]
Generates random bytes of specified length @param {Number} len @returns {Uint8Array}
[ "Generates", "random", "bytes", "of", "specified", "length" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/crypto/crypto-engine.js#L177-L185
9,845
keeweb/kdbxweb
lib/crypto/crypto-engine.js
chacha20
function chacha20(data, key, iv) { return Promise.resolve().then(function() { var algo = new ChaCha20(new Uint8Array(key), new Uint8Array(iv)); return ByteUtils.arrayToBuffer(algo.encrypt(new Uint8Array(data))); }); }
javascript
function chacha20(data, key, iv) { return Promise.resolve().then(function() { var algo = new ChaCha20(new Uint8Array(key), new Uint8Array(iv)); return ByteUtils.arrayToBuffer(algo.encrypt(new Uint8Array(data))); }); }
[ "function", "chacha20", "(", "data", ",", "key", ",", "iv", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "function", "(", ")", "{", "var", "algo", "=", "new", "ChaCha20", "(", "new", "Uint8Array", "(", "key", ")", ",", "new", "Uint8Array", "(", "iv", ")", ")", ";", "return", "ByteUtils", ".", "arrayToBuffer", "(", "algo", ".", "encrypt", "(", "new", "Uint8Array", "(", "data", ")", ")", ")", ";", "}", ")", ";", "}" ]
Encrypts with ChaCha20 @param {ArrayBuffer} data @param {ArrayBuffer} key @param {ArrayBuffer} iv @returns {Promise.<ArrayBuffer>}
[ "Encrypts", "with", "ChaCha20" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/crypto/crypto-engine.js#L194-L199
9,846
keeweb/kdbxweb
lib/crypto/crypto-engine.js
configure
function configure(newSubtle, newWebCrypto, newNodeCrypto) { subtle = newSubtle; webCrypto = newWebCrypto; nodeCrypto = newNodeCrypto; }
javascript
function configure(newSubtle, newWebCrypto, newNodeCrypto) { subtle = newSubtle; webCrypto = newWebCrypto; nodeCrypto = newNodeCrypto; }
[ "function", "configure", "(", "newSubtle", ",", "newWebCrypto", ",", "newNodeCrypto", ")", "{", "subtle", "=", "newSubtle", ";", "webCrypto", "=", "newWebCrypto", ";", "nodeCrypto", "=", "newNodeCrypto", ";", "}" ]
Configures globals, for tests
[ "Configures", "globals", "for", "tests" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/crypto/crypto-engine.js#L220-L224
9,847
keeweb/kdbxweb
lib/crypto/protected-value.js
function(value, salt) { Object.defineProperty(this, '_value', { value: new Uint8Array(value) }); Object.defineProperty(this, '_salt', { value: new Uint8Array(salt) }); }
javascript
function(value, salt) { Object.defineProperty(this, '_value', { value: new Uint8Array(value) }); Object.defineProperty(this, '_salt', { value: new Uint8Array(salt) }); }
[ "function", "(", "value", ",", "salt", ")", "{", "Object", ".", "defineProperty", "(", "this", ",", "'_value'", ",", "{", "value", ":", "new", "Uint8Array", "(", "value", ")", "}", ")", ";", "Object", ".", "defineProperty", "(", "this", ",", "'_salt'", ",", "{", "value", ":", "new", "Uint8Array", "(", "salt", ")", "}", ")", ";", "}" ]
Protected value, used for protected entry fields @param {ArrayBuffer} value - encrypted value @param {ArrayBuffer} salt - salt bytes @constructor
[ "Protected", "value", "used", "for", "protected", "entry", "fields" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/crypto/protected-value.js#L13-L16
9,848
keeweb/kdbxweb
lib/crypto/hmac-block-transform.js
getHmacKey
function getHmacKey(key, blockIndex) { var shaSrc = new Uint8Array(8 + key.byteLength); shaSrc.set(new Uint8Array(key), 8); var view = new DataView(shaSrc.buffer); view.setUint32(0, blockIndex.lo, true); view.setUint32(4, blockIndex.hi, true); return CryptoEngine.sha512(ByteUtils.arrayToBuffer(shaSrc)).then(function(sha) { ByteUtils.zeroBuffer(shaSrc); return sha; }); }
javascript
function getHmacKey(key, blockIndex) { var shaSrc = new Uint8Array(8 + key.byteLength); shaSrc.set(new Uint8Array(key), 8); var view = new DataView(shaSrc.buffer); view.setUint32(0, blockIndex.lo, true); view.setUint32(4, blockIndex.hi, true); return CryptoEngine.sha512(ByteUtils.arrayToBuffer(shaSrc)).then(function(sha) { ByteUtils.zeroBuffer(shaSrc); return sha; }); }
[ "function", "getHmacKey", "(", "key", ",", "blockIndex", ")", "{", "var", "shaSrc", "=", "new", "Uint8Array", "(", "8", "+", "key", ".", "byteLength", ")", ";", "shaSrc", ".", "set", "(", "new", "Uint8Array", "(", "key", ")", ",", "8", ")", ";", "var", "view", "=", "new", "DataView", "(", "shaSrc", ".", "buffer", ")", ";", "view", ".", "setUint32", "(", "0", ",", "blockIndex", ".", "lo", ",", "true", ")", ";", "view", ".", "setUint32", "(", "4", ",", "blockIndex", ".", "hi", ",", "true", ")", ";", "return", "CryptoEngine", ".", "sha512", "(", "ByteUtils", ".", "arrayToBuffer", "(", "shaSrc", ")", ")", ".", "then", "(", "function", "(", "sha", ")", "{", "ByteUtils", ".", "zeroBuffer", "(", "shaSrc", ")", ";", "return", "sha", ";", "}", ")", ";", "}" ]
Computes HMAC-SHA key @param {ArrayBuffer} key @param {Int64} blockIndex @returns {Promise.<ArrayBuffer>}
[ "Computes", "HMAC", "-", "SHA", "key" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/crypto/hmac-block-transform.js#L19-L29
9,849
keeweb/kdbxweb
lib/crypto/hmac-block-transform.js
getBlockHmac
function getBlockHmac(key, blockIndex, blockLength, blockData) { return getHmacKey(key, new Int64(blockIndex)).then(function(blockKey) { var blockDataForHash = new Uint8Array(blockData.byteLength + 4 + 8); var blockDataForHashView = new DataView(blockDataForHash.buffer); blockDataForHash.set(new Uint8Array(blockData), 4 + 8); blockDataForHashView.setInt32(0, blockIndex, true); blockDataForHashView.setInt32(8, blockLength, true); return CryptoEngine.hmacSha256(blockKey, blockDataForHash.buffer); }); }
javascript
function getBlockHmac(key, blockIndex, blockLength, blockData) { return getHmacKey(key, new Int64(blockIndex)).then(function(blockKey) { var blockDataForHash = new Uint8Array(blockData.byteLength + 4 + 8); var blockDataForHashView = new DataView(blockDataForHash.buffer); blockDataForHash.set(new Uint8Array(blockData), 4 + 8); blockDataForHashView.setInt32(0, blockIndex, true); blockDataForHashView.setInt32(8, blockLength, true); return CryptoEngine.hmacSha256(blockKey, blockDataForHash.buffer); }); }
[ "function", "getBlockHmac", "(", "key", ",", "blockIndex", ",", "blockLength", ",", "blockData", ")", "{", "return", "getHmacKey", "(", "key", ",", "new", "Int64", "(", "blockIndex", ")", ")", ".", "then", "(", "function", "(", "blockKey", ")", "{", "var", "blockDataForHash", "=", "new", "Uint8Array", "(", "blockData", ".", "byteLength", "+", "4", "+", "8", ")", ";", "var", "blockDataForHashView", "=", "new", "DataView", "(", "blockDataForHash", ".", "buffer", ")", ";", "blockDataForHash", ".", "set", "(", "new", "Uint8Array", "(", "blockData", ")", ",", "4", "+", "8", ")", ";", "blockDataForHashView", ".", "setInt32", "(", "0", ",", "blockIndex", ",", "true", ")", ";", "blockDataForHashView", ".", "setInt32", "(", "8", ",", "blockLength", ",", "true", ")", ";", "return", "CryptoEngine", ".", "hmacSha256", "(", "blockKey", ",", "blockDataForHash", ".", "buffer", ")", ";", "}", ")", ";", "}" ]
Gets block HMAC @param {ArrayBuffer} key @param {number} blockIndex @param {number} blockLength @param {ArrayBuffer} blockData @returns {Promise.<ArrayBuffer>}
[ "Gets", "block", "HMAC" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/crypto/hmac-block-transform.js#L39-L48
9,850
keeweb/kdbxweb
lib/utils/xml-utils.js
parse
function parse(xml) { var parser = domParserArg ? new dom.DOMParser(domParserArg) : new dom.DOMParser(); var doc; try { doc = parser.parseFromString(xml, 'application/xml'); } catch (e) { throw new KdbxError(Consts.ErrorCodes.FileCorrupt, 'bad xml: ' + e.message); } if (!doc.documentElement) { throw new KdbxError(Consts.ErrorCodes.FileCorrupt, 'bad xml'); } var parserError = doc.getElementsByTagName('parsererror')[0]; if (parserError) { throw new KdbxError(Consts.ErrorCodes.FileCorrupt, 'bad xml: ' + parserError.textContent); } return doc; }
javascript
function parse(xml) { var parser = domParserArg ? new dom.DOMParser(domParserArg) : new dom.DOMParser(); var doc; try { doc = parser.parseFromString(xml, 'application/xml'); } catch (e) { throw new KdbxError(Consts.ErrorCodes.FileCorrupt, 'bad xml: ' + e.message); } if (!doc.documentElement) { throw new KdbxError(Consts.ErrorCodes.FileCorrupt, 'bad xml'); } var parserError = doc.getElementsByTagName('parsererror')[0]; if (parserError) { throw new KdbxError(Consts.ErrorCodes.FileCorrupt, 'bad xml: ' + parserError.textContent); } return doc; }
[ "function", "parse", "(", "xml", ")", "{", "var", "parser", "=", "domParserArg", "?", "new", "dom", ".", "DOMParser", "(", "domParserArg", ")", ":", "new", "dom", ".", "DOMParser", "(", ")", ";", "var", "doc", ";", "try", "{", "doc", "=", "parser", ".", "parseFromString", "(", "xml", ",", "'application/xml'", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "KdbxError", "(", "Consts", ".", "ErrorCodes", ".", "FileCorrupt", ",", "'bad xml: '", "+", "e", ".", "message", ")", ";", "}", "if", "(", "!", "doc", ".", "documentElement", ")", "{", "throw", "new", "KdbxError", "(", "Consts", ".", "ErrorCodes", ".", "FileCorrupt", ",", "'bad xml'", ")", ";", "}", "var", "parserError", "=", "doc", ".", "getElementsByTagName", "(", "'parsererror'", ")", "[", "0", "]", ";", "if", "(", "parserError", ")", "{", "throw", "new", "KdbxError", "(", "Consts", ".", "ErrorCodes", ".", "FileCorrupt", ",", "'bad xml: '", "+", "parserError", ".", "textContent", ")", ";", "}", "return", "doc", ";", "}" ]
Parses XML document Throws an error in case of invalid XML @param {string} xml - xml document @returns {Document}
[ "Parses", "XML", "document", "Throws", "an", "error", "in", "case", "of", "invalid", "XML" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/xml-utils.js#L30-L46
9,851
keeweb/kdbxweb
lib/utils/xml-utils.js
getChildNode
function getChildNode(node, tagName, errorMsgIfAbsent) { if (node && node.childNodes) { for (var i = 0, cn = node.childNodes, len = cn.length; i < len; i++) { if (cn[i].tagName === tagName) { return cn[i]; } } } if (errorMsgIfAbsent) { throw new KdbxError(Consts.ErrorCodes.FileCorrupt, errorMsgIfAbsent); } else { return null; } }
javascript
function getChildNode(node, tagName, errorMsgIfAbsent) { if (node && node.childNodes) { for (var i = 0, cn = node.childNodes, len = cn.length; i < len; i++) { if (cn[i].tagName === tagName) { return cn[i]; } } } if (errorMsgIfAbsent) { throw new KdbxError(Consts.ErrorCodes.FileCorrupt, errorMsgIfAbsent); } else { return null; } }
[ "function", "getChildNode", "(", "node", ",", "tagName", ",", "errorMsgIfAbsent", ")", "{", "if", "(", "node", "&&", "node", ".", "childNodes", ")", "{", "for", "(", "var", "i", "=", "0", ",", "cn", "=", "node", ".", "childNodes", ",", "len", "=", "cn", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "cn", "[", "i", "]", ".", "tagName", "===", "tagName", ")", "{", "return", "cn", "[", "i", "]", ";", "}", "}", "}", "if", "(", "errorMsgIfAbsent", ")", "{", "throw", "new", "KdbxError", "(", "Consts", ".", "ErrorCodes", ".", "FileCorrupt", ",", "errorMsgIfAbsent", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Gets first child node from xml @param {Node} node - parent node for search @param {string} tagName - child node tag name @param {string} [errorMsgIfAbsent] - if set, error will be thrown if node is absent @returns {Node} - first found node, or null, if there's no such node
[ "Gets", "first", "child", "node", "from", "xml" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/xml-utils.js#L73-L86
9,852
keeweb/kdbxweb
lib/utils/xml-utils.js
addChildNode
function addChildNode(node, tagName) { return node.appendChild((node.ownerDocument || node).createElement(tagName)); }
javascript
function addChildNode(node, tagName) { return node.appendChild((node.ownerDocument || node).createElement(tagName)); }
[ "function", "addChildNode", "(", "node", ",", "tagName", ")", "{", "return", "node", ".", "appendChild", "(", "(", "node", ".", "ownerDocument", "||", "node", ")", ".", "createElement", "(", "tagName", ")", ")", ";", "}" ]
Adds child node to xml @param {Node} node - parent node @param {string} tagName - child node tag name @returns {Node} - created node
[ "Adds", "child", "node", "to", "xml" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/xml-utils.js#L94-L96
9,853
keeweb/kdbxweb
lib/utils/xml-utils.js
getText
function getText(node) { if (!node || !node.childNodes) { return undefined; } return node.protectedValue ? node.protectedValue.text : node.textContent; }
javascript
function getText(node) { if (!node || !node.childNodes) { return undefined; } return node.protectedValue ? node.protectedValue.text : node.textContent; }
[ "function", "getText", "(", "node", ")", "{", "if", "(", "!", "node", "||", "!", "node", ".", "childNodes", ")", "{", "return", "undefined", ";", "}", "return", "node", ".", "protectedValue", "?", "node", ".", "protectedValue", ".", "text", ":", "node", ".", "textContent", ";", "}" ]
Gets node inner text @param {Node} node - xml node @return {string|undefined} - node inner text or undefined, if the node is empty
[ "Gets", "node", "inner", "text" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/xml-utils.js#L103-L108
9,854
keeweb/kdbxweb
lib/utils/xml-utils.js
getBytes
function getBytes(node) { var text = getText(node); return text ? ByteUtils.arrayToBuffer(ByteUtils.base64ToBytes(text)) : undefined; }
javascript
function getBytes(node) { var text = getText(node); return text ? ByteUtils.arrayToBuffer(ByteUtils.base64ToBytes(text)) : undefined; }
[ "function", "getBytes", "(", "node", ")", "{", "var", "text", "=", "getText", "(", "node", ")", ";", "return", "text", "?", "ByteUtils", ".", "arrayToBuffer", "(", "ByteUtils", ".", "base64ToBytes", "(", "text", ")", ")", ":", "undefined", ";", "}" ]
Parses bytes saved by KeePass from XML @param {Node} node - xml node with bytes saved by KeePass (base64 format) @return {ArrayBuffer} - ArrayBuffer or undefined, if the tag is empty
[ "Parses", "bytes", "saved", "by", "KeePass", "from", "XML" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/xml-utils.js#L124-L127
9,855
keeweb/kdbxweb
lib/utils/xml-utils.js
setBytes
function setBytes(node, bytes) { if (typeof bytes === 'string') { bytes = ByteUtils.base64ToBytes(bytes); } setText(node, bytes ? ByteUtils.bytesToBase64(ByteUtils.arrayToBuffer(bytes)) : undefined); }
javascript
function setBytes(node, bytes) { if (typeof bytes === 'string') { bytes = ByteUtils.base64ToBytes(bytes); } setText(node, bytes ? ByteUtils.bytesToBase64(ByteUtils.arrayToBuffer(bytes)) : undefined); }
[ "function", "setBytes", "(", "node", ",", "bytes", ")", "{", "if", "(", "typeof", "bytes", "===", "'string'", ")", "{", "bytes", "=", "ByteUtils", ".", "base64ToBytes", "(", "bytes", ")", ";", "}", "setText", "(", "node", ",", "bytes", "?", "ByteUtils", ".", "bytesToBase64", "(", "ByteUtils", ".", "arrayToBuffer", "(", "bytes", ")", ")", ":", "undefined", ")", ";", "}" ]
Sets bytes for node @param {Node} node @param {ArrayBuffer|Uint8Array|string|undefined} bytes
[ "Sets", "bytes", "for", "node" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/xml-utils.js#L134-L139
9,856
keeweb/kdbxweb
lib/utils/xml-utils.js
getDate
function getDate(node) { var text = getText(node); if (!text) { return undefined; } if (text.indexOf(':') > 0) { return new Date(text); } var bytes = new DataView(ByteUtils.arrayToBuffer(ByteUtils.base64ToBytes(text))); var secondsFrom00 = new Int64(bytes.getUint32(0, true), bytes.getUint32(4, true)).value; var diff = (secondsFrom00 - EpochSeconds) * 1000; return new Date(diff); }
javascript
function getDate(node) { var text = getText(node); if (!text) { return undefined; } if (text.indexOf(':') > 0) { return new Date(text); } var bytes = new DataView(ByteUtils.arrayToBuffer(ByteUtils.base64ToBytes(text))); var secondsFrom00 = new Int64(bytes.getUint32(0, true), bytes.getUint32(4, true)).value; var diff = (secondsFrom00 - EpochSeconds) * 1000; return new Date(diff); }
[ "function", "getDate", "(", "node", ")", "{", "var", "text", "=", "getText", "(", "node", ")", ";", "if", "(", "!", "text", ")", "{", "return", "undefined", ";", "}", "if", "(", "text", ".", "indexOf", "(", "':'", ")", ">", "0", ")", "{", "return", "new", "Date", "(", "text", ")", ";", "}", "var", "bytes", "=", "new", "DataView", "(", "ByteUtils", ".", "arrayToBuffer", "(", "ByteUtils", ".", "base64ToBytes", "(", "text", ")", ")", ")", ";", "var", "secondsFrom00", "=", "new", "Int64", "(", "bytes", ".", "getUint32", "(", "0", ",", "true", ")", ",", "bytes", ".", "getUint32", "(", "4", ",", "true", ")", ")", ".", "value", ";", "var", "diff", "=", "(", "secondsFrom00", "-", "EpochSeconds", ")", "*", "1000", ";", "return", "new", "Date", "(", "diff", ")", ";", "}" ]
Parses date saved by KeePass from XML @param {Node} node - xml node with date saved by KeePass (ISO format or base64-uint64) format @return {Date} - date or undefined, if the tag is empty
[ "Parses", "date", "saved", "by", "KeePass", "from", "XML" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/xml-utils.js#L146-L158
9,857
keeweb/kdbxweb
lib/utils/xml-utils.js
setDate
function setDate(node, date, binary) { if (date) { if (binary) { var secondsFrom00 = Math.floor(date.getTime() / 1000) + EpochSeconds; var bytes = new DataView(new ArrayBuffer(8)); var val64 = Int64.from(secondsFrom00); bytes.setUint32(0, val64.lo, true); bytes.setUint32(4, val64.hi, true); setText(node, ByteUtils.bytesToBase64(bytes.buffer)); } else { setText(node, date.toISOString().replace(dateRegex, '')); } } else { setText(node, ''); } }
javascript
function setDate(node, date, binary) { if (date) { if (binary) { var secondsFrom00 = Math.floor(date.getTime() / 1000) + EpochSeconds; var bytes = new DataView(new ArrayBuffer(8)); var val64 = Int64.from(secondsFrom00); bytes.setUint32(0, val64.lo, true); bytes.setUint32(4, val64.hi, true); setText(node, ByteUtils.bytesToBase64(bytes.buffer)); } else { setText(node, date.toISOString().replace(dateRegex, '')); } } else { setText(node, ''); } }
[ "function", "setDate", "(", "node", ",", "date", ",", "binary", ")", "{", "if", "(", "date", ")", "{", "if", "(", "binary", ")", "{", "var", "secondsFrom00", "=", "Math", ".", "floor", "(", "date", ".", "getTime", "(", ")", "/", "1000", ")", "+", "EpochSeconds", ";", "var", "bytes", "=", "new", "DataView", "(", "new", "ArrayBuffer", "(", "8", ")", ")", ";", "var", "val64", "=", "Int64", ".", "from", "(", "secondsFrom00", ")", ";", "bytes", ".", "setUint32", "(", "0", ",", "val64", ".", "lo", ",", "true", ")", ";", "bytes", ".", "setUint32", "(", "4", ",", "val64", ".", "hi", ",", "true", ")", ";", "setText", "(", "node", ",", "ByteUtils", ".", "bytesToBase64", "(", "bytes", ".", "buffer", ")", ")", ";", "}", "else", "{", "setText", "(", "node", ",", "date", ".", "toISOString", "(", ")", ".", "replace", "(", "dateRegex", ",", "''", ")", ")", ";", "}", "}", "else", "{", "setText", "(", "node", ",", "''", ")", ";", "}", "}" ]
Sets node date as string or binary @param {Node} node @param {Date|undefined} date @param {boolean} [binary=false]
[ "Sets", "node", "date", "as", "string", "or", "binary" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/xml-utils.js#L166-L181
9,858
keeweb/kdbxweb
lib/utils/xml-utils.js
setNumber
function setNumber(node, number) { setText(node, typeof number === 'number' && !isNaN(number) ? number.toString() : undefined); }
javascript
function setNumber(node, number) { setText(node, typeof number === 'number' && !isNaN(number) ? number.toString() : undefined); }
[ "function", "setNumber", "(", "node", ",", "number", ")", "{", "setText", "(", "node", ",", "typeof", "number", "===", "'number'", "&&", "!", "isNaN", "(", "number", ")", "?", "number", ".", "toString", "(", ")", ":", "undefined", ")", ";", "}" ]
Sets node number @param {Node} node @return {Number|undefined} number
[ "Sets", "node", "number" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/xml-utils.js#L198-L200
9,859
keeweb/kdbxweb
lib/utils/xml-utils.js
setBoolean
function setBoolean(node, boolean) { setText(node, boolean === undefined ? '' : boolean === null ? 'null' : boolean ? 'True' : 'False'); }
javascript
function setBoolean(node, boolean) { setText(node, boolean === undefined ? '' : boolean === null ? 'null' : boolean ? 'True' : 'False'); }
[ "function", "setBoolean", "(", "node", ",", "boolean", ")", "{", "setText", "(", "node", ",", "boolean", "===", "undefined", "?", "''", ":", "boolean", "===", "null", "?", "'null'", ":", "boolean", "?", "'True'", ":", "'False'", ")", ";", "}" ]
Sets node boolean @param {Node} node @param {boolean|undefined} boolean
[ "Sets", "node", "boolean" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/xml-utils.js#L217-L219
9,860
keeweb/kdbxweb
lib/utils/xml-utils.js
strToBoolean
function strToBoolean(str) { switch (str && str.toLowerCase && str.toLowerCase()) { case 'true': return true; case 'false': return false; case 'null': return null; } return undefined; }
javascript
function strToBoolean(str) { switch (str && str.toLowerCase && str.toLowerCase()) { case 'true': return true; case 'false': return false; case 'null': return null; } return undefined; }
[ "function", "strToBoolean", "(", "str", ")", "{", "switch", "(", "str", "&&", "str", ".", "toLowerCase", "&&", "str", ".", "toLowerCase", "(", ")", ")", "{", "case", "'true'", ":", "return", "true", ";", "case", "'false'", ":", "return", "false", ";", "case", "'null'", ":", "return", "null", ";", "}", "return", "undefined", ";", "}" ]
Converts saved string to boolean @param {string} str @returns {boolean}
[ "Converts", "saved", "string", "to", "boolean" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/xml-utils.js#L226-L236
9,861
keeweb/kdbxweb
lib/utils/xml-utils.js
setUuid
function setUuid(node, uuid) { var uuidBytes = uuid instanceof KdbxUuid ? uuid.toBytes() : uuid; setBytes(node, uuidBytes); }
javascript
function setUuid(node, uuid) { var uuidBytes = uuid instanceof KdbxUuid ? uuid.toBytes() : uuid; setBytes(node, uuidBytes); }
[ "function", "setUuid", "(", "node", ",", "uuid", ")", "{", "var", "uuidBytes", "=", "uuid", "instanceof", "KdbxUuid", "?", "uuid", ".", "toBytes", "(", ")", ":", "uuid", ";", "setBytes", "(", "node", ",", "uuidBytes", ")", ";", "}" ]
Sets node uuid @param {Node} node @param {KdbxUuid} uuid
[ "Sets", "node", "uuid" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/xml-utils.js#L253-L256
9,862
keeweb/kdbxweb
lib/utils/xml-utils.js
setProtectedText
function setProtectedText(node, text) { if (text instanceof ProtectedValue) { node.protectedValue = text; node.setAttribute(XmlNames.Attr.Protected, 'True'); } else { setText(node, text); } }
javascript
function setProtectedText(node, text) { if (text instanceof ProtectedValue) { node.protectedValue = text; node.setAttribute(XmlNames.Attr.Protected, 'True'); } else { setText(node, text); } }
[ "function", "setProtectedText", "(", "node", ",", "text", ")", "{", "if", "(", "text", "instanceof", "ProtectedValue", ")", "{", "node", ".", "protectedValue", "=", "text", ";", "node", ".", "setAttribute", "(", "XmlNames", ".", "Attr", ".", "Protected", ",", "'True'", ")", ";", "}", "else", "{", "setText", "(", "node", ",", "text", ")", ";", "}", "}" ]
Sets node protected text @param {Node} node @param {ProtectedValue|string} text
[ "Sets", "node", "protected", "text" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/xml-utils.js#L272-L279
9,863
keeweb/kdbxweb
lib/utils/xml-utils.js
getProtectedBinary
function getProtectedBinary(node) { if (node.protectedValue) { return node.protectedValue; } var text = node.textContent; var ref = node.getAttribute(XmlNames.Attr.Ref); if (ref) { return { ref: ref }; } if (!text) { return undefined; } var compressed = strToBoolean(node.getAttribute(XmlNames.Attr.Compressed)); var bytes = ByteUtils.base64ToBytes(text); if (compressed) { bytes = pako.ungzip(bytes); } return ByteUtils.arrayToBuffer(bytes); }
javascript
function getProtectedBinary(node) { if (node.protectedValue) { return node.protectedValue; } var text = node.textContent; var ref = node.getAttribute(XmlNames.Attr.Ref); if (ref) { return { ref: ref }; } if (!text) { return undefined; } var compressed = strToBoolean(node.getAttribute(XmlNames.Attr.Compressed)); var bytes = ByteUtils.base64ToBytes(text); if (compressed) { bytes = pako.ungzip(bytes); } return ByteUtils.arrayToBuffer(bytes); }
[ "function", "getProtectedBinary", "(", "node", ")", "{", "if", "(", "node", ".", "protectedValue", ")", "{", "return", "node", ".", "protectedValue", ";", "}", "var", "text", "=", "node", ".", "textContent", ";", "var", "ref", "=", "node", ".", "getAttribute", "(", "XmlNames", ".", "Attr", ".", "Ref", ")", ";", "if", "(", "ref", ")", "{", "return", "{", "ref", ":", "ref", "}", ";", "}", "if", "(", "!", "text", ")", "{", "return", "undefined", ";", "}", "var", "compressed", "=", "strToBoolean", "(", "node", ".", "getAttribute", "(", "XmlNames", ".", "Attr", ".", "Compressed", ")", ")", ";", "var", "bytes", "=", "ByteUtils", ".", "base64ToBytes", "(", "text", ")", ";", "if", "(", "compressed", ")", "{", "bytes", "=", "pako", ".", "ungzip", "(", "bytes", ")", ";", "}", "return", "ByteUtils", ".", "arrayToBuffer", "(", "bytes", ")", ";", "}" ]
Gets node protected text from inner text @param {Node} node @return {ProtectedValue|ArrayBuffer|{ref: string}} - protected value, or array buffer, or reference to binary
[ "Gets", "node", "protected", "text", "from", "inner", "text" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/xml-utils.js#L286-L304
9,864
keeweb/kdbxweb
lib/utils/xml-utils.js
setProtectedBinary
function setProtectedBinary(node, binary) { if (binary instanceof ProtectedValue) { node.protectedValue = binary; node.setAttribute(XmlNames.Attr.Protected, 'True'); } else if (binary && binary.ref) { node.setAttribute(XmlNames.Attr.Ref, binary.ref); } else { setBytes(node, binary); } }
javascript
function setProtectedBinary(node, binary) { if (binary instanceof ProtectedValue) { node.protectedValue = binary; node.setAttribute(XmlNames.Attr.Protected, 'True'); } else if (binary && binary.ref) { node.setAttribute(XmlNames.Attr.Ref, binary.ref); } else { setBytes(node, binary); } }
[ "function", "setProtectedBinary", "(", "node", ",", "binary", ")", "{", "if", "(", "binary", "instanceof", "ProtectedValue", ")", "{", "node", ".", "protectedValue", "=", "binary", ";", "node", ".", "setAttribute", "(", "XmlNames", ".", "Attr", ".", "Protected", ",", "'True'", ")", ";", "}", "else", "if", "(", "binary", "&&", "binary", ".", "ref", ")", "{", "node", ".", "setAttribute", "(", "XmlNames", ".", "Attr", ".", "Ref", ",", "binary", ".", "ref", ")", ";", "}", "else", "{", "setBytes", "(", "node", ",", "binary", ")", ";", "}", "}" ]
Sets node protected binary @param {Node} node @param {ProtectedValue|ArrayBuffer|{ref: string}|string} binary
[ "Sets", "node", "protected", "binary" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/xml-utils.js#L311-L320
9,865
keeweb/kdbxweb
lib/utils/xml-utils.js
traverse
function traverse(node, callback) { callback(node); for (var i = 0, cn = node.childNodes, len = cn.length; i < len; i++) { var childNode = cn[i]; if (childNode.tagName) { traverse(childNode, callback); } } }
javascript
function traverse(node, callback) { callback(node); for (var i = 0, cn = node.childNodes, len = cn.length; i < len; i++) { var childNode = cn[i]; if (childNode.tagName) { traverse(childNode, callback); } } }
[ "function", "traverse", "(", "node", ",", "callback", ")", "{", "callback", "(", "node", ")", ";", "for", "(", "var", "i", "=", "0", ",", "cn", "=", "node", ".", "childNodes", ",", "len", "=", "cn", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "childNode", "=", "cn", "[", "i", "]", ";", "if", "(", "childNode", ".", "tagName", ")", "{", "traverse", "(", "childNode", ",", "callback", ")", ";", "}", "}", "}" ]
Traversed XML tree with depth-first preorder search @param {Node} node @param {function} callback
[ "Traversed", "XML", "tree", "with", "depth", "-", "first", "preorder", "search" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/xml-utils.js#L327-L335
9,866
keeweb/kdbxweb
lib/utils/xml-utils.js
setProtectedValues
function setProtectedValues(node, protectSaltGenerator) { traverse(node, function(node) { if (strToBoolean(node.getAttribute(XmlNames.Attr.Protected))) { try { var value = ByteUtils.arrayToBuffer(ByteUtils.base64ToBytes(node.textContent)); if (value.byteLength) { var salt = protectSaltGenerator.getSalt(value.byteLength); node.protectedValue = new ProtectedValue(value, salt); } } catch (e) { throw new KdbxError(Consts.ErrorCodes.FileCorrupt, 'bad protected value at line ' + node.lineNumber + ': ' + e); } } }); }
javascript
function setProtectedValues(node, protectSaltGenerator) { traverse(node, function(node) { if (strToBoolean(node.getAttribute(XmlNames.Attr.Protected))) { try { var value = ByteUtils.arrayToBuffer(ByteUtils.base64ToBytes(node.textContent)); if (value.byteLength) { var salt = protectSaltGenerator.getSalt(value.byteLength); node.protectedValue = new ProtectedValue(value, salt); } } catch (e) { throw new KdbxError(Consts.ErrorCodes.FileCorrupt, 'bad protected value at line ' + node.lineNumber + ': ' + e); } } }); }
[ "function", "setProtectedValues", "(", "node", ",", "protectSaltGenerator", ")", "{", "traverse", "(", "node", ",", "function", "(", "node", ")", "{", "if", "(", "strToBoolean", "(", "node", ".", "getAttribute", "(", "XmlNames", ".", "Attr", ".", "Protected", ")", ")", ")", "{", "try", "{", "var", "value", "=", "ByteUtils", ".", "arrayToBuffer", "(", "ByteUtils", ".", "base64ToBytes", "(", "node", ".", "textContent", ")", ")", ";", "if", "(", "value", ".", "byteLength", ")", "{", "var", "salt", "=", "protectSaltGenerator", ".", "getSalt", "(", "value", ".", "byteLength", ")", ";", "node", ".", "protectedValue", "=", "new", "ProtectedValue", "(", "value", ",", "salt", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "throw", "new", "KdbxError", "(", "Consts", ".", "ErrorCodes", ".", "FileCorrupt", ",", "'bad protected value at line '", "+", "node", ".", "lineNumber", "+", "': '", "+", "e", ")", ";", "}", "}", "}", ")", ";", "}" ]
Reads protected values for all nodes in tree @param {Node} node @param {ProtectSaltGenerator} protectSaltGenerator
[ "Reads", "protected", "values", "for", "all", "nodes", "in", "tree" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/xml-utils.js#L342-L357
9,867
keeweb/kdbxweb
lib/utils/xml-utils.js
updateProtectedValuesSalt
function updateProtectedValuesSalt(node, protectSaltGenerator) { traverse(node, function(node) { if (strToBoolean(node.getAttribute(XmlNames.Attr.Protected)) && node.protectedValue) { var newSalt = protectSaltGenerator.getSalt(node.protectedValue.byteLength); node.protectedValue.setSalt(newSalt); node.textContent = node.protectedValue.toString(); } }); }
javascript
function updateProtectedValuesSalt(node, protectSaltGenerator) { traverse(node, function(node) { if (strToBoolean(node.getAttribute(XmlNames.Attr.Protected)) && node.protectedValue) { var newSalt = protectSaltGenerator.getSalt(node.protectedValue.byteLength); node.protectedValue.setSalt(newSalt); node.textContent = node.protectedValue.toString(); } }); }
[ "function", "updateProtectedValuesSalt", "(", "node", ",", "protectSaltGenerator", ")", "{", "traverse", "(", "node", ",", "function", "(", "node", ")", "{", "if", "(", "strToBoolean", "(", "node", ".", "getAttribute", "(", "XmlNames", ".", "Attr", ".", "Protected", ")", ")", "&&", "node", ".", "protectedValue", ")", "{", "var", "newSalt", "=", "protectSaltGenerator", ".", "getSalt", "(", "node", ".", "protectedValue", ".", "byteLength", ")", ";", "node", ".", "protectedValue", ".", "setSalt", "(", "newSalt", ")", ";", "node", ".", "textContent", "=", "node", ".", "protectedValue", ".", "toString", "(", ")", ";", "}", "}", ")", ";", "}" ]
Updates protected values salt for all nodes in tree which have protected values assigned @param {Node} node @param {ProtectSaltGenerator} protectSaltGenerator
[ "Updates", "protected", "values", "salt", "for", "all", "nodes", "in", "tree", "which", "have", "protected", "values", "assigned" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/xml-utils.js#L364-L372
9,868
keeweb/kdbxweb
lib/utils/xml-utils.js
unprotectValues
function unprotectValues(node) { traverse(node, function(node) { if (strToBoolean(node.getAttribute(XmlNames.Attr.Protected)) && node.protectedValue) { node.removeAttribute(XmlNames.Attr.Protected); node.setAttribute(XmlNames.Attr.ProtectedInMemPlainXml, 'True'); node.textContent = node.protectedValue.getText(); } }); }
javascript
function unprotectValues(node) { traverse(node, function(node) { if (strToBoolean(node.getAttribute(XmlNames.Attr.Protected)) && node.protectedValue) { node.removeAttribute(XmlNames.Attr.Protected); node.setAttribute(XmlNames.Attr.ProtectedInMemPlainXml, 'True'); node.textContent = node.protectedValue.getText(); } }); }
[ "function", "unprotectValues", "(", "node", ")", "{", "traverse", "(", "node", ",", "function", "(", "node", ")", "{", "if", "(", "strToBoolean", "(", "node", ".", "getAttribute", "(", "XmlNames", ".", "Attr", ".", "Protected", ")", ")", "&&", "node", ".", "protectedValue", ")", "{", "node", ".", "removeAttribute", "(", "XmlNames", ".", "Attr", ".", "Protected", ")", ";", "node", ".", "setAttribute", "(", "XmlNames", ".", "Attr", ".", "ProtectedInMemPlainXml", ",", "'True'", ")", ";", "node", ".", "textContent", "=", "node", ".", "protectedValue", ".", "getText", "(", ")", ";", "}", "}", ")", ";", "}" ]
Unprotect protected values for all nodes in tree which have protected values assigned @param {Node} node
[ "Unprotect", "protected", "values", "for", "all", "nodes", "in", "tree", "which", "have", "protected", "values", "assigned" ]
43ada2ed06f0608b8cb88278fb309351a6eaad82
https://github.com/keeweb/kdbxweb/blob/43ada2ed06f0608b8cb88278fb309351a6eaad82/lib/utils/xml-utils.js#L378-L386
9,869
square/connect-javascript-sdk
src/model/Customer.js
function(id, createdAt, updatedAt) { var _this = this; _this['id'] = id; _this['created_at'] = createdAt; _this['updated_at'] = updatedAt; }
javascript
function(id, createdAt, updatedAt) { var _this = this; _this['id'] = id; _this['created_at'] = createdAt; _this['updated_at'] = updatedAt; }
[ "function", "(", "id", ",", "createdAt", ",", "updatedAt", ")", "{", "var", "_this", "=", "this", ";", "_this", "[", "'id'", "]", "=", "id", ";", "_this", "[", "'created_at'", "]", "=", "createdAt", ";", "_this", "[", "'updated_at'", "]", "=", "updatedAt", ";", "}" ]
The Customer model module. @module model/Customer Constructs a new <code>Customer</code>. Represents one of a business&#39;s customers, which can have one or more cards on file associated with it. @alias module:model/Customer @class @param id {String} The customer's unique ID. @param createdAt {String} The time when the customer was created, in RFC 3339 format. @param updatedAt {String} The time when the customer was last updated, in RFC 3339 format.
[ "The", "Customer", "model", "module", "." ]
5c69a3054e112ab10a0b651f33d8371a7485c13e
https://github.com/square/connect-javascript-sdk/blob/5c69a3054e112ab10a0b651f33d8371a7485c13e/src/model/Customer.js#L37-L57
9,870
hprose/hprose-nodejs
example/future.js
function(resolve, reject) { console.log(thisPromiseCount + ') Promise started (Async code started)'); // This only is an example to create asynchronism global.setTimeout( function() { // We fulfill the promise ! resolve(thisPromiseCount); }, Math.random() * 2000 + 1000); }
javascript
function(resolve, reject) { console.log(thisPromiseCount + ') Promise started (Async code started)'); // This only is an example to create asynchronism global.setTimeout( function() { // We fulfill the promise ! resolve(thisPromiseCount); }, Math.random() * 2000 + 1000); }
[ "function", "(", "resolve", ",", "reject", ")", "{", "console", ".", "log", "(", "thisPromiseCount", "+", "') Promise started (Async code started)'", ")", ";", "// This only is an example to create asynchronism", "global", ".", "setTimeout", "(", "function", "(", ")", "{", "// We fulfill the promise !", "resolve", "(", "thisPromiseCount", ")", ";", "}", ",", "Math", ".", "random", "(", ")", "*", "2000", "+", "1000", ")", ";", "}" ]
The resolver function is called with the ability to resolve or reject the promise
[ "The", "resolver", "function", "is", "called", "with", "the", "ability", "to", "resolve", "or", "reject", "the", "promise" ]
04da8ca371d4696c19a4ca189733aac6afbc05ad
https://github.com/hprose/hprose-nodejs/blob/04da8ca371d4696c19a4ca189733aac6afbc05ad/example/future.js#L178-L187
9,871
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/project_config/index.js
function(projectConfig, experimentId) { var experiment = projectConfig.experimentIdMap[experimentId]; if (fns.isEmpty(experiment)) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_EXPERIMENT_ID, MODULE_NAME, experimentId)); } return experiment.layerId; }
javascript
function(projectConfig, experimentId) { var experiment = projectConfig.experimentIdMap[experimentId]; if (fns.isEmpty(experiment)) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_EXPERIMENT_ID, MODULE_NAME, experimentId)); } return experiment.layerId; }
[ "function", "(", "projectConfig", ",", "experimentId", ")", "{", "var", "experiment", "=", "projectConfig", ".", "experimentIdMap", "[", "experimentId", "]", ";", "if", "(", "fns", ".", "isEmpty", "(", "experiment", ")", ")", "{", "throw", "new", "Error", "(", "sprintf", "(", "ERROR_MESSAGES", ".", "INVALID_EXPERIMENT_ID", ",", "MODULE_NAME", ",", "experimentId", ")", ")", ";", "}", "return", "experiment", ".", "layerId", ";", "}" ]
Get layer ID for the provided experiment key @param {Object} projectConfig Object representing project configuration @param {string} experimentId Experiment ID for which layer ID is to be determined @return {string} Layer ID corresponding to the provided experiment key @throws If experiment key is not in datafile
[ "Get", "layer", "ID", "for", "the", "provided", "experiment", "key" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/project_config/index.js#L140-L146
9,872
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/project_config/index.js
function(projectConfig, attributeKey, logger) { var attribute = projectConfig.attributeKeyMap[attributeKey]; var hasReservedPrefix = attributeKey.indexOf(RESERVED_ATTRIBUTE_PREFIX) === 0; if (attribute) { if (hasReservedPrefix) { logger.log(LOG_LEVEL.WARN, sprintf('Attribute %s unexpectedly has reserved prefix %s; using attribute ID instead of reserved attribute name.', attributeKey, RESERVED_ATTRIBUTE_PREFIX)); } return attribute.id; } else if (hasReservedPrefix) { return attributeKey; } logger.log(LOG_LEVEL.DEBUG, sprintf(ERROR_MESSAGES.UNRECOGNIZED_ATTRIBUTE, MODULE_NAME, attributeKey)); return null; }
javascript
function(projectConfig, attributeKey, logger) { var attribute = projectConfig.attributeKeyMap[attributeKey]; var hasReservedPrefix = attributeKey.indexOf(RESERVED_ATTRIBUTE_PREFIX) === 0; if (attribute) { if (hasReservedPrefix) { logger.log(LOG_LEVEL.WARN, sprintf('Attribute %s unexpectedly has reserved prefix %s; using attribute ID instead of reserved attribute name.', attributeKey, RESERVED_ATTRIBUTE_PREFIX)); } return attribute.id; } else if (hasReservedPrefix) { return attributeKey; } logger.log(LOG_LEVEL.DEBUG, sprintf(ERROR_MESSAGES.UNRECOGNIZED_ATTRIBUTE, MODULE_NAME, attributeKey)); return null; }
[ "function", "(", "projectConfig", ",", "attributeKey", ",", "logger", ")", "{", "var", "attribute", "=", "projectConfig", ".", "attributeKeyMap", "[", "attributeKey", "]", ";", "var", "hasReservedPrefix", "=", "attributeKey", ".", "indexOf", "(", "RESERVED_ATTRIBUTE_PREFIX", ")", "===", "0", ";", "if", "(", "attribute", ")", "{", "if", "(", "hasReservedPrefix", ")", "{", "logger", ".", "log", "(", "LOG_LEVEL", ".", "WARN", ",", "sprintf", "(", "'Attribute %s unexpectedly has reserved prefix %s; using attribute ID instead of reserved attribute name.'", ",", "attributeKey", ",", "RESERVED_ATTRIBUTE_PREFIX", ")", ")", ";", "}", "return", "attribute", ".", "id", ";", "}", "else", "if", "(", "hasReservedPrefix", ")", "{", "return", "attributeKey", ";", "}", "logger", ".", "log", "(", "LOG_LEVEL", ".", "DEBUG", ",", "sprintf", "(", "ERROR_MESSAGES", ".", "UNRECOGNIZED_ATTRIBUTE", ",", "MODULE_NAME", ",", "attributeKey", ")", ")", ";", "return", "null", ";", "}" ]
Get attribute ID for the provided attribute key @param {Object} projectConfig Object representing project configuration @param {string} attributeKey Attribute key for which ID is to be determined @param {Object} logger @return {string|null} Attribute ID corresponding to the provided attribute key. Attribute key if it is a reserved attribute.
[ "Get", "attribute", "ID", "for", "the", "provided", "attribute", "key" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/project_config/index.js#L155-L170
9,873
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/project_config/index.js
function(projectConfig, eventKey) { var event = projectConfig.eventKeyMap[eventKey]; if (event) { return event.id; } return null; }
javascript
function(projectConfig, eventKey) { var event = projectConfig.eventKeyMap[eventKey]; if (event) { return event.id; } return null; }
[ "function", "(", "projectConfig", ",", "eventKey", ")", "{", "var", "event", "=", "projectConfig", ".", "eventKeyMap", "[", "eventKey", "]", ";", "if", "(", "event", ")", "{", "return", "event", ".", "id", ";", "}", "return", "null", ";", "}" ]
Get event ID for the provided @param {Object} projectConfig Object representing project configuration @param {string} eventKey Event key for which ID is to be determined @return {string|null} Event ID corresponding to the provided event key
[ "Get", "event", "ID", "for", "the", "provided" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/project_config/index.js#L178-L184
9,874
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/project_config/index.js
function(projectConfig, experimentKey) { return module.exports.getExperimentStatus(projectConfig, experimentKey) === EXPERIMENT_RUNNING_STATUS || module.exports.getExperimentStatus(projectConfig, experimentKey) === EXPERIMENT_LAUNCHED_STATUS; }
javascript
function(projectConfig, experimentKey) { return module.exports.getExperimentStatus(projectConfig, experimentKey) === EXPERIMENT_RUNNING_STATUS || module.exports.getExperimentStatus(projectConfig, experimentKey) === EXPERIMENT_LAUNCHED_STATUS; }
[ "function", "(", "projectConfig", ",", "experimentKey", ")", "{", "return", "module", ".", "exports", ".", "getExperimentStatus", "(", "projectConfig", ",", "experimentKey", ")", "===", "EXPERIMENT_RUNNING_STATUS", "||", "module", ".", "exports", ".", "getExperimentStatus", "(", "projectConfig", ",", "experimentKey", ")", "===", "EXPERIMENT_LAUNCHED_STATUS", ";", "}" ]
Returns whether experiment has a status of 'Running' or 'Launched' @param {Object} projectConfig Object representing project configuration @param {string} experimentKey Experiment key for which status is to be compared with 'Running' @return {Boolean} true if experiment status is set to 'Running', false otherwise
[ "Returns", "whether", "experiment", "has", "a", "status", "of", "Running", "or", "Launched" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/project_config/index.js#L207-L210
9,875
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/project_config/index.js
function(projectConfig, experimentKey) { var experiment = projectConfig.experimentKeyMap[experimentKey]; if (fns.isEmpty(experiment)) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_EXPERIMENT_KEY, MODULE_NAME, experimentKey)); } return experiment.audienceConditions || experiment.audienceIds; }
javascript
function(projectConfig, experimentKey) { var experiment = projectConfig.experimentKeyMap[experimentKey]; if (fns.isEmpty(experiment)) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_EXPERIMENT_KEY, MODULE_NAME, experimentKey)); } return experiment.audienceConditions || experiment.audienceIds; }
[ "function", "(", "projectConfig", ",", "experimentKey", ")", "{", "var", "experiment", "=", "projectConfig", ".", "experimentKeyMap", "[", "experimentKey", "]", ";", "if", "(", "fns", ".", "isEmpty", "(", "experiment", ")", ")", "{", "throw", "new", "Error", "(", "sprintf", "(", "ERROR_MESSAGES", ".", "INVALID_EXPERIMENT_KEY", ",", "MODULE_NAME", ",", "experimentKey", ")", ")", ";", "}", "return", "experiment", ".", "audienceConditions", "||", "experiment", ".", "audienceIds", ";", "}" ]
Get audience conditions for the experiment @param {Object} projectConfig Object representing project configuration @param {string} experimentKey Experiment key for which audience conditions are to be determined @return {Array} Audience conditions for the experiment - can be an array of audience IDs, or a nested array of conditions Examples: ["5", "6"], ["and", ["or", "1", "2"], "3"] @throws If experiment key is not in datafile
[ "Get", "audience", "conditions", "for", "the", "experiment" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/project_config/index.js#L228-L235
9,876
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/project_config/index.js
function(projectConfig, variationId) { if (projectConfig.variationIdMap.hasOwnProperty(variationId)) { return projectConfig.variationIdMap[variationId].key; } return null; }
javascript
function(projectConfig, variationId) { if (projectConfig.variationIdMap.hasOwnProperty(variationId)) { return projectConfig.variationIdMap[variationId].key; } return null; }
[ "function", "(", "projectConfig", ",", "variationId", ")", "{", "if", "(", "projectConfig", ".", "variationIdMap", ".", "hasOwnProperty", "(", "variationId", ")", ")", "{", "return", "projectConfig", ".", "variationIdMap", "[", "variationId", "]", ".", "key", ";", "}", "return", "null", ";", "}" ]
Get variation key given experiment key and variation ID @param {Object} projectConfig Object representing project configuration @param {string} variationId ID of the variation @return {string} Variation key or null if the variation ID is not found
[ "Get", "variation", "key", "given", "experiment", "key", "and", "variation", "ID" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/project_config/index.js#L243-L248
9,877
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/project_config/index.js
function(projectConfig, experimentKey, variationKey) { var experiment = projectConfig.experimentKeyMap[experimentKey]; if (experiment.variationKeyMap.hasOwnProperty(variationKey)) { return experiment.variationKeyMap[variationKey].id; } return null; }
javascript
function(projectConfig, experimentKey, variationKey) { var experiment = projectConfig.experimentKeyMap[experimentKey]; if (experiment.variationKeyMap.hasOwnProperty(variationKey)) { return experiment.variationKeyMap[variationKey].id; } return null; }
[ "function", "(", "projectConfig", ",", "experimentKey", ",", "variationKey", ")", "{", "var", "experiment", "=", "projectConfig", ".", "experimentKeyMap", "[", "experimentKey", "]", ";", "if", "(", "experiment", ".", "variationKeyMap", ".", "hasOwnProperty", "(", "variationKey", ")", ")", "{", "return", "experiment", ".", "variationKeyMap", "[", "variationKey", "]", ".", "id", ";", "}", "return", "null", ";", "}" ]
Get the variation ID given the experiment key and variation key @param {Object} projectConfig Object representing project configuration @param {string} experimentKey Key of the experiment the variation belongs to @param {string} variationKey The variation key @return {string} the variation ID
[ "Get", "the", "variation", "ID", "given", "the", "experiment", "key", "and", "variation", "key" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/project_config/index.js#L257-L263
9,878
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/project_config/index.js
function(projectConfig, experimentKey) { if (projectConfig.experimentKeyMap.hasOwnProperty(experimentKey)) { var experiment = projectConfig.experimentKeyMap[experimentKey]; if (!!experiment) { return experiment; } } throw new Error(sprintf(ERROR_MESSAGES.EXPERIMENT_KEY_NOT_IN_DATAFILE, MODULE_NAME, experimentKey)); }
javascript
function(projectConfig, experimentKey) { if (projectConfig.experimentKeyMap.hasOwnProperty(experimentKey)) { var experiment = projectConfig.experimentKeyMap[experimentKey]; if (!!experiment) { return experiment; } } throw new Error(sprintf(ERROR_MESSAGES.EXPERIMENT_KEY_NOT_IN_DATAFILE, MODULE_NAME, experimentKey)); }
[ "function", "(", "projectConfig", ",", "experimentKey", ")", "{", "if", "(", "projectConfig", ".", "experimentKeyMap", ".", "hasOwnProperty", "(", "experimentKey", ")", ")", "{", "var", "experiment", "=", "projectConfig", ".", "experimentKeyMap", "[", "experimentKey", "]", ";", "if", "(", "!", "!", "experiment", ")", "{", "return", "experiment", ";", "}", "}", "throw", "new", "Error", "(", "sprintf", "(", "ERROR_MESSAGES", ".", "EXPERIMENT_KEY_NOT_IN_DATAFILE", ",", "MODULE_NAME", ",", "experimentKey", ")", ")", ";", "}" ]
Get experiment from provided experiment key @param {Object} projectConfig Object representing project configuration @param {string} experimentKey Event key for which experiment IDs are to be retrieved @return {Object} experiment @throws If experiment key is not in datafile
[ "Get", "experiment", "from", "provided", "experiment", "key" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/project_config/index.js#L272-L281
9,879
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/project_config/index.js
function(projectConfig, experimentKey) { var experiment = projectConfig.experimentKeyMap[experimentKey]; if (fns.isEmpty(experiment)) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_EXPERIMENT_KEY, MODULE_NAME, experimentKey)); } return experiment.trafficAllocation; }
javascript
function(projectConfig, experimentKey) { var experiment = projectConfig.experimentKeyMap[experimentKey]; if (fns.isEmpty(experiment)) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_EXPERIMENT_KEY, MODULE_NAME, experimentKey)); } return experiment.trafficAllocation; }
[ "function", "(", "projectConfig", ",", "experimentKey", ")", "{", "var", "experiment", "=", "projectConfig", ".", "experimentKeyMap", "[", "experimentKey", "]", ";", "if", "(", "fns", ".", "isEmpty", "(", "experiment", ")", ")", "{", "throw", "new", "Error", "(", "sprintf", "(", "ERROR_MESSAGES", ".", "INVALID_EXPERIMENT_KEY", ",", "MODULE_NAME", ",", "experimentKey", ")", ")", ";", "}", "return", "experiment", ".", "trafficAllocation", ";", "}" ]
Given an experiment key, returns the traffic allocation within that experiment @param {Object} projectConfig Object representing project configuration @param {string} experimentKey Key representing the experiment @return {Array<Object>} Traffic allocation for the experiment @throws If experiment key is not in datafile
[ "Given", "an", "experiment", "key", "returns", "the", "traffic", "allocation", "within", "that", "experiment" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/project_config/index.js#L290-L296
9,880
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/project_config/index.js
function(projectConfig, experimentId, logger) { if (projectConfig.experimentIdMap.hasOwnProperty(experimentId)) { var experiment = projectConfig.experimentIdMap[experimentId]; if (!!experiment) { return experiment; } } logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.INVALID_EXPERIMENT_ID, MODULE_NAME, experimentId)); return null; }
javascript
function(projectConfig, experimentId, logger) { if (projectConfig.experimentIdMap.hasOwnProperty(experimentId)) { var experiment = projectConfig.experimentIdMap[experimentId]; if (!!experiment) { return experiment; } } logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.INVALID_EXPERIMENT_ID, MODULE_NAME, experimentId)); return null; }
[ "function", "(", "projectConfig", ",", "experimentId", ",", "logger", ")", "{", "if", "(", "projectConfig", ".", "experimentIdMap", ".", "hasOwnProperty", "(", "experimentId", ")", ")", "{", "var", "experiment", "=", "projectConfig", ".", "experimentIdMap", "[", "experimentId", "]", ";", "if", "(", "!", "!", "experiment", ")", "{", "return", "experiment", ";", "}", "}", "logger", ".", "log", "(", "LOG_LEVEL", ".", "ERROR", ",", "sprintf", "(", "ERROR_MESSAGES", ".", "INVALID_EXPERIMENT_ID", ",", "MODULE_NAME", ",", "experimentId", ")", ")", ";", "return", "null", ";", "}" ]
Get experiment from provided experiment id. Log an error if no experiment exists in the project config with the given ID. @param {Object} projectConfig Object representing project configuration @param {string} experimentId ID of desired experiment object @return {Object} Experiment object
[ "Get", "experiment", "from", "provided", "experiment", "id", ".", "Log", "an", "error", "if", "no", "experiment", "exists", "in", "the", "project", "config", "with", "the", "given", "ID", "." ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/project_config/index.js#L305-L315
9,881
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/project_config/index.js
function(projectConfig, featureKey, logger) { if (projectConfig.featureKeyMap.hasOwnProperty(featureKey)) { var feature = projectConfig.featureKeyMap[featureKey]; if (!!feature) { return feature; } } logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.FEATURE_NOT_IN_DATAFILE, MODULE_NAME, featureKey)); return null; }
javascript
function(projectConfig, featureKey, logger) { if (projectConfig.featureKeyMap.hasOwnProperty(featureKey)) { var feature = projectConfig.featureKeyMap[featureKey]; if (!!feature) { return feature; } } logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.FEATURE_NOT_IN_DATAFILE, MODULE_NAME, featureKey)); return null; }
[ "function", "(", "projectConfig", ",", "featureKey", ",", "logger", ")", "{", "if", "(", "projectConfig", ".", "featureKeyMap", ".", "hasOwnProperty", "(", "featureKey", ")", ")", "{", "var", "feature", "=", "projectConfig", ".", "featureKeyMap", "[", "featureKey", "]", ";", "if", "(", "!", "!", "feature", ")", "{", "return", "feature", ";", "}", "}", "logger", ".", "log", "(", "LOG_LEVEL", ".", "ERROR", ",", "sprintf", "(", "ERROR_MESSAGES", ".", "FEATURE_NOT_IN_DATAFILE", ",", "MODULE_NAME", ",", "featureKey", ")", ")", ";", "return", "null", ";", "}" ]
Get feature from provided feature key. Log an error if no feature exists in the project config with the given key. @param {Object} projectConfig @param {string} featureKey @param {Object} logger @return {Object|null} Feature object, or null if no feature with the given key exists
[ "Get", "feature", "from", "provided", "feature", "key", ".", "Log", "an", "error", "if", "no", "feature", "exists", "in", "the", "project", "config", "with", "the", "given", "key", "." ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/project_config/index.js#L326-L336
9,882
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/project_config/index.js
function(projectConfig, featureKey, variableKey, logger) { var feature = projectConfig.featureKeyMap[featureKey]; if (!feature) { logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.FEATURE_NOT_IN_DATAFILE, MODULE_NAME, featureKey)); return null; } var variable = feature.variableKeyMap[variableKey]; if (!variable) { logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.VARIABLE_KEY_NOT_IN_DATAFILE, MODULE_NAME, variableKey, featureKey)); return null; } return variable; }
javascript
function(projectConfig, featureKey, variableKey, logger) { var feature = projectConfig.featureKeyMap[featureKey]; if (!feature) { logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.FEATURE_NOT_IN_DATAFILE, MODULE_NAME, featureKey)); return null; } var variable = feature.variableKeyMap[variableKey]; if (!variable) { logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.VARIABLE_KEY_NOT_IN_DATAFILE, MODULE_NAME, variableKey, featureKey)); return null; } return variable; }
[ "function", "(", "projectConfig", ",", "featureKey", ",", "variableKey", ",", "logger", ")", "{", "var", "feature", "=", "projectConfig", ".", "featureKeyMap", "[", "featureKey", "]", ";", "if", "(", "!", "feature", ")", "{", "logger", ".", "log", "(", "LOG_LEVEL", ".", "ERROR", ",", "sprintf", "(", "ERROR_MESSAGES", ".", "FEATURE_NOT_IN_DATAFILE", ",", "MODULE_NAME", ",", "featureKey", ")", ")", ";", "return", "null", ";", "}", "var", "variable", "=", "feature", ".", "variableKeyMap", "[", "variableKey", "]", ";", "if", "(", "!", "variable", ")", "{", "logger", ".", "log", "(", "LOG_LEVEL", ".", "ERROR", ",", "sprintf", "(", "ERROR_MESSAGES", ".", "VARIABLE_KEY_NOT_IN_DATAFILE", ",", "MODULE_NAME", ",", "variableKey", ",", "featureKey", ")", ")", ";", "return", "null", ";", "}", "return", "variable", ";", "}" ]
Get the variable with the given key associated with the feature with the given key. If the feature key or the variable key are invalid, log an error message. @param {Object} projectConfig @param {string} featureKey @param {string} variableKey @param {Object} logger @return {Object|null} Variable object, or null one or both of the given feature and variable keys are invalid
[ "Get", "the", "variable", "with", "the", "given", "key", "associated", "with", "the", "feature", "with", "the", "given", "key", ".", "If", "the", "feature", "key", "or", "the", "variable", "key", "are", "invalid", "log", "an", "error", "message", "." ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/project_config/index.js#L349-L363
9,883
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/project_config/index.js
function(projectConfig, variable, variation, logger) { if (!variable || !variation) { return null; } if (!projectConfig.variationVariableUsageMap.hasOwnProperty(variation.id)) { logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.VARIATION_ID_NOT_IN_DATAFILE_NO_EXPERIMENT, MODULE_NAME, variation.id)); return null; } var variableUsages = projectConfig.variationVariableUsageMap[variation.id]; var variableUsage = variableUsages[variable.id]; return variableUsage ? variableUsage.value : null; }
javascript
function(projectConfig, variable, variation, logger) { if (!variable || !variation) { return null; } if (!projectConfig.variationVariableUsageMap.hasOwnProperty(variation.id)) { logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.VARIATION_ID_NOT_IN_DATAFILE_NO_EXPERIMENT, MODULE_NAME, variation.id)); return null; } var variableUsages = projectConfig.variationVariableUsageMap[variation.id]; var variableUsage = variableUsages[variable.id]; return variableUsage ? variableUsage.value : null; }
[ "function", "(", "projectConfig", ",", "variable", ",", "variation", ",", "logger", ")", "{", "if", "(", "!", "variable", "||", "!", "variation", ")", "{", "return", "null", ";", "}", "if", "(", "!", "projectConfig", ".", "variationVariableUsageMap", ".", "hasOwnProperty", "(", "variation", ".", "id", ")", ")", "{", "logger", ".", "log", "(", "LOG_LEVEL", ".", "ERROR", ",", "sprintf", "(", "ERROR_MESSAGES", ".", "VARIATION_ID_NOT_IN_DATAFILE_NO_EXPERIMENT", ",", "MODULE_NAME", ",", "variation", ".", "id", ")", ")", ";", "return", "null", ";", "}", "var", "variableUsages", "=", "projectConfig", ".", "variationVariableUsageMap", "[", "variation", ".", "id", "]", ";", "var", "variableUsage", "=", "variableUsages", "[", "variable", ".", "id", "]", ";", "return", "variableUsage", "?", "variableUsage", ".", "value", ":", "null", ";", "}" ]
Get the value of the given variable for the given variation. If the given variable has no value for the given variation, return null. Log an error message if the variation is invalid. If the variable or variation are invalid, return null. @param {Object} projectConfig @param {Object} variable @param {Object} variation @param {Object} logger @return {string|null} The value of the given variable for the given variation, or null if the given variable has no value for the given variation or if the variation or variable are invalid
[ "Get", "the", "value", "of", "the", "given", "variable", "for", "the", "given", "variation", ".", "If", "the", "given", "variable", "has", "no", "value", "for", "the", "given", "variation", "return", "null", ".", "Log", "an", "error", "message", "if", "the", "variation", "is", "invalid", ".", "If", "the", "variable", "or", "variation", "are", "invalid", "return", "null", "." ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/project_config/index.js#L377-L391
9,884
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/project_config/index.js
function(variableValue, variableType, logger) { var castValue; switch (variableType) { case FEATURE_VARIABLE_TYPES.BOOLEAN: if (variableValue !== 'true' && variableValue !== 'false') { logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.UNABLE_TO_CAST_VALUE, MODULE_NAME, variableValue, variableType)); castValue = null; } else { castValue = variableValue === 'true'; } break; case FEATURE_VARIABLE_TYPES.INTEGER: castValue = parseInt(variableValue, 10); if (isNaN(castValue)) { logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.UNABLE_TO_CAST_VALUE, MODULE_NAME, variableValue, variableType)); castValue = null; } break; case FEATURE_VARIABLE_TYPES.DOUBLE: castValue = parseFloat(variableValue); if (isNaN(castValue)) { logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.UNABLE_TO_CAST_VALUE, MODULE_NAME, variableValue, variableType)); castValue = null; } break; default: // type is STRING castValue = variableValue; break; } return castValue; }
javascript
function(variableValue, variableType, logger) { var castValue; switch (variableType) { case FEATURE_VARIABLE_TYPES.BOOLEAN: if (variableValue !== 'true' && variableValue !== 'false') { logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.UNABLE_TO_CAST_VALUE, MODULE_NAME, variableValue, variableType)); castValue = null; } else { castValue = variableValue === 'true'; } break; case FEATURE_VARIABLE_TYPES.INTEGER: castValue = parseInt(variableValue, 10); if (isNaN(castValue)) { logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.UNABLE_TO_CAST_VALUE, MODULE_NAME, variableValue, variableType)); castValue = null; } break; case FEATURE_VARIABLE_TYPES.DOUBLE: castValue = parseFloat(variableValue); if (isNaN(castValue)) { logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.UNABLE_TO_CAST_VALUE, MODULE_NAME, variableValue, variableType)); castValue = null; } break; default: // type is STRING castValue = variableValue; break; } return castValue; }
[ "function", "(", "variableValue", ",", "variableType", ",", "logger", ")", "{", "var", "castValue", ";", "switch", "(", "variableType", ")", "{", "case", "FEATURE_VARIABLE_TYPES", ".", "BOOLEAN", ":", "if", "(", "variableValue", "!==", "'true'", "&&", "variableValue", "!==", "'false'", ")", "{", "logger", ".", "log", "(", "LOG_LEVEL", ".", "ERROR", ",", "sprintf", "(", "ERROR_MESSAGES", ".", "UNABLE_TO_CAST_VALUE", ",", "MODULE_NAME", ",", "variableValue", ",", "variableType", ")", ")", ";", "castValue", "=", "null", ";", "}", "else", "{", "castValue", "=", "variableValue", "===", "'true'", ";", "}", "break", ";", "case", "FEATURE_VARIABLE_TYPES", ".", "INTEGER", ":", "castValue", "=", "parseInt", "(", "variableValue", ",", "10", ")", ";", "if", "(", "isNaN", "(", "castValue", ")", ")", "{", "logger", ".", "log", "(", "LOG_LEVEL", ".", "ERROR", ",", "sprintf", "(", "ERROR_MESSAGES", ".", "UNABLE_TO_CAST_VALUE", ",", "MODULE_NAME", ",", "variableValue", ",", "variableType", ")", ")", ";", "castValue", "=", "null", ";", "}", "break", ";", "case", "FEATURE_VARIABLE_TYPES", ".", "DOUBLE", ":", "castValue", "=", "parseFloat", "(", "variableValue", ")", ";", "if", "(", "isNaN", "(", "castValue", ")", ")", "{", "logger", ".", "log", "(", "LOG_LEVEL", ".", "ERROR", ",", "sprintf", "(", "ERROR_MESSAGES", ".", "UNABLE_TO_CAST_VALUE", ",", "MODULE_NAME", ",", "variableValue", ",", "variableType", ")", ")", ";", "castValue", "=", "null", ";", "}", "break", ";", "default", ":", "// type is STRING", "castValue", "=", "variableValue", ";", "break", ";", "}", "return", "castValue", ";", "}" ]
Given a variable value in string form, try to cast it to the argument type. If the type cast succeeds, return the type casted value, otherwise log an error and return null. @param {string} variableValue Variable value in string form @param {string} variableType Type of the variable whose value was passed in the first argument. Must be one of FEATURE_VARIABLE_TYPES in lib/utils/enums/index.js. The return value's type is determined by this argument (boolean for BOOLEAN, number for INTEGER or DOUBLE, and string for STRING). @param {Object} logger Logger instance @returns {*} Variable value of the appropriate type, or null if the type cast failed
[ "Given", "a", "variable", "value", "in", "string", "form", "try", "to", "cast", "it", "to", "the", "argument", "type", ".", "If", "the", "type", "cast", "succeeds", "return", "the", "type", "casted", "value", "otherwise", "log", "an", "error", "and", "return", "null", "." ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/project_config/index.js#L409-L444
9,885
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/project_config/index.js
function(config) { configValidator.validateDatafile(config.datafile); if (config.skipJSONValidation === true) { config.logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.SKIPPING_JSON_VALIDATION, MODULE_NAME)); } else if (config.jsonSchemaValidator) { config.jsonSchemaValidator.validate(projectConfigSchema, config.datafile); config.logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.VALID_DATAFILE, MODULE_NAME)); } return module.exports.createProjectConfig(config.datafile); }
javascript
function(config) { configValidator.validateDatafile(config.datafile); if (config.skipJSONValidation === true) { config.logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.SKIPPING_JSON_VALIDATION, MODULE_NAME)); } else if (config.jsonSchemaValidator) { config.jsonSchemaValidator.validate(projectConfigSchema, config.datafile); config.logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.VALID_DATAFILE, MODULE_NAME)); } return module.exports.createProjectConfig(config.datafile); }
[ "function", "(", "config", ")", "{", "configValidator", ".", "validateDatafile", "(", "config", ".", "datafile", ")", ";", "if", "(", "config", ".", "skipJSONValidation", "===", "true", ")", "{", "config", ".", "logger", ".", "log", "(", "LOG_LEVEL", ".", "INFO", ",", "sprintf", "(", "LOG_MESSAGES", ".", "SKIPPING_JSON_VALIDATION", ",", "MODULE_NAME", ")", ")", ";", "}", "else", "if", "(", "config", ".", "jsonSchemaValidator", ")", "{", "config", ".", "jsonSchemaValidator", ".", "validate", "(", "projectConfigSchema", ",", "config", ".", "datafile", ")", ";", "config", ".", "logger", ".", "log", "(", "LOG_LEVEL", ".", "INFO", ",", "sprintf", "(", "LOG_MESSAGES", ".", "VALID_DATAFILE", ",", "MODULE_NAME", ")", ")", ";", "}", "return", "module", ".", "exports", ".", "createProjectConfig", "(", "config", ".", "datafile", ")", ";", "}" ]
Try to create a project config object from the given datafile and configuration properties. If successful, return the project config object, otherwise throws an error @param {Object} config @param {Object} config.datafile @param {Object} config.jsonSchemaValidator @param {Object} config.logger @param {Object} config.skipJSONValidation @return {Object} Project config object
[ "Try", "to", "create", "a", "project", "config", "object", "from", "the", "given", "datafile", "and", "configuration", "properties", ".", "If", "successful", "return", "the", "project", "config", "object", "otherwise", "throws", "an", "error" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/project_config/index.js#L488-L497
9,886
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/audience_evaluator/index.js
function(audienceConditions, audiencesById, userAttributes, logger) { // if there are no audiences, return true because that means ALL users are included in the experiment if (!audienceConditions || audienceConditions.length === 0) { return true; } if (!userAttributes) { userAttributes = {}; } var evaluateConditionWithUserAttributes = function(condition) { return customAttributeConditionEvaluator.evaluate(condition, userAttributes, logger); }; var evaluateAudience = function(audienceId) { var audience = audiencesById[audienceId]; if (audience) { logger.log(LOG_LEVEL.DEBUG, sprintf(LOG_MESSAGES.EVALUATING_AUDIENCE, MODULE_NAME, audienceId, JSON.stringify(audience.conditions))); var result = conditionTreeEvaluator.evaluate(audience.conditions, evaluateConditionWithUserAttributes); var resultText = result === null ? 'UNKNOWN' : result.toString().toUpperCase(); logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.AUDIENCE_EVALUATION_RESULT, MODULE_NAME, audienceId, resultText)); return result; } return null; }; return conditionTreeEvaluator.evaluate(audienceConditions, evaluateAudience) || false; }
javascript
function(audienceConditions, audiencesById, userAttributes, logger) { // if there are no audiences, return true because that means ALL users are included in the experiment if (!audienceConditions || audienceConditions.length === 0) { return true; } if (!userAttributes) { userAttributes = {}; } var evaluateConditionWithUserAttributes = function(condition) { return customAttributeConditionEvaluator.evaluate(condition, userAttributes, logger); }; var evaluateAudience = function(audienceId) { var audience = audiencesById[audienceId]; if (audience) { logger.log(LOG_LEVEL.DEBUG, sprintf(LOG_MESSAGES.EVALUATING_AUDIENCE, MODULE_NAME, audienceId, JSON.stringify(audience.conditions))); var result = conditionTreeEvaluator.evaluate(audience.conditions, evaluateConditionWithUserAttributes); var resultText = result === null ? 'UNKNOWN' : result.toString().toUpperCase(); logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.AUDIENCE_EVALUATION_RESULT, MODULE_NAME, audienceId, resultText)); return result; } return null; }; return conditionTreeEvaluator.evaluate(audienceConditions, evaluateAudience) || false; }
[ "function", "(", "audienceConditions", ",", "audiencesById", ",", "userAttributes", ",", "logger", ")", "{", "// if there are no audiences, return true because that means ALL users are included in the experiment", "if", "(", "!", "audienceConditions", "||", "audienceConditions", ".", "length", "===", "0", ")", "{", "return", "true", ";", "}", "if", "(", "!", "userAttributes", ")", "{", "userAttributes", "=", "{", "}", ";", "}", "var", "evaluateConditionWithUserAttributes", "=", "function", "(", "condition", ")", "{", "return", "customAttributeConditionEvaluator", ".", "evaluate", "(", "condition", ",", "userAttributes", ",", "logger", ")", ";", "}", ";", "var", "evaluateAudience", "=", "function", "(", "audienceId", ")", "{", "var", "audience", "=", "audiencesById", "[", "audienceId", "]", ";", "if", "(", "audience", ")", "{", "logger", ".", "log", "(", "LOG_LEVEL", ".", "DEBUG", ",", "sprintf", "(", "LOG_MESSAGES", ".", "EVALUATING_AUDIENCE", ",", "MODULE_NAME", ",", "audienceId", ",", "JSON", ".", "stringify", "(", "audience", ".", "conditions", ")", ")", ")", ";", "var", "result", "=", "conditionTreeEvaluator", ".", "evaluate", "(", "audience", ".", "conditions", ",", "evaluateConditionWithUserAttributes", ")", ";", "var", "resultText", "=", "result", "===", "null", "?", "'UNKNOWN'", ":", "result", ".", "toString", "(", ")", ".", "toUpperCase", "(", ")", ";", "logger", ".", "log", "(", "LOG_LEVEL", ".", "INFO", ",", "sprintf", "(", "LOG_MESSAGES", ".", "AUDIENCE_EVALUATION_RESULT", ",", "MODULE_NAME", ",", "audienceId", ",", "resultText", ")", ")", ";", "return", "result", ";", "}", "return", "null", ";", "}", ";", "return", "conditionTreeEvaluator", ".", "evaluate", "(", "audienceConditions", ",", "evaluateAudience", ")", "||", "false", ";", "}" ]
Determine if the given user attributes satisfy the given audience conditions @param {Array|String|null|undefined} audienceConditions Audience conditions to match the user attributes against - can be an array of audience IDs, a nested array of conditions, or a single leaf condition. Examples: ["5", "6"], ["and", ["or", "1", "2"], "3"], "1" @param {Object} audiencesById Object providing access to full audience objects for audience IDs contained in audienceConditions. Keys should be audience IDs, values should be full audience objects with conditions properties @param {Object} [userAttributes] User attributes which will be used in determining if audience conditions are met. If not provided, defaults to an empty object @param {Object} logger Logger instance. @return {Boolean} true if the user attributes match the given audience conditions, false otherwise
[ "Determine", "if", "the", "given", "user", "attributes", "satisfy", "the", "given", "audience", "conditions" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/audience_evaluator/index.js#L40-L68
9,887
optimizely/javascript-sdk
packages/optimizely-sdk/lib/utils/event_tags_validator/index.js
function(eventTags) { if (typeof eventTags === 'object' && !Array.isArray(eventTags) && eventTags !== null) { return true; } else { throw new Error(sprintf(ERROR_MESSAGES.INVALID_EVENT_TAGS, MODULE_NAME)); } }
javascript
function(eventTags) { if (typeof eventTags === 'object' && !Array.isArray(eventTags) && eventTags !== null) { return true; } else { throw new Error(sprintf(ERROR_MESSAGES.INVALID_EVENT_TAGS, MODULE_NAME)); } }
[ "function", "(", "eventTags", ")", "{", "if", "(", "typeof", "eventTags", "===", "'object'", "&&", "!", "Array", ".", "isArray", "(", "eventTags", ")", "&&", "eventTags", "!==", "null", ")", "{", "return", "true", ";", "}", "else", "{", "throw", "new", "Error", "(", "sprintf", "(", "ERROR_MESSAGES", ".", "INVALID_EVENT_TAGS", ",", "MODULE_NAME", ")", ")", ";", "}", "}" ]
Validates user's provided event tags @param {Object} event tags @return {boolean} True if event tags are valid @throws If event tags are not valid
[ "Validates", "user", "s", "provided", "event", "tags" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/utils/event_tags_validator/index.js#L33-L39
9,888
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/decision_service/index.js
DecisionService
function DecisionService(options) { this.userProfileService = options.userProfileService || null; this.logger = options.logger; this.forcedVariationMap = {}; }
javascript
function DecisionService(options) { this.userProfileService = options.userProfileService || null; this.logger = options.logger; this.forcedVariationMap = {}; }
[ "function", "DecisionService", "(", "options", ")", "{", "this", ".", "userProfileService", "=", "options", ".", "userProfileService", "||", "null", ";", "this", ".", "logger", "=", "options", ".", "logger", ";", "this", ".", "forcedVariationMap", "=", "{", "}", ";", "}" ]
Optimizely's decision service that determines which variation of an experiment the user will be allocated to. The decision service contains all logic around how a user decision is made. This includes all of the following (in order): 1. Checking experiment status 2. Checking forced bucketing 3. Checking whitelisting 4. Checking user profile service for past bucketing decisions (sticky bucketing) 5. Checking audience targeting 6. Using Murmurhash3 to bucket the user. @constructor @param {Object} options @param {Object} options.userProfileService An instance of the user profile service for sticky bucketing. @param {Object} options.logger An instance of a logger to log messages with. @returns {Object}
[ "Optimizely", "s", "decision", "service", "that", "determines", "which", "variation", "of", "an", "experiment", "the", "user", "will", "be", "allocated", "to", "." ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/decision_service/index.js#L51-L55
9,889
optimizely/javascript-sdk
packages/optimizely-sdk/lib/utils/config_validator/index.js
function(config) { if (config.errorHandler && (typeof config.errorHandler.handleError !== 'function')) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_ERROR_HANDLER, MODULE_NAME)); } if (config.eventDispatcher && (typeof config.eventDispatcher.dispatchEvent !== 'function')) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_EVENT_DISPATCHER, MODULE_NAME)); } if (config.logger && (typeof config.logger.log !== 'function')) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_LOGGER, MODULE_NAME)); } return true; }
javascript
function(config) { if (config.errorHandler && (typeof config.errorHandler.handleError !== 'function')) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_ERROR_HANDLER, MODULE_NAME)); } if (config.eventDispatcher && (typeof config.eventDispatcher.dispatchEvent !== 'function')) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_EVENT_DISPATCHER, MODULE_NAME)); } if (config.logger && (typeof config.logger.log !== 'function')) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_LOGGER, MODULE_NAME)); } return true; }
[ "function", "(", "config", ")", "{", "if", "(", "config", ".", "errorHandler", "&&", "(", "typeof", "config", ".", "errorHandler", ".", "handleError", "!==", "'function'", ")", ")", "{", "throw", "new", "Error", "(", "sprintf", "(", "ERROR_MESSAGES", ".", "INVALID_ERROR_HANDLER", ",", "MODULE_NAME", ")", ")", ";", "}", "if", "(", "config", ".", "eventDispatcher", "&&", "(", "typeof", "config", ".", "eventDispatcher", ".", "dispatchEvent", "!==", "'function'", ")", ")", "{", "throw", "new", "Error", "(", "sprintf", "(", "ERROR_MESSAGES", ".", "INVALID_EVENT_DISPATCHER", ",", "MODULE_NAME", ")", ")", ";", "}", "if", "(", "config", ".", "logger", "&&", "(", "typeof", "config", ".", "logger", ".", "log", "!==", "'function'", ")", ")", "{", "throw", "new", "Error", "(", "sprintf", "(", "ERROR_MESSAGES", ".", "INVALID_LOGGER", ",", "MODULE_NAME", ")", ")", ";", "}", "return", "true", ";", "}" ]
Validates the given config options @param {Object} config @param {Object} config.errorHandler @param {Object} config.eventDispatcher @param {Object} config.logger @return {Boolean} True if the config options are valid @throws If any of the config options are not valid
[ "Validates", "the", "given", "config", "options" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/utils/config_validator/index.js#L41-L55
9,890
optimizely/javascript-sdk
packages/optimizely-sdk/lib/utils/config_validator/index.js
function(datafile) { if (!datafile) { throw new Error(sprintf(ERROR_MESSAGES.NO_DATAFILE_SPECIFIED, MODULE_NAME)); } if (typeof datafile === 'string' || datafile instanceof String) { // Attempt to parse the datafile string try { datafile = JSON.parse(datafile); } catch (ex) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_DATAFILE_MALFORMED, MODULE_NAME)); } } if (SUPPORTED_VERSIONS.indexOf(datafile.version) === -1) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_DATAFILE_VERSION, MODULE_NAME, datafile.version)); } return true; }
javascript
function(datafile) { if (!datafile) { throw new Error(sprintf(ERROR_MESSAGES.NO_DATAFILE_SPECIFIED, MODULE_NAME)); } if (typeof datafile === 'string' || datafile instanceof String) { // Attempt to parse the datafile string try { datafile = JSON.parse(datafile); } catch (ex) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_DATAFILE_MALFORMED, MODULE_NAME)); } } if (SUPPORTED_VERSIONS.indexOf(datafile.version) === -1) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_DATAFILE_VERSION, MODULE_NAME, datafile.version)); } return true; }
[ "function", "(", "datafile", ")", "{", "if", "(", "!", "datafile", ")", "{", "throw", "new", "Error", "(", "sprintf", "(", "ERROR_MESSAGES", ".", "NO_DATAFILE_SPECIFIED", ",", "MODULE_NAME", ")", ")", ";", "}", "if", "(", "typeof", "datafile", "===", "'string'", "||", "datafile", "instanceof", "String", ")", "{", "// Attempt to parse the datafile string", "try", "{", "datafile", "=", "JSON", ".", "parse", "(", "datafile", ")", ";", "}", "catch", "(", "ex", ")", "{", "throw", "new", "Error", "(", "sprintf", "(", "ERROR_MESSAGES", ".", "INVALID_DATAFILE_MALFORMED", ",", "MODULE_NAME", ")", ")", ";", "}", "}", "if", "(", "SUPPORTED_VERSIONS", ".", "indexOf", "(", "datafile", ".", "version", ")", "===", "-", "1", ")", "{", "throw", "new", "Error", "(", "sprintf", "(", "ERROR_MESSAGES", ".", "INVALID_DATAFILE_VERSION", ",", "MODULE_NAME", ",", "datafile", ".", "version", ")", ")", ";", "}", "return", "true", ";", "}" ]
Validates the datafile @param {string} datafile @return {Boolean} True if the datafile is valid @throws If the datafile is not valid for any of the following reasons: - The datafile string is undefined - The datafile string cannot be parsed as a JSON object - The datafile version is not supported
[ "Validates", "the", "datafile" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/utils/config_validator/index.js#L66-L85
9,891
optimizely/javascript-sdk
packages/optimizely-sdk/lib/plugins/event_dispatcher/index.node.js
function(eventObj, callback) { // Non-POST requests not supported if (eventObj.httpVerb !== 'POST') { return; } var parsedUrl = url.parse(eventObj.url); var path = parsedUrl.path; if (parsedUrl.query) { path += '?' + parsedUrl.query; } var dataString = JSON.stringify(eventObj.params); var requestOptions = { host: parsedUrl.host, path: parsedUrl.path, method: 'POST', headers: { 'content-type': 'application/json', 'content-length': dataString.length.toString(), } }; var requestCallback = function(response) { if (response && response.statusCode && response.statusCode >= 200 && response.statusCode < 400) { callback(response); } }; var req = (parsedUrl.protocol === 'http:' ? http : https).request(requestOptions, requestCallback); // Add no-op error listener to prevent this from throwing req.on('error', function() {}); req.write(dataString); req.end(); return req; }
javascript
function(eventObj, callback) { // Non-POST requests not supported if (eventObj.httpVerb !== 'POST') { return; } var parsedUrl = url.parse(eventObj.url); var path = parsedUrl.path; if (parsedUrl.query) { path += '?' + parsedUrl.query; } var dataString = JSON.stringify(eventObj.params); var requestOptions = { host: parsedUrl.host, path: parsedUrl.path, method: 'POST', headers: { 'content-type': 'application/json', 'content-length': dataString.length.toString(), } }; var requestCallback = function(response) { if (response && response.statusCode && response.statusCode >= 200 && response.statusCode < 400) { callback(response); } }; var req = (parsedUrl.protocol === 'http:' ? http : https).request(requestOptions, requestCallback); // Add no-op error listener to prevent this from throwing req.on('error', function() {}); req.write(dataString); req.end(); return req; }
[ "function", "(", "eventObj", ",", "callback", ")", "{", "// Non-POST requests not supported", "if", "(", "eventObj", ".", "httpVerb", "!==", "'POST'", ")", "{", "return", ";", "}", "var", "parsedUrl", "=", "url", ".", "parse", "(", "eventObj", ".", "url", ")", ";", "var", "path", "=", "parsedUrl", ".", "path", ";", "if", "(", "parsedUrl", ".", "query", ")", "{", "path", "+=", "'?'", "+", "parsedUrl", ".", "query", ";", "}", "var", "dataString", "=", "JSON", ".", "stringify", "(", "eventObj", ".", "params", ")", ";", "var", "requestOptions", "=", "{", "host", ":", "parsedUrl", ".", "host", ",", "path", ":", "parsedUrl", ".", "path", ",", "method", ":", "'POST'", ",", "headers", ":", "{", "'content-type'", ":", "'application/json'", ",", "'content-length'", ":", "dataString", ".", "length", ".", "toString", "(", ")", ",", "}", "}", ";", "var", "requestCallback", "=", "function", "(", "response", ")", "{", "if", "(", "response", "&&", "response", ".", "statusCode", "&&", "response", ".", "statusCode", ">=", "200", "&&", "response", ".", "statusCode", "<", "400", ")", "{", "callback", "(", "response", ")", ";", "}", "}", ";", "var", "req", "=", "(", "parsedUrl", ".", "protocol", "===", "'http:'", "?", "http", ":", "https", ")", ".", "request", "(", "requestOptions", ",", "requestCallback", ")", ";", "// Add no-op error listener to prevent this from throwing", "req", ".", "on", "(", "'error'", ",", "function", "(", ")", "{", "}", ")", ";", "req", ".", "write", "(", "dataString", ")", ";", "req", ".", "end", "(", ")", ";", "return", "req", ";", "}" ]
Dispatch an HTTP request to the given url and the specified options @param {Object} eventObj Event object containing @param {string} eventObj.url the url to make the request to @param {Object} eventObj.params parameters to pass to the request (i.e. in the POST body) @param {string} eventObj.httpVerb the HTTP request method type. only POST is supported. @param {function} callback callback to execute @return {ClientRequest|undefined} ClientRequest object which made the request, or undefined if no request was made (error)
[ "Dispatch", "an", "HTTP", "request", "to", "the", "given", "url", "and", "the", "specified", "options" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/plugins/event_dispatcher/index.node.js#L30-L66
9,892
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/bucketer/index.js
function(bucketerParams) { // Check if user is in a random group; if so, check if user is bucketed into a specific experiment var experiment = bucketerParams.experimentKeyMap[bucketerParams.experimentKey]; var groupId = experiment['groupId']; if (groupId) { var group = bucketerParams.groupIdMap[groupId]; if (!group) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_GROUP_ID, MODULE_NAME, groupId)); } if (group.policy === RANDOM_POLICY) { var bucketedExperimentId = module.exports.bucketUserIntoExperiment(group, bucketerParams.bucketingId, bucketerParams.userId, bucketerParams.logger); // Return if user is not bucketed into any experiment if (bucketedExperimentId === null) { var notbucketedInAnyExperimentLogMessage = sprintf(LOG_MESSAGES.USER_NOT_IN_ANY_EXPERIMENT, MODULE_NAME, bucketerParams.userId, groupId); bucketerParams.logger.log(LOG_LEVEL.INFO, notbucketedInAnyExperimentLogMessage); return null; } // Return if user is bucketed into a different experiment than the one specified if (bucketedExperimentId !== bucketerParams.experimentId) { var notBucketedIntoExperimentOfGroupLogMessage = sprintf(LOG_MESSAGES.USER_NOT_BUCKETED_INTO_EXPERIMENT_IN_GROUP, MODULE_NAME, bucketerParams.userId, bucketerParams.experimentKey, groupId); bucketerParams.logger.log(LOG_LEVEL.INFO, notBucketedIntoExperimentOfGroupLogMessage); return null; } // Continue bucketing if user is bucketed into specified experiment var bucketedIntoExperimentOfGroupLogMessage = sprintf(LOG_MESSAGES.USER_BUCKETED_INTO_EXPERIMENT_IN_GROUP, MODULE_NAME, bucketerParams.userId, bucketerParams.experimentKey, groupId); bucketerParams.logger.log(LOG_LEVEL.INFO, bucketedIntoExperimentOfGroupLogMessage); } } var bucketingId = sprintf('%s%s', bucketerParams.bucketingId, bucketerParams.experimentId); var bucketValue = module.exports._generateBucketValue(bucketingId); var bucketedUserLogMessage = sprintf(LOG_MESSAGES.USER_ASSIGNED_TO_VARIATION_BUCKET, MODULE_NAME, bucketValue, bucketerParams.userId); bucketerParams.logger.log(LOG_LEVEL.DEBUG, bucketedUserLogMessage); var entityId = module.exports._findBucket(bucketValue, bucketerParams.trafficAllocationConfig); if (entityId === null) { var userHasNoVariationLogMessage = sprintf(LOG_MESSAGES.USER_HAS_NO_VARIATION, MODULE_NAME, bucketerParams.userId, bucketerParams.experimentKey); bucketerParams.logger.log(LOG_LEVEL.DEBUG, userHasNoVariationLogMessage); } else if (entityId === '' || !bucketerParams.variationIdMap.hasOwnProperty(entityId)) { var invalidVariationIdLogMessage = sprintf(LOG_MESSAGES.INVALID_VARIATION_ID, MODULE_NAME); bucketerParams.logger.log(LOG_LEVEL.WARNING, invalidVariationIdLogMessage); return null; } else { var variationKey = bucketerParams.variationIdMap[entityId].key; var userInVariationLogMessage = sprintf(LOG_MESSAGES.USER_HAS_VARIATION, MODULE_NAME, bucketerParams.userId, variationKey, bucketerParams.experimentKey); bucketerParams.logger.log(LOG_LEVEL.INFO, userInVariationLogMessage); } return entityId; }
javascript
function(bucketerParams) { // Check if user is in a random group; if so, check if user is bucketed into a specific experiment var experiment = bucketerParams.experimentKeyMap[bucketerParams.experimentKey]; var groupId = experiment['groupId']; if (groupId) { var group = bucketerParams.groupIdMap[groupId]; if (!group) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_GROUP_ID, MODULE_NAME, groupId)); } if (group.policy === RANDOM_POLICY) { var bucketedExperimentId = module.exports.bucketUserIntoExperiment(group, bucketerParams.bucketingId, bucketerParams.userId, bucketerParams.logger); // Return if user is not bucketed into any experiment if (bucketedExperimentId === null) { var notbucketedInAnyExperimentLogMessage = sprintf(LOG_MESSAGES.USER_NOT_IN_ANY_EXPERIMENT, MODULE_NAME, bucketerParams.userId, groupId); bucketerParams.logger.log(LOG_LEVEL.INFO, notbucketedInAnyExperimentLogMessage); return null; } // Return if user is bucketed into a different experiment than the one specified if (bucketedExperimentId !== bucketerParams.experimentId) { var notBucketedIntoExperimentOfGroupLogMessage = sprintf(LOG_MESSAGES.USER_NOT_BUCKETED_INTO_EXPERIMENT_IN_GROUP, MODULE_NAME, bucketerParams.userId, bucketerParams.experimentKey, groupId); bucketerParams.logger.log(LOG_LEVEL.INFO, notBucketedIntoExperimentOfGroupLogMessage); return null; } // Continue bucketing if user is bucketed into specified experiment var bucketedIntoExperimentOfGroupLogMessage = sprintf(LOG_MESSAGES.USER_BUCKETED_INTO_EXPERIMENT_IN_GROUP, MODULE_NAME, bucketerParams.userId, bucketerParams.experimentKey, groupId); bucketerParams.logger.log(LOG_LEVEL.INFO, bucketedIntoExperimentOfGroupLogMessage); } } var bucketingId = sprintf('%s%s', bucketerParams.bucketingId, bucketerParams.experimentId); var bucketValue = module.exports._generateBucketValue(bucketingId); var bucketedUserLogMessage = sprintf(LOG_MESSAGES.USER_ASSIGNED_TO_VARIATION_BUCKET, MODULE_NAME, bucketValue, bucketerParams.userId); bucketerParams.logger.log(LOG_LEVEL.DEBUG, bucketedUserLogMessage); var entityId = module.exports._findBucket(bucketValue, bucketerParams.trafficAllocationConfig); if (entityId === null) { var userHasNoVariationLogMessage = sprintf(LOG_MESSAGES.USER_HAS_NO_VARIATION, MODULE_NAME, bucketerParams.userId, bucketerParams.experimentKey); bucketerParams.logger.log(LOG_LEVEL.DEBUG, userHasNoVariationLogMessage); } else if (entityId === '' || !bucketerParams.variationIdMap.hasOwnProperty(entityId)) { var invalidVariationIdLogMessage = sprintf(LOG_MESSAGES.INVALID_VARIATION_ID, MODULE_NAME); bucketerParams.logger.log(LOG_LEVEL.WARNING, invalidVariationIdLogMessage); return null; } else { var variationKey = bucketerParams.variationIdMap[entityId].key; var userInVariationLogMessage = sprintf(LOG_MESSAGES.USER_HAS_VARIATION, MODULE_NAME, bucketerParams.userId, variationKey, bucketerParams.experimentKey); bucketerParams.logger.log(LOG_LEVEL.INFO, userInVariationLogMessage); } return entityId; }
[ "function", "(", "bucketerParams", ")", "{", "// Check if user is in a random group; if so, check if user is bucketed into a specific experiment", "var", "experiment", "=", "bucketerParams", ".", "experimentKeyMap", "[", "bucketerParams", ".", "experimentKey", "]", ";", "var", "groupId", "=", "experiment", "[", "'groupId'", "]", ";", "if", "(", "groupId", ")", "{", "var", "group", "=", "bucketerParams", ".", "groupIdMap", "[", "groupId", "]", ";", "if", "(", "!", "group", ")", "{", "throw", "new", "Error", "(", "sprintf", "(", "ERROR_MESSAGES", ".", "INVALID_GROUP_ID", ",", "MODULE_NAME", ",", "groupId", ")", ")", ";", "}", "if", "(", "group", ".", "policy", "===", "RANDOM_POLICY", ")", "{", "var", "bucketedExperimentId", "=", "module", ".", "exports", ".", "bucketUserIntoExperiment", "(", "group", ",", "bucketerParams", ".", "bucketingId", ",", "bucketerParams", ".", "userId", ",", "bucketerParams", ".", "logger", ")", ";", "// Return if user is not bucketed into any experiment", "if", "(", "bucketedExperimentId", "===", "null", ")", "{", "var", "notbucketedInAnyExperimentLogMessage", "=", "sprintf", "(", "LOG_MESSAGES", ".", "USER_NOT_IN_ANY_EXPERIMENT", ",", "MODULE_NAME", ",", "bucketerParams", ".", "userId", ",", "groupId", ")", ";", "bucketerParams", ".", "logger", ".", "log", "(", "LOG_LEVEL", ".", "INFO", ",", "notbucketedInAnyExperimentLogMessage", ")", ";", "return", "null", ";", "}", "// Return if user is bucketed into a different experiment than the one specified", "if", "(", "bucketedExperimentId", "!==", "bucketerParams", ".", "experimentId", ")", "{", "var", "notBucketedIntoExperimentOfGroupLogMessage", "=", "sprintf", "(", "LOG_MESSAGES", ".", "USER_NOT_BUCKETED_INTO_EXPERIMENT_IN_GROUP", ",", "MODULE_NAME", ",", "bucketerParams", ".", "userId", ",", "bucketerParams", ".", "experimentKey", ",", "groupId", ")", ";", "bucketerParams", ".", "logger", ".", "log", "(", "LOG_LEVEL", ".", "INFO", ",", "notBucketedIntoExperimentOfGroupLogMessage", ")", ";", "return", "null", ";", "}", "// Continue bucketing if user is bucketed into specified experiment", "var", "bucketedIntoExperimentOfGroupLogMessage", "=", "sprintf", "(", "LOG_MESSAGES", ".", "USER_BUCKETED_INTO_EXPERIMENT_IN_GROUP", ",", "MODULE_NAME", ",", "bucketerParams", ".", "userId", ",", "bucketerParams", ".", "experimentKey", ",", "groupId", ")", ";", "bucketerParams", ".", "logger", ".", "log", "(", "LOG_LEVEL", ".", "INFO", ",", "bucketedIntoExperimentOfGroupLogMessage", ")", ";", "}", "}", "var", "bucketingId", "=", "sprintf", "(", "'%s%s'", ",", "bucketerParams", ".", "bucketingId", ",", "bucketerParams", ".", "experimentId", ")", ";", "var", "bucketValue", "=", "module", ".", "exports", ".", "_generateBucketValue", "(", "bucketingId", ")", ";", "var", "bucketedUserLogMessage", "=", "sprintf", "(", "LOG_MESSAGES", ".", "USER_ASSIGNED_TO_VARIATION_BUCKET", ",", "MODULE_NAME", ",", "bucketValue", ",", "bucketerParams", ".", "userId", ")", ";", "bucketerParams", ".", "logger", ".", "log", "(", "LOG_LEVEL", ".", "DEBUG", ",", "bucketedUserLogMessage", ")", ";", "var", "entityId", "=", "module", ".", "exports", ".", "_findBucket", "(", "bucketValue", ",", "bucketerParams", ".", "trafficAllocationConfig", ")", ";", "if", "(", "entityId", "===", "null", ")", "{", "var", "userHasNoVariationLogMessage", "=", "sprintf", "(", "LOG_MESSAGES", ".", "USER_HAS_NO_VARIATION", ",", "MODULE_NAME", ",", "bucketerParams", ".", "userId", ",", "bucketerParams", ".", "experimentKey", ")", ";", "bucketerParams", ".", "logger", ".", "log", "(", "LOG_LEVEL", ".", "DEBUG", ",", "userHasNoVariationLogMessage", ")", ";", "}", "else", "if", "(", "entityId", "===", "''", "||", "!", "bucketerParams", ".", "variationIdMap", ".", "hasOwnProperty", "(", "entityId", ")", ")", "{", "var", "invalidVariationIdLogMessage", "=", "sprintf", "(", "LOG_MESSAGES", ".", "INVALID_VARIATION_ID", ",", "MODULE_NAME", ")", ";", "bucketerParams", ".", "logger", ".", "log", "(", "LOG_LEVEL", ".", "WARNING", ",", "invalidVariationIdLogMessage", ")", ";", "return", "null", ";", "}", "else", "{", "var", "variationKey", "=", "bucketerParams", ".", "variationIdMap", "[", "entityId", "]", ".", "key", ";", "var", "userInVariationLogMessage", "=", "sprintf", "(", "LOG_MESSAGES", ".", "USER_HAS_VARIATION", ",", "MODULE_NAME", ",", "bucketerParams", ".", "userId", ",", "variationKey", ",", "bucketerParams", ".", "experimentKey", ")", ";", "bucketerParams", ".", "logger", ".", "log", "(", "LOG_LEVEL", ".", "INFO", ",", "userInVariationLogMessage", ")", ";", "}", "return", "entityId", ";", "}" ]
Determines ID of variation to be shown for the given input params @param {Object} bucketerParams @param {string} bucketerParams.experimentId @param {string} bucketerParams.experimentKey @param {string} bucketerParams.userId @param {Object[]} bucketerParams.trafficAllocationConfig @param {Array} bucketerParams.experimentKeyMap @param {Object} bucketerParams.groupIdMap @param {Object} bucketerParams.variationIdMap @param {string} bucketerParams.varationIdMap[].key @param {Object} bucketerParams.logger @param {string} bucketerParams.bucketingId @return Variation ID that user has been bucketed into, null if user is not bucketed into any experiment
[ "Determines", "ID", "of", "variation", "to", "be", "shown", "for", "the", "given", "input", "params" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/bucketer/index.js#L49-L104
9,893
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/bucketer/index.js
function(group, bucketingId, userId, logger) { var bucketingKey = sprintf('%s%s', bucketingId, group.id); var bucketValue = module.exports._generateBucketValue(bucketingKey); logger.log(LOG_LEVEL.DEBUG, sprintf(LOG_MESSAGES.USER_ASSIGNED_TO_EXPERIMENT_BUCKET, MODULE_NAME, bucketValue, userId)); var trafficAllocationConfig = group.trafficAllocation; var bucketedExperimentId = module.exports._findBucket(bucketValue, trafficAllocationConfig); return bucketedExperimentId; }
javascript
function(group, bucketingId, userId, logger) { var bucketingKey = sprintf('%s%s', bucketingId, group.id); var bucketValue = module.exports._generateBucketValue(bucketingKey); logger.log(LOG_LEVEL.DEBUG, sprintf(LOG_MESSAGES.USER_ASSIGNED_TO_EXPERIMENT_BUCKET, MODULE_NAME, bucketValue, userId)); var trafficAllocationConfig = group.trafficAllocation; var bucketedExperimentId = module.exports._findBucket(bucketValue, trafficAllocationConfig); return bucketedExperimentId; }
[ "function", "(", "group", ",", "bucketingId", ",", "userId", ",", "logger", ")", "{", "var", "bucketingKey", "=", "sprintf", "(", "'%s%s'", ",", "bucketingId", ",", "group", ".", "id", ")", ";", "var", "bucketValue", "=", "module", ".", "exports", ".", "_generateBucketValue", "(", "bucketingKey", ")", ";", "logger", ".", "log", "(", "LOG_LEVEL", ".", "DEBUG", ",", "sprintf", "(", "LOG_MESSAGES", ".", "USER_ASSIGNED_TO_EXPERIMENT_BUCKET", ",", "MODULE_NAME", ",", "bucketValue", ",", "userId", ")", ")", ";", "var", "trafficAllocationConfig", "=", "group", ".", "trafficAllocation", ";", "var", "bucketedExperimentId", "=", "module", ".", "exports", ".", "_findBucket", "(", "bucketValue", ",", "trafficAllocationConfig", ")", ";", "return", "bucketedExperimentId", ";", "}" ]
Returns bucketed experiment ID to compare against experiment user is being called into @param {Object} group Group that experiment is in @param {string} bucketingId Bucketing ID @param {string} userId ID of user to be bucketed into experiment @param {Object} logger Logger implementation @return {string} ID of experiment if user is bucketed into experiment within the group, null otherwise
[ "Returns", "bucketed", "experiment", "ID", "to", "compare", "against", "experiment", "user", "is", "being", "called", "into" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/bucketer/index.js#L114-L121
9,894
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/bucketer/index.js
function(bucketValue, trafficAllocationConfig) { for (var i = 0; i < trafficAllocationConfig.length; i++) { if (bucketValue < trafficAllocationConfig[i].endOfRange) { return trafficAllocationConfig[i].entityId; } } return null; }
javascript
function(bucketValue, trafficAllocationConfig) { for (var i = 0; i < trafficAllocationConfig.length; i++) { if (bucketValue < trafficAllocationConfig[i].endOfRange) { return trafficAllocationConfig[i].entityId; } } return null; }
[ "function", "(", "bucketValue", ",", "trafficAllocationConfig", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "trafficAllocationConfig", ".", "length", ";", "i", "++", ")", "{", "if", "(", "bucketValue", "<", "trafficAllocationConfig", "[", "i", "]", ".", "endOfRange", ")", "{", "return", "trafficAllocationConfig", "[", "i", "]", ".", "entityId", ";", "}", "}", "return", "null", ";", "}" ]
Returns entity ID associated with bucket value @param {string} bucketValue @param {Object[]} trafficAllocationConfig @param {number} trafficAllocationConfig[].endOfRange @param {number} trafficAllocationConfig[].entityId @return {string} Entity ID for bucketing if bucket value is within traffic allocation boundaries, null otherwise
[ "Returns", "entity", "ID", "associated", "with", "bucket", "value" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/bucketer/index.js#L131-L138
9,895
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/bucketer/index.js
function(bucketingKey) { try { // NOTE: the mmh library already does cast the hash value as an unsigned 32bit int // https://github.com/perezd/node-murmurhash/blob/master/murmurhash.js#L115 var hashValue = murmurhash.v3(bucketingKey, HASH_SEED); var ratio = hashValue / MAX_HASH_VALUE; return parseInt(ratio * MAX_TRAFFIC_VALUE, 10); } catch (ex) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_BUCKETING_ID, MODULE_NAME, bucketingKey, ex.message)); } }
javascript
function(bucketingKey) { try { // NOTE: the mmh library already does cast the hash value as an unsigned 32bit int // https://github.com/perezd/node-murmurhash/blob/master/murmurhash.js#L115 var hashValue = murmurhash.v3(bucketingKey, HASH_SEED); var ratio = hashValue / MAX_HASH_VALUE; return parseInt(ratio * MAX_TRAFFIC_VALUE, 10); } catch (ex) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_BUCKETING_ID, MODULE_NAME, bucketingKey, ex.message)); } }
[ "function", "(", "bucketingKey", ")", "{", "try", "{", "// NOTE: the mmh library already does cast the hash value as an unsigned 32bit int", "// https://github.com/perezd/node-murmurhash/blob/master/murmurhash.js#L115", "var", "hashValue", "=", "murmurhash", ".", "v3", "(", "bucketingKey", ",", "HASH_SEED", ")", ";", "var", "ratio", "=", "hashValue", "/", "MAX_HASH_VALUE", ";", "return", "parseInt", "(", "ratio", "*", "MAX_TRAFFIC_VALUE", ",", "10", ")", ";", "}", "catch", "(", "ex", ")", "{", "throw", "new", "Error", "(", "sprintf", "(", "ERROR_MESSAGES", ".", "INVALID_BUCKETING_ID", ",", "MODULE_NAME", ",", "bucketingKey", ",", "ex", ".", "message", ")", ")", ";", "}", "}" ]
Helper function to generate bucket value in half-closed interval [0, MAX_TRAFFIC_VALUE) @param {string} bucketingKey String value for bucketing @return {string} the generated bucket value @throws If bucketing value is not a valid string
[ "Helper", "function", "to", "generate", "bucket", "value", "in", "half", "-", "closed", "interval", "[", "0", "MAX_TRAFFIC_VALUE", ")" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/bucketer/index.js#L146-L156
9,896
optimizely/javascript-sdk
packages/optimizely-sdk/lib/plugins/event_dispatcher/index.browser.js
function(eventObj, callback) { var url = eventObj.url; var params = eventObj.params; if (eventObj.httpVerb === POST_METHOD) { var req = new XMLHttpRequest(); req.open(POST_METHOD, url, true); req.setRequestHeader('Content-Type', 'application/json'); req.onreadystatechange = function() { if (req.readyState === READYSTATE_COMPLETE && callback && typeof callback === 'function') { try { callback(params); } catch (e) { // TODO: Log this somehow (consider adding a logger to the EventDispatcher interface) } } }; req.send(JSON.stringify(params)); } else { // add param for cors headers to be sent by the log endpoint url += '?wxhr=true'; if (params) { url += '&' + toQueryString(params); } var req = new XMLHttpRequest(); req.open(GET_METHOD, url, true); req.onreadystatechange = function() { if (req.readyState === READYSTATE_COMPLETE && callback && typeof callback === 'function') { try { callback(); } catch (e) { // TODO: Log this somehow (consider adding a logger to the EventDispatcher interface) } } }; req.send(); } }
javascript
function(eventObj, callback) { var url = eventObj.url; var params = eventObj.params; if (eventObj.httpVerb === POST_METHOD) { var req = new XMLHttpRequest(); req.open(POST_METHOD, url, true); req.setRequestHeader('Content-Type', 'application/json'); req.onreadystatechange = function() { if (req.readyState === READYSTATE_COMPLETE && callback && typeof callback === 'function') { try { callback(params); } catch (e) { // TODO: Log this somehow (consider adding a logger to the EventDispatcher interface) } } }; req.send(JSON.stringify(params)); } else { // add param for cors headers to be sent by the log endpoint url += '?wxhr=true'; if (params) { url += '&' + toQueryString(params); } var req = new XMLHttpRequest(); req.open(GET_METHOD, url, true); req.onreadystatechange = function() { if (req.readyState === READYSTATE_COMPLETE && callback && typeof callback === 'function') { try { callback(); } catch (e) { // TODO: Log this somehow (consider adding a logger to the EventDispatcher interface) } } }; req.send(); } }
[ "function", "(", "eventObj", ",", "callback", ")", "{", "var", "url", "=", "eventObj", ".", "url", ";", "var", "params", "=", "eventObj", ".", "params", ";", "if", "(", "eventObj", ".", "httpVerb", "===", "POST_METHOD", ")", "{", "var", "req", "=", "new", "XMLHttpRequest", "(", ")", ";", "req", ".", "open", "(", "POST_METHOD", ",", "url", ",", "true", ")", ";", "req", ".", "setRequestHeader", "(", "'Content-Type'", ",", "'application/json'", ")", ";", "req", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "req", ".", "readyState", "===", "READYSTATE_COMPLETE", "&&", "callback", "&&", "typeof", "callback", "===", "'function'", ")", "{", "try", "{", "callback", "(", "params", ")", ";", "}", "catch", "(", "e", ")", "{", "// TODO: Log this somehow (consider adding a logger to the EventDispatcher interface)", "}", "}", "}", ";", "req", ".", "send", "(", "JSON", ".", "stringify", "(", "params", ")", ")", ";", "}", "else", "{", "// add param for cors headers to be sent by the log endpoint", "url", "+=", "'?wxhr=true'", ";", "if", "(", "params", ")", "{", "url", "+=", "'&'", "+", "toQueryString", "(", "params", ")", ";", "}", "var", "req", "=", "new", "XMLHttpRequest", "(", ")", ";", "req", ".", "open", "(", "GET_METHOD", ",", "url", ",", "true", ")", ";", "req", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "req", ".", "readyState", "===", "READYSTATE_COMPLETE", "&&", "callback", "&&", "typeof", "callback", "===", "'function'", ")", "{", "try", "{", "callback", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "// TODO: Log this somehow (consider adding a logger to the EventDispatcher interface)", "}", "}", "}", ";", "req", ".", "send", "(", ")", ";", "}", "}" ]
Sample event dispatcher implementation for tracking impression and conversions Users of the SDK can provide their own implementation @param {Object} eventObj @param {Function} callback
[ "Sample", "event", "dispatcher", "implementation", "for", "tracking", "impression", "and", "conversions", "Users", "of", "the", "SDK", "can", "provide", "their", "own", "implementation" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/plugins/event_dispatcher/index.browser.js#L29-L66
9,897
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/event_builder/index.js
getCommonEventParams
function getCommonEventParams(options) { var attributes = options.attributes; var configObj = options.configObj; var anonymize_ip = configObj.anonymizeIP; var botFiltering = configObj.botFiltering; if (anonymize_ip === null || anonymize_ip === undefined) { anonymize_ip = false; } var visitor = { snapshots: [], visitor_id: options.userId, attributes: [] }; var commonParams = { account_id: configObj.accountId, project_id: configObj.projectId, visitors: [visitor], revision: configObj.revision, client_name: options.clientEngine, client_version: options.clientVersion, anonymize_ip: anonymize_ip, enrich_decisions: true, }; // Omit attribute values that are not supported by the log endpoint. fns.forOwn(attributes, function(attributeValue, attributeKey) { if (attributeValidator.isAttributeValid(attributeKey, attributeValue)) { var attributeId = projectConfig.getAttributeId(options.configObj, attributeKey, options.logger); if (attributeId) { commonParams.visitors[0].attributes.push({ entity_id: attributeId, key: attributeKey, type: CUSTOM_ATTRIBUTE_FEATURE_TYPE, value: attributes[attributeKey], }); } } }); if (typeof botFiltering === 'boolean') { commonParams.visitors[0].attributes.push({ entity_id: enums.CONTROL_ATTRIBUTES.BOT_FILTERING, key: enums.CONTROL_ATTRIBUTES.BOT_FILTERING, type: CUSTOM_ATTRIBUTE_FEATURE_TYPE, value: botFiltering, }); } return commonParams; }
javascript
function getCommonEventParams(options) { var attributes = options.attributes; var configObj = options.configObj; var anonymize_ip = configObj.anonymizeIP; var botFiltering = configObj.botFiltering; if (anonymize_ip === null || anonymize_ip === undefined) { anonymize_ip = false; } var visitor = { snapshots: [], visitor_id: options.userId, attributes: [] }; var commonParams = { account_id: configObj.accountId, project_id: configObj.projectId, visitors: [visitor], revision: configObj.revision, client_name: options.clientEngine, client_version: options.clientVersion, anonymize_ip: anonymize_ip, enrich_decisions: true, }; // Omit attribute values that are not supported by the log endpoint. fns.forOwn(attributes, function(attributeValue, attributeKey) { if (attributeValidator.isAttributeValid(attributeKey, attributeValue)) { var attributeId = projectConfig.getAttributeId(options.configObj, attributeKey, options.logger); if (attributeId) { commonParams.visitors[0].attributes.push({ entity_id: attributeId, key: attributeKey, type: CUSTOM_ATTRIBUTE_FEATURE_TYPE, value: attributes[attributeKey], }); } } }); if (typeof botFiltering === 'boolean') { commonParams.visitors[0].attributes.push({ entity_id: enums.CONTROL_ATTRIBUTES.BOT_FILTERING, key: enums.CONTROL_ATTRIBUTES.BOT_FILTERING, type: CUSTOM_ATTRIBUTE_FEATURE_TYPE, value: botFiltering, }); } return commonParams; }
[ "function", "getCommonEventParams", "(", "options", ")", "{", "var", "attributes", "=", "options", ".", "attributes", ";", "var", "configObj", "=", "options", ".", "configObj", ";", "var", "anonymize_ip", "=", "configObj", ".", "anonymizeIP", ";", "var", "botFiltering", "=", "configObj", ".", "botFiltering", ";", "if", "(", "anonymize_ip", "===", "null", "||", "anonymize_ip", "===", "undefined", ")", "{", "anonymize_ip", "=", "false", ";", "}", "var", "visitor", "=", "{", "snapshots", ":", "[", "]", ",", "visitor_id", ":", "options", ".", "userId", ",", "attributes", ":", "[", "]", "}", ";", "var", "commonParams", "=", "{", "account_id", ":", "configObj", ".", "accountId", ",", "project_id", ":", "configObj", ".", "projectId", ",", "visitors", ":", "[", "visitor", "]", ",", "revision", ":", "configObj", ".", "revision", ",", "client_name", ":", "options", ".", "clientEngine", ",", "client_version", ":", "options", ".", "clientVersion", ",", "anonymize_ip", ":", "anonymize_ip", ",", "enrich_decisions", ":", "true", ",", "}", ";", "// Omit attribute values that are not supported by the log endpoint.", "fns", ".", "forOwn", "(", "attributes", ",", "function", "(", "attributeValue", ",", "attributeKey", ")", "{", "if", "(", "attributeValidator", ".", "isAttributeValid", "(", "attributeKey", ",", "attributeValue", ")", ")", "{", "var", "attributeId", "=", "projectConfig", ".", "getAttributeId", "(", "options", ".", "configObj", ",", "attributeKey", ",", "options", ".", "logger", ")", ";", "if", "(", "attributeId", ")", "{", "commonParams", ".", "visitors", "[", "0", "]", ".", "attributes", ".", "push", "(", "{", "entity_id", ":", "attributeId", ",", "key", ":", "attributeKey", ",", "type", ":", "CUSTOM_ATTRIBUTE_FEATURE_TYPE", ",", "value", ":", "attributes", "[", "attributeKey", "]", ",", "}", ")", ";", "}", "}", "}", ")", ";", "if", "(", "typeof", "botFiltering", "===", "'boolean'", ")", "{", "commonParams", ".", "visitors", "[", "0", "]", ".", "attributes", ".", "push", "(", "{", "entity_id", ":", "enums", ".", "CONTROL_ATTRIBUTES", ".", "BOT_FILTERING", ",", "key", ":", "enums", ".", "CONTROL_ATTRIBUTES", ".", "BOT_FILTERING", ",", "type", ":", "CUSTOM_ATTRIBUTE_FEATURE_TYPE", ",", "value", ":", "botFiltering", ",", "}", ")", ";", "}", "return", "commonParams", ";", "}" ]
Get params which are used same in both conversion and impression events @param {Object} options.attributes Object representing user attributes and values which need to be recorded @param {string} options.clientEngine The client we are using: node or javascript @param {string} options.clientVersion The version of the client @param {Object} options.configObj Object representing project configuration, including datafile information and mappings for quick lookup @param {string} options.userId ID for user @param {Object} options.Logger logger @return {Object} Common params with properties that are used in both conversion and impression events
[ "Get", "params", "which", "are", "used", "same", "in", "both", "conversion", "and", "impression", "events" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/event_builder/index.js#L37-L87
9,898
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/event_builder/index.js
getImpressionEventParams
function getImpressionEventParams(configObj, experimentId, variationId) { var impressionEventParams = { decisions: [{ campaign_id: projectConfig.getLayerId(configObj, experimentId), experiment_id: experimentId, variation_id: variationId, }], events: [{ entity_id: projectConfig.getLayerId(configObj, experimentId), timestamp: fns.currentTimestamp(), key: ACTIVATE_EVENT_KEY, uuid: fns.uuid(), }] }; return impressionEventParams; }
javascript
function getImpressionEventParams(configObj, experimentId, variationId) { var impressionEventParams = { decisions: [{ campaign_id: projectConfig.getLayerId(configObj, experimentId), experiment_id: experimentId, variation_id: variationId, }], events: [{ entity_id: projectConfig.getLayerId(configObj, experimentId), timestamp: fns.currentTimestamp(), key: ACTIVATE_EVENT_KEY, uuid: fns.uuid(), }] }; return impressionEventParams; }
[ "function", "getImpressionEventParams", "(", "configObj", ",", "experimentId", ",", "variationId", ")", "{", "var", "impressionEventParams", "=", "{", "decisions", ":", "[", "{", "campaign_id", ":", "projectConfig", ".", "getLayerId", "(", "configObj", ",", "experimentId", ")", ",", "experiment_id", ":", "experimentId", ",", "variation_id", ":", "variationId", ",", "}", "]", ",", "events", ":", "[", "{", "entity_id", ":", "projectConfig", ".", "getLayerId", "(", "configObj", ",", "experimentId", ")", ",", "timestamp", ":", "fns", ".", "currentTimestamp", "(", ")", ",", "key", ":", "ACTIVATE_EVENT_KEY", ",", "uuid", ":", "fns", ".", "uuid", "(", ")", ",", "}", "]", "}", ";", "return", "impressionEventParams", ";", "}" ]
Creates object of params specific to impression events @param {Object} configObj Object representing project configuration @param {string} experimentId ID of experiment for which impression needs to be recorded @param {string} variationId ID for variation which would be presented to user @return {Object} Impression event params
[ "Creates", "object", "of", "params", "specific", "to", "impression", "events" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/event_builder/index.js#L96-L112
9,899
optimizely/javascript-sdk
packages/optimizely-sdk/lib/core/event_builder/index.js
getVisitorSnapshot
function getVisitorSnapshot(configObj, eventKey, eventTags, logger) { var snapshot = { events: [] }; var eventDict = { entity_id: projectConfig.getEventId(configObj, eventKey), timestamp: fns.currentTimestamp(), uuid: fns.uuid(), key: eventKey, }; if (eventTags) { var revenue = eventTagUtils.getRevenueValue(eventTags, logger); if (revenue !== null) { eventDict[enums.RESERVED_EVENT_KEYWORDS.REVENUE] = revenue; } var eventValue = eventTagUtils.getEventValue(eventTags, logger); if (eventValue !== null) { eventDict[enums.RESERVED_EVENT_KEYWORDS.VALUE] = eventValue; } eventDict['tags'] = eventTags; } snapshot.events.push(eventDict); return snapshot; }
javascript
function getVisitorSnapshot(configObj, eventKey, eventTags, logger) { var snapshot = { events: [] }; var eventDict = { entity_id: projectConfig.getEventId(configObj, eventKey), timestamp: fns.currentTimestamp(), uuid: fns.uuid(), key: eventKey, }; if (eventTags) { var revenue = eventTagUtils.getRevenueValue(eventTags, logger); if (revenue !== null) { eventDict[enums.RESERVED_EVENT_KEYWORDS.REVENUE] = revenue; } var eventValue = eventTagUtils.getEventValue(eventTags, logger); if (eventValue !== null) { eventDict[enums.RESERVED_EVENT_KEYWORDS.VALUE] = eventValue; } eventDict['tags'] = eventTags; } snapshot.events.push(eventDict); return snapshot; }
[ "function", "getVisitorSnapshot", "(", "configObj", ",", "eventKey", ",", "eventTags", ",", "logger", ")", "{", "var", "snapshot", "=", "{", "events", ":", "[", "]", "}", ";", "var", "eventDict", "=", "{", "entity_id", ":", "projectConfig", ".", "getEventId", "(", "configObj", ",", "eventKey", ")", ",", "timestamp", ":", "fns", ".", "currentTimestamp", "(", ")", ",", "uuid", ":", "fns", ".", "uuid", "(", ")", ",", "key", ":", "eventKey", ",", "}", ";", "if", "(", "eventTags", ")", "{", "var", "revenue", "=", "eventTagUtils", ".", "getRevenueValue", "(", "eventTags", ",", "logger", ")", ";", "if", "(", "revenue", "!==", "null", ")", "{", "eventDict", "[", "enums", ".", "RESERVED_EVENT_KEYWORDS", ".", "REVENUE", "]", "=", "revenue", ";", "}", "var", "eventValue", "=", "eventTagUtils", ".", "getEventValue", "(", "eventTags", ",", "logger", ")", ";", "if", "(", "eventValue", "!==", "null", ")", "{", "eventDict", "[", "enums", ".", "RESERVED_EVENT_KEYWORDS", ".", "VALUE", "]", "=", "eventValue", ";", "}", "eventDict", "[", "'tags'", "]", "=", "eventTags", ";", "}", "snapshot", ".", "events", ".", "push", "(", "eventDict", ")", ";", "return", "snapshot", ";", "}" ]
Creates object of params specific to conversion events @param {Object} configObj Object representing project configuration @param {string} eventKey Event key representing the event which needs to be recorded @param {Object} eventTags Values associated with the event. @param {Object} logger Logger object @return {Object} Conversion event params
[ "Creates", "object", "of", "params", "specific", "to", "conversion", "events" ]
39c3b2d97388100abd1c25d355a71c72b17363be
https://github.com/optimizely/javascript-sdk/blob/39c3b2d97388100abd1c25d355a71c72b17363be/packages/optimizely-sdk/lib/core/event_builder/index.js#L122-L150