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
21,300
sourcejs/Source
core/api/index.js
function (req, res, dataPath) { var body = req.body; var data = body.data; var dataUnflatten = body.unflatten; if (dataUnflatten) { data = unflatten(data, { delimiter: '/', overwrite: 'root' }); } htmlTree.writeDataFile(data, true, dataPath, function(err, finalData){ if (err || !finalData) { res.status(config.statusCodes.error).json({ message: err }); } else { res.status(config.statusCodes.OK).json(finalData); } }); }
javascript
function (req, res, dataPath) { var body = req.body; var data = body.data; var dataUnflatten = body.unflatten; if (dataUnflatten) { data = unflatten(data, { delimiter: '/', overwrite: 'root' }); } htmlTree.writeDataFile(data, true, dataPath, function(err, finalData){ if (err || !finalData) { res.status(config.statusCodes.error).json({ message: err }); } else { res.status(config.statusCodes.OK).json(finalData); } }); }
[ "function", "(", "req", ",", "res", ",", "dataPath", ")", "{", "var", "body", "=", "req", ".", "body", ";", "var", "data", "=", "body", ".", "data", ";", "var", "dataUnflatten", "=", "body", ".", "unflatten", ";", "if", "(", "dataUnflatten", ")", "{", "data", "=", "unflatten", "(", "data", ",", "{", "delimiter", ":", "'/'", ",", "overwrite", ":", "'root'", "}", ")", ";", "}", "htmlTree", ".", "writeDataFile", "(", "data", ",", "true", ",", "dataPath", ",", "function", "(", "err", ",", "finalData", ")", "{", "if", "(", "err", "||", "!", "finalData", ")", "{", "res", ".", "status", "(", "config", ".", "statusCodes", ".", "error", ")", ".", "json", "(", "{", "message", ":", "err", "}", ")", ";", "}", "else", "{", "res", ".", "status", "(", "config", ".", "statusCodes", ".", "OK", ")", ".", "json", "(", "finalData", ")", ";", "}", "}", ")", ";", "}" ]
postHTML REST api processor @param {Object} req - express request @param {Object} req.body.data - data to write @param {Boolean} req.body.unflatten - set true, to unflat tree from 'base/spec' @param {Object} res - express response @param {String} dataPath - custom data storage path Writes result to res object
[ "postHTML", "REST", "api", "processor" ]
e6461409302486c5db1085bb44a81f310403eb90
https://github.com/sourcejs/Source/blob/e6461409302486c5db1085bb44a81f310403eb90/core/api/index.js#L151-L169
21,301
sourcejs/Source
core/api/index.js
function (req, res, dataPath) { var body = req.body; var reqID = body.id || req.query.id; htmlTree.deleteFromDataFile(dataPath, reqID, function(err, finalData){ if (err || !finalData) { res.status(config.statusCodes.error).json({ message: err }); } else { res.status(config.statusCodes.OK).json(finalData); } }); }
javascript
function (req, res, dataPath) { var body = req.body; var reqID = body.id || req.query.id; htmlTree.deleteFromDataFile(dataPath, reqID, function(err, finalData){ if (err || !finalData) { res.status(config.statusCodes.error).json({ message: err }); } else { res.status(config.statusCodes.OK).json(finalData); } }); }
[ "function", "(", "req", ",", "res", ",", "dataPath", ")", "{", "var", "body", "=", "req", ".", "body", ";", "var", "reqID", "=", "body", ".", "id", "||", "req", ".", "query", ".", "id", ";", "htmlTree", ".", "deleteFromDataFile", "(", "dataPath", ",", "reqID", ",", "function", "(", "err", ",", "finalData", ")", "{", "if", "(", "err", "||", "!", "finalData", ")", "{", "res", ".", "status", "(", "config", ".", "statusCodes", ".", "error", ")", ".", "json", "(", "{", "message", ":", "err", "}", ")", ";", "}", "else", "{", "res", ".", "status", "(", "config", ".", "statusCodes", ".", "OK", ")", ".", "json", "(", "finalData", ")", ";", "}", "}", ")", ";", "}" ]
postHTML DELETE api processor @param {Object} req - express request @param {Object} req.body.path - data path for deletion @param {Object} res - express response @param {String} dataPath - custom data storage path Writes result to res object
[ "postHTML", "DELETE", "api", "processor" ]
e6461409302486c5db1085bb44a81f310403eb90
https://github.com/sourcejs/Source/blob/e6461409302486c5db1085bb44a81f310403eb90/core/api/index.js#L182-L195
21,302
sourcejs/Source
assets/js/modules/sectionFolding.js
function() { var navHash = utils.parseNavHash(); openSpoiler($(navHash)); //Close other closed by default sections for (var i = 0; i < sectionsOnPage.length; i++) { var t = $(sectionsOnPage[i]); var tID = t.attr('id'); if (t.attr('data-def-stat') === 'closed' && navHash !== '#' + tID) { closeSpoiler(t); } } if (navHash !== '') { utils.scrollToSection(navHash); } }
javascript
function() { var navHash = utils.parseNavHash(); openSpoiler($(navHash)); //Close other closed by default sections for (var i = 0; i < sectionsOnPage.length; i++) { var t = $(sectionsOnPage[i]); var tID = t.attr('id'); if (t.attr('data-def-stat') === 'closed' && navHash !== '#' + tID) { closeSpoiler(t); } } if (navHash !== '') { utils.scrollToSection(navHash); } }
[ "function", "(", ")", "{", "var", "navHash", "=", "utils", ".", "parseNavHash", "(", ")", ";", "openSpoiler", "(", "$", "(", "navHash", ")", ")", ";", "//Close other closed by default sections", "for", "(", "var", "i", "=", "0", ";", "i", "<", "sectionsOnPage", ".", "length", ";", "i", "++", ")", "{", "var", "t", "=", "$", "(", "sectionsOnPage", "[", "i", "]", ")", ";", "var", "tID", "=", "t", ".", "attr", "(", "'id'", ")", ";", "if", "(", "t", ".", "attr", "(", "'data-def-stat'", ")", "===", "'closed'", "&&", "navHash", "!==", "'#'", "+", "tID", ")", "{", "closeSpoiler", "(", "t", ")", ";", "}", "}", "if", "(", "navHash", "!==", "''", ")", "{", "utils", ".", "scrollToSection", "(", "navHash", ")", ";", "}", "}" ]
To open sections on from inner navigation
[ "To", "open", "sections", "on", "from", "inner", "navigation" ]
e6461409302486c5db1085bb44a81f310403eb90
https://github.com/sourcejs/Source/blob/e6461409302486c5db1085bb44a81f310403eb90/assets/js/modules/sectionFolding.js#L171-L189
21,303
sourcejs/Source
assets/js/lib/modalbox.js
function(config, data) { var isNewInstance = !context; context = context || this; context.data = data ? data : initialBlocksData; if (!isNewInstance) { context.render(); return context; } var modulesOptions = context.options.modulesOptions; modulesOptions.modalBox = $.extend(true, { "classes": { "box": [context.options.mainClass, context.options.colMain, "source_modal_box"].join(' '), "title": "source_modal_title", "body": "source_modal_body", "close": "source_modal_close" }, "labels": { "close": "Close extended search results" }, "appendTo": ".source_main" }, modulesOptions.modalBox, config); context.init(); }
javascript
function(config, data) { var isNewInstance = !context; context = context || this; context.data = data ? data : initialBlocksData; if (!isNewInstance) { context.render(); return context; } var modulesOptions = context.options.modulesOptions; modulesOptions.modalBox = $.extend(true, { "classes": { "box": [context.options.mainClass, context.options.colMain, "source_modal_box"].join(' '), "title": "source_modal_title", "body": "source_modal_body", "close": "source_modal_close" }, "labels": { "close": "Close extended search results" }, "appendTo": ".source_main" }, modulesOptions.modalBox, config); context.init(); }
[ "function", "(", "config", ",", "data", ")", "{", "var", "isNewInstance", "=", "!", "context", ";", "context", "=", "context", "||", "this", ";", "context", ".", "data", "=", "data", "?", "data", ":", "initialBlocksData", ";", "if", "(", "!", "isNewInstance", ")", "{", "context", ".", "render", "(", ")", ";", "return", "context", ";", "}", "var", "modulesOptions", "=", "context", ".", "options", ".", "modulesOptions", ";", "modulesOptions", ".", "modalBox", "=", "$", ".", "extend", "(", "true", ",", "{", "\"classes\"", ":", "{", "\"box\"", ":", "[", "context", ".", "options", ".", "mainClass", ",", "context", ".", "options", ".", "colMain", ",", "\"source_modal_box\"", "]", ".", "join", "(", "' '", ")", ",", "\"title\"", ":", "\"source_modal_title\"", ",", "\"body\"", ":", "\"source_modal_body\"", ",", "\"close\"", ":", "\"source_modal_close\"", "}", ",", "\"labels\"", ":", "{", "\"close\"", ":", "\"Close extended search results\"", "}", ",", "\"appendTo\"", ":", "\".source_main\"", "}", ",", "modulesOptions", ".", "modalBox", ",", "config", ")", ";", "context", ".", "init", "(", ")", ";", "}" ]
instance of box
[ "instance", "of", "box" ]
e6461409302486c5db1085bb44a81f310403eb90
https://github.com/sourcejs/Source/blob/e6461409302486c5db1085bb44a81f310403eb90/assets/js/lib/modalbox.js#L10-L35
21,304
sourcejs/Source
assets/js/modules/codeSource.js
function() { new Css('/source/assets/js/lib/prism/prism.css', 'core'); var selection = onlyStatic ? $('.source_section pre[class*="src-"].source_visible > code') : $('.source_section pre[class*="src-"] > code'); selection.each(function () { var _this = $(this); var parent = _this.parent(); var langClass=''; if (!parent.hasClass('src-json')) { if (parent.hasClass('src-css')) { langClass = SourceCodeToggleCSS; } else if (parent.hasClass('src-js')) { langClass = SourceCodeToggleJS; } else { langClass = SourceCodeToggleHTML; } if (parent.hasClass('source_visible')) { parent.wrap('<div class="'+SourceCode+' '+SourceCodeStatic+'"><div class="' + SourceCodeCnt + '"></div></div>'); } else if (!parent.hasClass('src-json')) { parent.wrap('<div class="'+SourceCode+'"><div class="' + SourceCodeCnt + '"></div></div>'); _this.closest('.' + SourceCode).prepend('' + '<a href="" class="' + SourceCodeToggle + ' ' + langClass + '"><span class="source_hide">' + RES_HIDE_CODE + '</span><span class="source_show">' + RES_SHOW_CODE + '</span> ' + RES_CODE + '</a>' + ''); } Prism.highlightElement(_this[0]); } }); }
javascript
function() { new Css('/source/assets/js/lib/prism/prism.css', 'core'); var selection = onlyStatic ? $('.source_section pre[class*="src-"].source_visible > code') : $('.source_section pre[class*="src-"] > code'); selection.each(function () { var _this = $(this); var parent = _this.parent(); var langClass=''; if (!parent.hasClass('src-json')) { if (parent.hasClass('src-css')) { langClass = SourceCodeToggleCSS; } else if (parent.hasClass('src-js')) { langClass = SourceCodeToggleJS; } else { langClass = SourceCodeToggleHTML; } if (parent.hasClass('source_visible')) { parent.wrap('<div class="'+SourceCode+' '+SourceCodeStatic+'"><div class="' + SourceCodeCnt + '"></div></div>'); } else if (!parent.hasClass('src-json')) { parent.wrap('<div class="'+SourceCode+'"><div class="' + SourceCodeCnt + '"></div></div>'); _this.closest('.' + SourceCode).prepend('' + '<a href="" class="' + SourceCodeToggle + ' ' + langClass + '"><span class="source_hide">' + RES_HIDE_CODE + '</span><span class="source_show">' + RES_SHOW_CODE + '</span> ' + RES_CODE + '</a>' + ''); } Prism.highlightElement(_this[0]); } }); }
[ "function", "(", ")", "{", "new", "Css", "(", "'/source/assets/js/lib/prism/prism.css'", ",", "'core'", ")", ";", "var", "selection", "=", "onlyStatic", "?", "$", "(", "'.source_section pre[class*=\"src-\"].source_visible > code'", ")", ":", "$", "(", "'.source_section pre[class*=\"src-\"] > code'", ")", ";", "selection", ".", "each", "(", "function", "(", ")", "{", "var", "_this", "=", "$", "(", "this", ")", ";", "var", "parent", "=", "_this", ".", "parent", "(", ")", ";", "var", "langClass", "=", "''", ";", "if", "(", "!", "parent", ".", "hasClass", "(", "'src-json'", ")", ")", "{", "if", "(", "parent", ".", "hasClass", "(", "'src-css'", ")", ")", "{", "langClass", "=", "SourceCodeToggleCSS", ";", "}", "else", "if", "(", "parent", ".", "hasClass", "(", "'src-js'", ")", ")", "{", "langClass", "=", "SourceCodeToggleJS", ";", "}", "else", "{", "langClass", "=", "SourceCodeToggleHTML", ";", "}", "if", "(", "parent", ".", "hasClass", "(", "'source_visible'", ")", ")", "{", "parent", ".", "wrap", "(", "'<div class=\"'", "+", "SourceCode", "+", "' '", "+", "SourceCodeStatic", "+", "'\"><div class=\"'", "+", "SourceCodeCnt", "+", "'\"></div></div>'", ")", ";", "}", "else", "if", "(", "!", "parent", ".", "hasClass", "(", "'src-json'", ")", ")", "{", "parent", ".", "wrap", "(", "'<div class=\"'", "+", "SourceCode", "+", "'\"><div class=\"'", "+", "SourceCodeCnt", "+", "'\"></div></div>'", ")", ";", "_this", ".", "closest", "(", "'.'", "+", "SourceCode", ")", ".", "prepend", "(", "''", "+", "'<a href=\"\" class=\"'", "+", "SourceCodeToggle", "+", "' '", "+", "langClass", "+", "'\"><span class=\"source_hide\">'", "+", "RES_HIDE_CODE", "+", "'</span><span class=\"source_show\">'", "+", "RES_SHOW_CODE", "+", "'</span> '", "+", "RES_CODE", "+", "'</a>'", "+", "''", ")", ";", "}", "Prism", ".", "highlightElement", "(", "_this", "[", "0", "]", ")", ";", "}", "}", ")", ";", "}" ]
Code show toggle on each code block
[ "Code", "show", "toggle", "on", "each", "code", "block" ]
e6461409302486c5db1085bb44a81f310403eb90
https://github.com/sourcejs/Source/blob/e6461409302486c5db1085bb44a81f310403eb90/assets/js/modules/codeSource.js#L116-L143
21,305
sourcejs/Source
assets/js/modules/codeSource.js
function() { $('.source_container').on('click', '.' + SourceCodeToggle, function (e) { e.preventDefault(); var codeCnt = $(this).closest('.' + SourceCode); codeCnt.toggleClass(SourceCodeMin); }); }
javascript
function() { $('.source_container').on('click', '.' + SourceCodeToggle, function (e) { e.preventDefault(); var codeCnt = $(this).closest('.' + SourceCode); codeCnt.toggleClass(SourceCodeMin); }); }
[ "function", "(", ")", "{", "$", "(", "'.source_container'", ")", ".", "on", "(", "'click'", ",", "'.'", "+", "SourceCodeToggle", ",", "function", "(", "e", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "var", "codeCnt", "=", "$", "(", "this", ")", ".", "closest", "(", "'.'", "+", "SourceCode", ")", ";", "codeCnt", ".", "toggleClass", "(", "SourceCodeMin", ")", ";", "}", ")", ";", "}" ]
Toggle show source sections
[ "Toggle", "show", "source", "sections" ]
e6461409302486c5db1085bb44a81f310403eb90
https://github.com/sourcejs/Source/blob/e6461409302486c5db1085bb44a81f310403eb90/assets/js/modules/codeSource.js#L182-L188
21,306
sourcejs/Source
assets/js/modules/navHighlight.js
function () { var headersLength = sourceHeaders.length; var minDistance = Number.MAX_VALUE; var closestHeader = -1; var fileNameInUrl = filename === '' ? '' : filename + '.' + extension; if ((document.body.scrollTop || document.documentElement.scrollTop) < hashThreshold) { if (!!window.location.hash) { currentHeader = -1; if (!!(window.history && history.pushState)) { window.history.replaceState({anchor: 0}, document.title, window.location.pathname); } } return; } // catch section which is closed for top window border for (var i=0; i < headersLength; i++) { if ((sourceHeaders[i].tagName === 'H3') && (!utils.hasClass(utils.closest(sourceHeaders[i], 'source_section'), 'source_section__open')) ) { continue; } var currentDist = Math.abs( utils.offsetTop(sourceHeaders[i]) - 60 - window.pageYOffset ); //60 = Header heights if (currentDist < minDistance) { closestHeader = i; minDistance = currentDist; } } if (closestHeader !== currentHeader) { utils.removeClass( document.querySelector('.source_main_nav_li.__active'), '__active'); utils.removeClass( document.querySelector('.source_main_nav_a.__active'), '__active'); utils.addClass(navHeaders[closestHeader], '__active'); var parent = utils.closest(navHeaders[closestHeader], 'source_main_nav_li'); var hashFromLink = navHeaders[closestHeader].getAttribute('href'); if (!!parent && parent) { utils.addClass(parent, '__active'); } if (_this.conf.updateHash) { // TODO: pause hash change when scrolling - append it only on stand-still // Modern browsers uses history API for correct back-button-browser functionality if (!!(window.history && history.pushState)) { window.history.replaceState({anchor: closestHeader+1}, document.title, fileNameInUrl + hashFromLink); } else { // ie9 fallback window.location.hash = hashFromLink; } } currentHeader = closestHeader; } }
javascript
function () { var headersLength = sourceHeaders.length; var minDistance = Number.MAX_VALUE; var closestHeader = -1; var fileNameInUrl = filename === '' ? '' : filename + '.' + extension; if ((document.body.scrollTop || document.documentElement.scrollTop) < hashThreshold) { if (!!window.location.hash) { currentHeader = -1; if (!!(window.history && history.pushState)) { window.history.replaceState({anchor: 0}, document.title, window.location.pathname); } } return; } // catch section which is closed for top window border for (var i=0; i < headersLength; i++) { if ((sourceHeaders[i].tagName === 'H3') && (!utils.hasClass(utils.closest(sourceHeaders[i], 'source_section'), 'source_section__open')) ) { continue; } var currentDist = Math.abs( utils.offsetTop(sourceHeaders[i]) - 60 - window.pageYOffset ); //60 = Header heights if (currentDist < minDistance) { closestHeader = i; minDistance = currentDist; } } if (closestHeader !== currentHeader) { utils.removeClass( document.querySelector('.source_main_nav_li.__active'), '__active'); utils.removeClass( document.querySelector('.source_main_nav_a.__active'), '__active'); utils.addClass(navHeaders[closestHeader], '__active'); var parent = utils.closest(navHeaders[closestHeader], 'source_main_nav_li'); var hashFromLink = navHeaders[closestHeader].getAttribute('href'); if (!!parent && parent) { utils.addClass(parent, '__active'); } if (_this.conf.updateHash) { // TODO: pause hash change when scrolling - append it only on stand-still // Modern browsers uses history API for correct back-button-browser functionality if (!!(window.history && history.pushState)) { window.history.replaceState({anchor: closestHeader+1}, document.title, fileNameInUrl + hashFromLink); } else { // ie9 fallback window.location.hash = hashFromLink; } } currentHeader = closestHeader; } }
[ "function", "(", ")", "{", "var", "headersLength", "=", "sourceHeaders", ".", "length", ";", "var", "minDistance", "=", "Number", ".", "MAX_VALUE", ";", "var", "closestHeader", "=", "-", "1", ";", "var", "fileNameInUrl", "=", "filename", "===", "''", "?", "''", ":", "filename", "+", "'.'", "+", "extension", ";", "if", "(", "(", "document", ".", "body", ".", "scrollTop", "||", "document", ".", "documentElement", ".", "scrollTop", ")", "<", "hashThreshold", ")", "{", "if", "(", "!", "!", "window", ".", "location", ".", "hash", ")", "{", "currentHeader", "=", "-", "1", ";", "if", "(", "!", "!", "(", "window", ".", "history", "&&", "history", ".", "pushState", ")", ")", "{", "window", ".", "history", ".", "replaceState", "(", "{", "anchor", ":", "0", "}", ",", "document", ".", "title", ",", "window", ".", "location", ".", "pathname", ")", ";", "}", "}", "return", ";", "}", "// catch section which is closed for top window border", "for", "(", "var", "i", "=", "0", ";", "i", "<", "headersLength", ";", "i", "++", ")", "{", "if", "(", "(", "sourceHeaders", "[", "i", "]", ".", "tagName", "===", "'H3'", ")", "&&", "(", "!", "utils", ".", "hasClass", "(", "utils", ".", "closest", "(", "sourceHeaders", "[", "i", "]", ",", "'source_section'", ")", ",", "'source_section__open'", ")", ")", ")", "{", "continue", ";", "}", "var", "currentDist", "=", "Math", ".", "abs", "(", "utils", ".", "offsetTop", "(", "sourceHeaders", "[", "i", "]", ")", "-", "60", "-", "window", ".", "pageYOffset", ")", ";", "//60 = Header heights", "if", "(", "currentDist", "<", "minDistance", ")", "{", "closestHeader", "=", "i", ";", "minDistance", "=", "currentDist", ";", "}", "}", "if", "(", "closestHeader", "!==", "currentHeader", ")", "{", "utils", ".", "removeClass", "(", "document", ".", "querySelector", "(", "'.source_main_nav_li.__active'", ")", ",", "'__active'", ")", ";", "utils", ".", "removeClass", "(", "document", ".", "querySelector", "(", "'.source_main_nav_a.__active'", ")", ",", "'__active'", ")", ";", "utils", ".", "addClass", "(", "navHeaders", "[", "closestHeader", "]", ",", "'__active'", ")", ";", "var", "parent", "=", "utils", ".", "closest", "(", "navHeaders", "[", "closestHeader", "]", ",", "'source_main_nav_li'", ")", ";", "var", "hashFromLink", "=", "navHeaders", "[", "closestHeader", "]", ".", "getAttribute", "(", "'href'", ")", ";", "if", "(", "!", "!", "parent", "&&", "parent", ")", "{", "utils", ".", "addClass", "(", "parent", ",", "'__active'", ")", ";", "}", "if", "(", "_this", ".", "conf", ".", "updateHash", ")", "{", "// TODO: pause hash change when scrolling - append it only on stand-still", "// Modern browsers uses history API for correct back-button-browser functionality", "if", "(", "!", "!", "(", "window", ".", "history", "&&", "history", ".", "pushState", ")", ")", "{", "window", ".", "history", ".", "replaceState", "(", "{", "anchor", ":", "closestHeader", "+", "1", "}", ",", "document", ".", "title", ",", "fileNameInUrl", "+", "hashFromLink", ")", ";", "}", "else", "{", "// ie9 fallback", "window", ".", "location", ".", "hash", "=", "hashFromLink", ";", "}", "}", "currentHeader", "=", "closestHeader", ";", "}", "}" ]
watch headers position
[ "watch", "headers", "position" ]
e6461409302486c5db1085bb44a81f310403eb90
https://github.com/sourcejs/Source/blob/e6461409302486c5db1085bb44a81f310403eb90/assets/js/modules/navHighlight.js#L92-L151
21,307
sourcejs/Source
assets/js/lib/jquery.couch.js
function(options, section, option, value) { var req = {url: this.urlPrefix + "/_config/"}; if (section) { req.url += encodeURIComponent(section) + "/"; if (option) { req.url += encodeURIComponent(option); } } if (value === null) { req.type = "DELETE"; } else if (value !== undefined) { req.type = "PUT"; req.data = toJSON(value); req.contentType = "application/json"; req.processData = false } ajax(req, options, "An error occurred retrieving/updating the server configuration" ); }
javascript
function(options, section, option, value) { var req = {url: this.urlPrefix + "/_config/"}; if (section) { req.url += encodeURIComponent(section) + "/"; if (option) { req.url += encodeURIComponent(option); } } if (value === null) { req.type = "DELETE"; } else if (value !== undefined) { req.type = "PUT"; req.data = toJSON(value); req.contentType = "application/json"; req.processData = false } ajax(req, options, "An error occurred retrieving/updating the server configuration" ); }
[ "function", "(", "options", ",", "section", ",", "option", ",", "value", ")", "{", "var", "req", "=", "{", "url", ":", "this", ".", "urlPrefix", "+", "\"/_config/\"", "}", ";", "if", "(", "section", ")", "{", "req", ".", "url", "+=", "encodeURIComponent", "(", "section", ")", "+", "\"/\"", ";", "if", "(", "option", ")", "{", "req", ".", "url", "+=", "encodeURIComponent", "(", "option", ")", ";", "}", "}", "if", "(", "value", "===", "null", ")", "{", "req", ".", "type", "=", "\"DELETE\"", ";", "}", "else", "if", "(", "value", "!==", "undefined", ")", "{", "req", ".", "type", "=", "\"PUT\"", ";", "req", ".", "data", "=", "toJSON", "(", "value", ")", ";", "req", ".", "contentType", "=", "\"application/json\"", ";", "req", ".", "processData", "=", "false", "}", "ajax", "(", "req", ",", "options", ",", "\"An error occurred retrieving/updating the server configuration\"", ")", ";", "}" ]
View and edit the CouchDB configuration, called with just the options parameter the entire config is returned, you can be more specific by passing the section and option parameters, if you specify a value that value will be stored in the configuration. @see <a href="http://techzone.couchbase.com/sites/default/files/uploads/ all/documentation/couchbase-api-config.html#couchbase-api-config_config -section-key_put">docs for /_config</a> @param {ajaxSettings} options <a href="http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings"> jQuery ajax settings</a> @param {String} [section] the section of the config @param {String} [option] the particular config option @param {String} [value] value to be set
[ "View", "and", "edit", "the", "CouchDB", "configuration", "called", "with", "just", "the", "options", "parameter", "the", "entire", "config", "is", "returned", "you", "can", "be", "more", "specific", "by", "passing", "the", "section", "and", "option", "parameters", "if", "you", "specify", "a", "value", "that", "value", "will", "be", "stored", "in", "the", "configuration", "." ]
e6461409302486c5db1085bb44a81f310403eb90
https://github.com/sourcejs/Source/blob/e6461409302486c5db1085bb44a81f310403eb90/assets/js/lib/jquery.couch.js#L112-L132
21,308
sourcejs/Source
assets/js/lib/jquery.couch.js
function(options) { $.extend(options, {successStatus: 202}); ajax({ type: "POST", url: this.uri + "_compact", data: "", processData: false }, options, "The database could not be compacted" ); }
javascript
function(options) { $.extend(options, {successStatus: 202}); ajax({ type: "POST", url: this.uri + "_compact", data: "", processData: false }, options, "The database could not be compacted" ); }
[ "function", "(", "options", ")", "{", "$", ".", "extend", "(", "options", ",", "{", "successStatus", ":", "202", "}", ")", ";", "ajax", "(", "{", "type", ":", "\"POST\"", ",", "url", ":", "this", ".", "uri", "+", "\"_compact\"", ",", "data", ":", "\"\"", ",", "processData", ":", "false", "}", ",", "options", ",", "\"The database could not be compacted\"", ")", ";", "}" ]
Request compaction of the specified database. @see <a href="http://techzone.couchbase.com/sites/default/files/ uploads/all/documentation/couchbase-api-db.html#couchbase-api-db_ db-compact_post">docs for /db/_compact</a> @param {ajaxSettings} options <a href="http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings"> jQuery ajax settings</a>
[ "Request", "compaction", "of", "the", "specified", "database", "." ]
e6461409302486c5db1085bb44a81f310403eb90
https://github.com/sourcejs/Source/blob/e6461409302486c5db1085bb44a81f310403eb90/assets/js/lib/jquery.couch.js#L295-L304
21,309
sourcejs/Source
assets/js/lib/jquery.couch.js
getChangesSince
function getChangesSince() { var opts = $.extend({heartbeat : 10 * 1000}, options, { feed : "longpoll", since : since }); ajax( {url: db.uri + "_changes"+encodeOptions(opts)}, options, "Error connecting to "+db.uri+"/_changes." ); }
javascript
function getChangesSince() { var opts = $.extend({heartbeat : 10 * 1000}, options, { feed : "longpoll", since : since }); ajax( {url: db.uri + "_changes"+encodeOptions(opts)}, options, "Error connecting to "+db.uri+"/_changes." ); }
[ "function", "getChangesSince", "(", ")", "{", "var", "opts", "=", "$", ".", "extend", "(", "{", "heartbeat", ":", "10", "*", "1000", "}", ",", "options", ",", "{", "feed", ":", "\"longpoll\"", ",", "since", ":", "since", "}", ")", ";", "ajax", "(", "{", "url", ":", "db", ".", "uri", "+", "\"_changes\"", "+", "encodeOptions", "(", "opts", ")", "}", ",", "options", ",", "\"Error connecting to \"", "+", "db", ".", "uri", "+", "\"/_changes.\"", ")", ";", "}" ]
actually make the changes request
[ "actually", "make", "the", "changes", "request" ]
e6461409302486c5db1085bb44a81f310403eb90
https://github.com/sourcejs/Source/blob/e6461409302486c5db1085bb44a81f310403eb90/assets/js/lib/jquery.couch.js#L459-L469
21,310
sourcejs/Source
assets/js/lib/jquery.couch.js
function(docId, options, ajaxOptions) { options = options || {}; if (db_opts.attachPrevRev || options.attachPrevRev) { $.extend(options, { beforeSuccess : function(req, doc) { rawDocs[doc._id] = { rev : doc._rev, raw : req.responseText }; } }); } else { $.extend(options, { beforeSuccess : function(req, doc) { if (doc["jquery.couch.attachPrevRev"]) { rawDocs[doc._id] = { rev : doc._rev, raw : req.responseText }; } } }); } ajax({url: this.uri + encodeDocId(docId) + encodeOptions(options)}, options, "The document could not be retrieved", ajaxOptions ); }
javascript
function(docId, options, ajaxOptions) { options = options || {}; if (db_opts.attachPrevRev || options.attachPrevRev) { $.extend(options, { beforeSuccess : function(req, doc) { rawDocs[doc._id] = { rev : doc._rev, raw : req.responseText }; } }); } else { $.extend(options, { beforeSuccess : function(req, doc) { if (doc["jquery.couch.attachPrevRev"]) { rawDocs[doc._id] = { rev : doc._rev, raw : req.responseText }; } } }); } ajax({url: this.uri + encodeDocId(docId) + encodeOptions(options)}, options, "The document could not be retrieved", ajaxOptions ); }
[ "function", "(", "docId", ",", "options", ",", "ajaxOptions", ")", "{", "options", "=", "options", "||", "{", "}", ";", "if", "(", "db_opts", ".", "attachPrevRev", "||", "options", ".", "attachPrevRev", ")", "{", "$", ".", "extend", "(", "options", ",", "{", "beforeSuccess", ":", "function", "(", "req", ",", "doc", ")", "{", "rawDocs", "[", "doc", ".", "_id", "]", "=", "{", "rev", ":", "doc", ".", "_rev", ",", "raw", ":", "req", ".", "responseText", "}", ";", "}", "}", ")", ";", "}", "else", "{", "$", ".", "extend", "(", "options", ",", "{", "beforeSuccess", ":", "function", "(", "req", ",", "doc", ")", "{", "if", "(", "doc", "[", "\"jquery.couch.attachPrevRev\"", "]", ")", "{", "rawDocs", "[", "doc", ".", "_id", "]", "=", "{", "rev", ":", "doc", ".", "_rev", ",", "raw", ":", "req", ".", "responseText", "}", ";", "}", "}", "}", ")", ";", "}", "ajax", "(", "{", "url", ":", "this", ".", "uri", "+", "encodeDocId", "(", "docId", ")", "+", "encodeOptions", "(", "options", ")", "}", ",", "options", ",", "\"The document could not be retrieved\"", ",", "ajaxOptions", ")", ";", "}" ]
Returns the specified doc from the specified db. @see <a href="http://techzone.couchbase.com/sites/default/files/ uploads/all/documentation/couchbase-api-dbdoc.html#couchbase-api- dbdoc_db-doc_get">docs for GET /db/doc</a> @param {String} docId id of document to fetch @param {ajaxSettings} options <a href="http://api.jquery.com/ jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a> @param {ajaxSettings} ajaxOptions <a href="http://api.jquery.com/ jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
[ "Returns", "the", "specified", "doc", "from", "the", "specified", "db", "." ]
e6461409302486c5db1085bb44a81f310403eb90
https://github.com/sourcejs/Source/blob/e6461409302486c5db1085bb44a81f310403eb90/assets/js/lib/jquery.couch.js#L572-L600
21,311
sourcejs/Source
assets/js/lib/jquery.couch.js
function(doc, options) { options = options || {}; var db = this; var beforeSend = fullCommit(options); if (doc._id === undefined) { var method = "POST"; var uri = this.uri; } else { var method = "PUT"; var uri = this.uri + encodeDocId(doc._id); } var versioned = maybeApplyVersion(doc); $.ajax({ type: method, url: uri + encodeOptions(options), contentType: "application/json", dataType: "json", data: toJSON(doc), beforeSend : beforeSend, complete: function(req) { var resp = $.parseJSON(req.responseText); if (req.status == 200 || req.status == 201 || req.status == 202) { doc._id = resp.id; doc._rev = resp.rev; if (versioned) { db.openDoc(doc._id, { attachPrevRev : true, success : function(d) { doc._attachments = d._attachments; if (options.success) options.success(resp); } }); } else { if (options.success) options.success(resp); } } else if (options.error) { options.error(req.status, resp.error, resp.reason); } else { throw "The document could not be saved: " + resp.reason; } } }); }
javascript
function(doc, options) { options = options || {}; var db = this; var beforeSend = fullCommit(options); if (doc._id === undefined) { var method = "POST"; var uri = this.uri; } else { var method = "PUT"; var uri = this.uri + encodeDocId(doc._id); } var versioned = maybeApplyVersion(doc); $.ajax({ type: method, url: uri + encodeOptions(options), contentType: "application/json", dataType: "json", data: toJSON(doc), beforeSend : beforeSend, complete: function(req) { var resp = $.parseJSON(req.responseText); if (req.status == 200 || req.status == 201 || req.status == 202) { doc._id = resp.id; doc._rev = resp.rev; if (versioned) { db.openDoc(doc._id, { attachPrevRev : true, success : function(d) { doc._attachments = d._attachments; if (options.success) options.success(resp); } }); } else { if (options.success) options.success(resp); } } else if (options.error) { options.error(req.status, resp.error, resp.reason); } else { throw "The document could not be saved: " + resp.reason; } } }); }
[ "function", "(", "doc", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "db", "=", "this", ";", "var", "beforeSend", "=", "fullCommit", "(", "options", ")", ";", "if", "(", "doc", ".", "_id", "===", "undefined", ")", "{", "var", "method", "=", "\"POST\"", ";", "var", "uri", "=", "this", ".", "uri", ";", "}", "else", "{", "var", "method", "=", "\"PUT\"", ";", "var", "uri", "=", "this", ".", "uri", "+", "encodeDocId", "(", "doc", ".", "_id", ")", ";", "}", "var", "versioned", "=", "maybeApplyVersion", "(", "doc", ")", ";", "$", ".", "ajax", "(", "{", "type", ":", "method", ",", "url", ":", "uri", "+", "encodeOptions", "(", "options", ")", ",", "contentType", ":", "\"application/json\"", ",", "dataType", ":", "\"json\"", ",", "data", ":", "toJSON", "(", "doc", ")", ",", "beforeSend", ":", "beforeSend", ",", "complete", ":", "function", "(", "req", ")", "{", "var", "resp", "=", "$", ".", "parseJSON", "(", "req", ".", "responseText", ")", ";", "if", "(", "req", ".", "status", "==", "200", "||", "req", ".", "status", "==", "201", "||", "req", ".", "status", "==", "202", ")", "{", "doc", ".", "_id", "=", "resp", ".", "id", ";", "doc", ".", "_rev", "=", "resp", ".", "rev", ";", "if", "(", "versioned", ")", "{", "db", ".", "openDoc", "(", "doc", ".", "_id", ",", "{", "attachPrevRev", ":", "true", ",", "success", ":", "function", "(", "d", ")", "{", "doc", ".", "_attachments", "=", "d", ".", "_attachments", ";", "if", "(", "options", ".", "success", ")", "options", ".", "success", "(", "resp", ")", ";", "}", "}", ")", ";", "}", "else", "{", "if", "(", "options", ".", "success", ")", "options", ".", "success", "(", "resp", ")", ";", "}", "}", "else", "if", "(", "options", ".", "error", ")", "{", "options", ".", "error", "(", "req", ".", "status", ",", "resp", ".", "error", ",", "resp", ".", "reason", ")", ";", "}", "else", "{", "throw", "\"The document could not be saved: \"", "+", "resp", ".", "reason", ";", "}", "}", "}", ")", ";", "}" ]
Create a new document in the specified database, using the supplied JSON document structure. If the JSON structure includes the _id field, then the document will be created with the specified document ID. If the _id field is not specified, a new unique ID will be generated. @see <a href="http://techzone.couchbase.com/sites/default/files/ uploads/all/documentation/couchbase-api-dbdoc.html#couchbase-api- dbdoc_db_post">docs for GET /db/doc</a> @param {String} doc document to save @param {ajaxSettings} options <a href="http://api.jquery.com/ jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
[ "Create", "a", "new", "document", "in", "the", "specified", "database", "using", "the", "supplied", "JSON", "document", "structure", ".", "If", "the", "JSON", "structure", "includes", "the", "_id", "field", "then", "the", "document", "will", "be", "created", "with", "the", "specified", "document", "ID", ".", "If", "the", "_id", "field", "is", "not", "specified", "a", "new", "unique", "ID", "will", "be", "generated", "." ]
e6461409302486c5db1085bb44a81f310403eb90
https://github.com/sourcejs/Source/blob/e6461409302486c5db1085bb44a81f310403eb90/assets/js/lib/jquery.couch.js#L615-L655
21,312
sourcejs/Source
assets/js/lib/jquery.couch.js
function(docs, options) { var beforeSend = fullCommit(options); $.extend(options, {successStatus: 201, beforeSend : beforeSend}); ajax({ type: "POST", url: this.uri + "_bulk_docs" + encodeOptions(options), contentType: "application/json", data: toJSON(docs) }, options, "The documents could not be saved" ); }
javascript
function(docs, options) { var beforeSend = fullCommit(options); $.extend(options, {successStatus: 201, beforeSend : beforeSend}); ajax({ type: "POST", url: this.uri + "_bulk_docs" + encodeOptions(options), contentType: "application/json", data: toJSON(docs) }, options, "The documents could not be saved" ); }
[ "function", "(", "docs", ",", "options", ")", "{", "var", "beforeSend", "=", "fullCommit", "(", "options", ")", ";", "$", ".", "extend", "(", "options", ",", "{", "successStatus", ":", "201", ",", "beforeSend", ":", "beforeSend", "}", ")", ";", "ajax", "(", "{", "type", ":", "\"POST\"", ",", "url", ":", "this", ".", "uri", "+", "\"_bulk_docs\"", "+", "encodeOptions", "(", "options", ")", ",", "contentType", ":", "\"application/json\"", ",", "data", ":", "toJSON", "(", "docs", ")", "}", ",", "options", ",", "\"The documents could not be saved\"", ")", ";", "}" ]
Save a list of documents @see <a href="http://techzone.couchbase.com/sites/default/files/ uploads/all/documentation/couchbase-api-db.html#couchbase-api-db_ db-bulk-docs_post">docs for /db/_bulk_docs</a> @param {Object[]} docs List of documents to save @param {ajaxSettings} options <a href="http://api.jquery.com/ jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
[ "Save", "a", "list", "of", "documents" ]
e6461409302486c5db1085bb44a81f310403eb90
https://github.com/sourcejs/Source/blob/e6461409302486c5db1085bb44a81f310403eb90/assets/js/lib/jquery.couch.js#L666-L677
21,313
sourcejs/Source
assets/js/lib/jquery.couch.js
function(docs, options){ docs.docs = $.each( docs.docs, function(i, doc){ doc._deleted = true; } ); $.extend(options, {successStatus: 201}); ajax({ type: "POST", url: this.uri + "_bulk_docs" + encodeOptions(options), data: toJSON(docs) }, options, "The documents could not be deleted" ); }
javascript
function(docs, options){ docs.docs = $.each( docs.docs, function(i, doc){ doc._deleted = true; } ); $.extend(options, {successStatus: 201}); ajax({ type: "POST", url: this.uri + "_bulk_docs" + encodeOptions(options), data: toJSON(docs) }, options, "The documents could not be deleted" ); }
[ "function", "(", "docs", ",", "options", ")", "{", "docs", ".", "docs", "=", "$", ".", "each", "(", "docs", ".", "docs", ",", "function", "(", "i", ",", "doc", ")", "{", "doc", ".", "_deleted", "=", "true", ";", "}", ")", ";", "$", ".", "extend", "(", "options", ",", "{", "successStatus", ":", "201", "}", ")", ";", "ajax", "(", "{", "type", ":", "\"POST\"", ",", "url", ":", "this", ".", "uri", "+", "\"_bulk_docs\"", "+", "encodeOptions", "(", "options", ")", ",", "data", ":", "toJSON", "(", "docs", ")", "}", ",", "options", ",", "\"The documents could not be deleted\"", ")", ";", "}" ]
Remove a set of documents @see <a href="http://techzone.couchbase.com/sites/default/files/ uploads/all/documentation/couchbase-api-db.html#couchbase-api-db_ db-bulk-docs_post">docs for /db/_bulk_docs</a> @param {String[]} docs List of document id's to remove @param {ajaxSettings} options <a href="http://api.jquery.com/ jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
[ "Remove", "a", "set", "of", "documents" ]
e6461409302486c5db1085bb44a81f310403eb90
https://github.com/sourcejs/Source/blob/e6461409302486c5db1085bb44a81f310403eb90/assets/js/lib/jquery.couch.js#L711-L726
21,314
sourcejs/Source
assets/js/lib/jquery.couch.js
function(propName, options, ajaxOptions) { ajax({url: this.uri + propName + encodeOptions(options)}, options, "The property could not be retrieved", ajaxOptions ); }
javascript
function(propName, options, ajaxOptions) { ajax({url: this.uri + propName + encodeOptions(options)}, options, "The property could not be retrieved", ajaxOptions ); }
[ "function", "(", "propName", ",", "options", ",", "ajaxOptions", ")", "{", "ajax", "(", "{", "url", ":", "this", ".", "uri", "+", "propName", "+", "encodeOptions", "(", "options", ")", "}", ",", "options", ",", "\"The property could not be retrieved\"", ",", "ajaxOptions", ")", ";", "}" ]
Fetch an arbitrary CouchDB database property @see <a href="http://techzone.couchbase.com/sites/default/files/ uploads/all/documentation/couchbase-api.html">docs for /db/_prop</a> @param {String} propName Propery name to fetch @param {ajaxSettings} options <a href="http://api.jquery.com/ jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a> @param {ajaxSettings} ajaxOptions <a href="http://api.jquery.com/ jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
[ "Fetch", "an", "arbitrary", "CouchDB", "database", "property" ]
e6461409302486c5db1085bb44a81f310403eb90
https://github.com/sourcejs/Source/blob/e6461409302486c5db1085bb44a81f310403eb90/assets/js/lib/jquery.couch.js#L878-L884
21,315
sourcejs/Source
assets/js/lib/jquery.couch.js
function(propName, propValue, options, ajaxOptions) { ajax({ type: "PUT", url: this.uri + propName + encodeOptions(options), data : JSON.stringify(propValue) }, options, "The property could not be updated", ajaxOptions ); }
javascript
function(propName, propValue, options, ajaxOptions) { ajax({ type: "PUT", url: this.uri + propName + encodeOptions(options), data : JSON.stringify(propValue) }, options, "The property could not be updated", ajaxOptions ); }
[ "function", "(", "propName", ",", "propValue", ",", "options", ",", "ajaxOptions", ")", "{", "ajax", "(", "{", "type", ":", "\"PUT\"", ",", "url", ":", "this", ".", "uri", "+", "propName", "+", "encodeOptions", "(", "options", ")", ",", "data", ":", "JSON", ".", "stringify", "(", "propValue", ")", "}", ",", "options", ",", "\"The property could not be updated\"", ",", "ajaxOptions", ")", ";", "}" ]
Set an arbitrary CouchDB database property @see <a href="http://techzone.couchbase.com/sites/default/files/ uploads/all/documentation/couchbase-api.html">docs for /db/_prop</a> @param {String} propName Propery name to fetch @param {String} propValue Propery value to set @param {ajaxSettings} options <a href="http://api.jquery.com/ jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a> @param {ajaxSettings} ajaxOptions <a href="http://api.jquery.com/ jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
[ "Set", "an", "arbitrary", "CouchDB", "database", "property" ]
e6461409302486c5db1085bb44a81f310403eb90
https://github.com/sourcejs/Source/blob/e6461409302486c5db1085bb44a81f310403eb90/assets/js/lib/jquery.couch.js#L897-L907
21,316
sourcejs/Source
assets/js/lib/jquery.couch.js
function(source, target, ajaxOptions, repOpts) { repOpts = $.extend({source: source, target: target}, repOpts); if (repOpts.continuous && !repOpts.cancel) { ajaxOptions.successStatus = 202; } ajax({ type: "POST", url: this.urlPrefix + "/_replicate", data: JSON.stringify(repOpts), contentType: "application/json" }, ajaxOptions, "Replication failed" ); }
javascript
function(source, target, ajaxOptions, repOpts) { repOpts = $.extend({source: source, target: target}, repOpts); if (repOpts.continuous && !repOpts.cancel) { ajaxOptions.successStatus = 202; } ajax({ type: "POST", url: this.urlPrefix + "/_replicate", data: JSON.stringify(repOpts), contentType: "application/json" }, ajaxOptions, "Replication failed" ); }
[ "function", "(", "source", ",", "target", ",", "ajaxOptions", ",", "repOpts", ")", "{", "repOpts", "=", "$", ".", "extend", "(", "{", "source", ":", "source", ",", "target", ":", "target", "}", ",", "repOpts", ")", ";", "if", "(", "repOpts", ".", "continuous", "&&", "!", "repOpts", ".", "cancel", ")", "{", "ajaxOptions", ".", "successStatus", "=", "202", ";", "}", "ajax", "(", "{", "type", ":", "\"POST\"", ",", "url", ":", "this", ".", "urlPrefix", "+", "\"/_replicate\"", ",", "data", ":", "JSON", ".", "stringify", "(", "repOpts", ")", ",", "contentType", ":", "\"application/json\"", "}", ",", "ajaxOptions", ",", "\"Replication failed\"", ")", ";", "}" ]
Request, configure, or stop, a replication operation. @see <a href="http://techzone.couchbase.com/sites/default/files/ uploads/all/documentation/couchbase-api-misc.html#couchbase-api- misc_replicate_post">docs for POST /_replicate</a> @param {String} source Path or url to source database @param {String} target Path or url to target database @param {ajaxSettings} ajaxOptions <a href="http://api.jquery.com/ jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a> @param {Object} repOpts Additional replication options
[ "Request", "configure", "or", "stop", "a", "replication", "operation", "." ]
e6461409302486c5db1085bb44a81f310403eb90
https://github.com/sourcejs/Source/blob/e6461409302486c5db1085bb44a81f310403eb90/assets/js/lib/jquery.couch.js#L943-L956
21,317
sourcejs/Source
assets/js/lib/jquery.couch.js
function(cacheNum) { if (cacheNum === undefined) { cacheNum = 1; } if (!uuidCache.length) { ajax({url: this.urlPrefix + "/_uuids", data: {count: cacheNum}, async: false}, { success: function(resp) { uuidCache = resp.uuids; } }, "Failed to retrieve UUID batch." ); } return uuidCache.shift(); }
javascript
function(cacheNum) { if (cacheNum === undefined) { cacheNum = 1; } if (!uuidCache.length) { ajax({url: this.urlPrefix + "/_uuids", data: {count: cacheNum}, async: false}, { success: function(resp) { uuidCache = resp.uuids; } }, "Failed to retrieve UUID batch." ); } return uuidCache.shift(); }
[ "function", "(", "cacheNum", ")", "{", "if", "(", "cacheNum", "===", "undefined", ")", "{", "cacheNum", "=", "1", ";", "}", "if", "(", "!", "uuidCache", ".", "length", ")", "{", "ajax", "(", "{", "url", ":", "this", ".", "urlPrefix", "+", "\"/_uuids\"", ",", "data", ":", "{", "count", ":", "cacheNum", "}", ",", "async", ":", "false", "}", ",", "{", "success", ":", "function", "(", "resp", ")", "{", "uuidCache", "=", "resp", ".", "uuids", ";", "}", "}", ",", "\"Failed to retrieve UUID batch.\"", ")", ";", "}", "return", "uuidCache", ".", "shift", "(", ")", ";", "}" ]
Fetch a new UUID @see <a href="http://techzone.couchbase.com/sites/default/files/ uploads/all/documentation/couchbase-api-misc.html#couchbase-api- misc_uuids_get">docs for /_uuids</a> @param {Int} cacheNum Number of uuids to keep cached for future use
[ "Fetch", "a", "new", "UUID" ]
e6461409302486c5db1085bb44a81f310403eb90
https://github.com/sourcejs/Source/blob/e6461409302486c5db1085bb44a81f310403eb90/assets/js/lib/jquery.couch.js#L965-L980
21,318
TobiasHennig/nativescript-toast
publish/scripts/postinstall.js
askAndroidPrompt
function askAndroidPrompt() { prompt.get({ name: 'using_android', description: 'Are you using Android (y/n)', default: 'y' }, function(err, result) { if (err) { return console.log(err); } mergeConfig(result); askAndroidPromptResult(result); if (usingiOS || usingAndroid) { promptQuestions(); } else { askSaveConfigPrompt(); } }); }
javascript
function askAndroidPrompt() { prompt.get({ name: 'using_android', description: 'Are you using Android (y/n)', default: 'y' }, function(err, result) { if (err) { return console.log(err); } mergeConfig(result); askAndroidPromptResult(result); if (usingiOS || usingAndroid) { promptQuestions(); } else { askSaveConfigPrompt(); } }); }
[ "function", "askAndroidPrompt", "(", ")", "{", "prompt", ".", "get", "(", "{", "name", ":", "'using_android'", ",", "description", ":", "'Are you using Android (y/n)'", ",", "default", ":", "'y'", "}", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "return", "console", ".", "log", "(", "err", ")", ";", "}", "mergeConfig", "(", "result", ")", ";", "askAndroidPromptResult", "(", "result", ")", ";", "if", "(", "usingiOS", "||", "usingAndroid", ")", "{", "promptQuestions", "(", ")", ";", "}", "else", "{", "askSaveConfigPrompt", "(", ")", ";", "}", "}", ")", ";", "}" ]
Prompt the user if they are integrating Fabric with Android
[ "Prompt", "the", "user", "if", "they", "are", "integrating", "Fabric", "with", "Android" ]
5de877615a94125bb677fa8a68646146285828dd
https://github.com/TobiasHennig/nativescript-toast/blob/5de877615a94125bb677fa8a68646146285828dd/publish/scripts/postinstall.js#L128-L145
21,319
TobiasHennig/nativescript-toast
publish/scripts/postinstall.js
promptQuestions
function promptQuestions() { prompt.get([{ name: 'api_key', description: 'Your Fabric API Key', default: '' }, { name: 'api_secret', description: 'Your Fabric API Secret', default: '' }], function(err, result) { if (err) { return console.log(err); } mergeConfig(result); promptQuestionsResult(result); askSaveConfigPrompt(); }); }
javascript
function promptQuestions() { prompt.get([{ name: 'api_key', description: 'Your Fabric API Key', default: '' }, { name: 'api_secret', description: 'Your Fabric API Secret', default: '' }], function(err, result) { if (err) { return console.log(err); } mergeConfig(result); promptQuestionsResult(result); askSaveConfigPrompt(); }); }
[ "function", "promptQuestions", "(", ")", "{", "prompt", ".", "get", "(", "[", "{", "name", ":", "'api_key'", ",", "description", ":", "'Your Fabric API Key'", ",", "default", ":", "''", "}", ",", "{", "name", ":", "'api_secret'", ",", "description", ":", "'Your Fabric API Secret'", ",", "default", ":", "''", "}", "]", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "return", "console", ".", "log", "(", "err", ")", ";", "}", "mergeConfig", "(", "result", ")", ";", "promptQuestionsResult", "(", "result", ")", ";", "askSaveConfigPrompt", "(", ")", ";", "}", ")", ";", "}" ]
Prompt the user through the configurable Fabric add-on services
[ "Prompt", "the", "user", "through", "the", "configurable", "Fabric", "add", "-", "on", "services" ]
5de877615a94125bb677fa8a68646146285828dd
https://github.com/TobiasHennig/nativescript-toast/blob/5de877615a94125bb677fa8a68646146285828dd/publish/scripts/postinstall.js#L156-L173
21,320
TobiasHennig/nativescript-toast
publish/scripts/postinstall.js
writePodFile
function writePodFile(result) { if (!fs.existsSync(directories.ios)) { fs.mkdirSync(directories.ios); } try { fs.writeFileSync(directories.ios + '/Podfile', `use_frameworks! pod 'Fabric', '${FABRIC_IOS_FABRIC}' pod 'Crashlytics', '${FABRIC_IOS_CRASHLYTICS}' # Crashlytics works best without bitcode post_install do |installer| installer.pods_project.targets.each do |target| target.build_configurations.each do |config| config.build_settings['ENABLE_BITCODE'] = "NO" end end end `); console.log('Successfully created iOS (Pod) file.'); } catch (e) { console.log('Failed to create iOS (Pod) file.'); console.log(e); throw e; } }
javascript
function writePodFile(result) { if (!fs.existsSync(directories.ios)) { fs.mkdirSync(directories.ios); } try { fs.writeFileSync(directories.ios + '/Podfile', `use_frameworks! pod 'Fabric', '${FABRIC_IOS_FABRIC}' pod 'Crashlytics', '${FABRIC_IOS_CRASHLYTICS}' # Crashlytics works best without bitcode post_install do |installer| installer.pods_project.targets.each do |target| target.build_configurations.each do |config| config.build_settings['ENABLE_BITCODE'] = "NO" end end end `); console.log('Successfully created iOS (Pod) file.'); } catch (e) { console.log('Failed to create iOS (Pod) file.'); console.log(e); throw e; } }
[ "function", "writePodFile", "(", "result", ")", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "directories", ".", "ios", ")", ")", "{", "fs", ".", "mkdirSync", "(", "directories", ".", "ios", ")", ";", "}", "try", "{", "fs", ".", "writeFileSync", "(", "directories", ".", "ios", "+", "'/Podfile'", ",", "`", "${", "FABRIC_IOS_FABRIC", "}", "${", "FABRIC_IOS_CRASHLYTICS", "}", "`", ")", ";", "console", ".", "log", "(", "'Successfully created iOS (Pod) file.'", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "'Failed to create iOS (Pod) file.'", ")", ";", "console", ".", "log", "(", "e", ")", ";", "throw", "e", ";", "}", "}" ]
Create the iOS PodFile for installing the Fabric iOS dependencies and service dependencies @param {any} result The answers to the micro-service prompts
[ "Create", "the", "iOS", "PodFile", "for", "installing", "the", "Fabric", "iOS", "dependencies", "and", "service", "dependencies" ]
5de877615a94125bb677fa8a68646146285828dd
https://github.com/TobiasHennig/nativescript-toast/blob/5de877615a94125bb677fa8a68646146285828dd/publish/scripts/postinstall.js#L291-L315
21,321
TobiasHennig/nativescript-toast
publish/scripts/postinstall.js
writeGradleFile
function writeGradleFile() { if (!fs.existsSync(directories.android)) { fs.mkdirSync(directories.android); } try { fs.writeFileSync(directories.android + '/include.gradle', ` android { } buildscript { repositories { maven { url 'https://maven.fabric.io/public' } } } repositories { mavenCentral() maven { url 'https://maven.fabric.io/public' } } dependencies { compile('com.crashlytics.sdk.android:crashlytics:${FABRIC_ANDROID_CRASHLYTICS}@aar') { transitive = true; } compile('com.crashlytics.sdk.android:answers:${FABRIC_ANDROID_ANSWERS}@aar') { transitive = true; } } `); console.log('Successfully created Android (include.gradle) file.'); } catch (e) { console.log('Failed to create Android (include.gradle) file.'); console.log(e); throw e; } }
javascript
function writeGradleFile() { if (!fs.existsSync(directories.android)) { fs.mkdirSync(directories.android); } try { fs.writeFileSync(directories.android + '/include.gradle', ` android { } buildscript { repositories { maven { url 'https://maven.fabric.io/public' } } } repositories { mavenCentral() maven { url 'https://maven.fabric.io/public' } } dependencies { compile('com.crashlytics.sdk.android:crashlytics:${FABRIC_ANDROID_CRASHLYTICS}@aar') { transitive = true; } compile('com.crashlytics.sdk.android:answers:${FABRIC_ANDROID_ANSWERS}@aar') { transitive = true; } } `); console.log('Successfully created Android (include.gradle) file.'); } catch (e) { console.log('Failed to create Android (include.gradle) file.'); console.log(e); throw e; } }
[ "function", "writeGradleFile", "(", ")", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "directories", ".", "android", ")", ")", "{", "fs", ".", "mkdirSync", "(", "directories", ".", "android", ")", ";", "}", "try", "{", "fs", ".", "writeFileSync", "(", "directories", ".", "android", "+", "'/include.gradle'", ",", "`", "${", "FABRIC_ANDROID_CRASHLYTICS", "}", "${", "FABRIC_ANDROID_ANSWERS", "}", "`", ")", ";", "console", ".", "log", "(", "'Successfully created Android (include.gradle) file.'", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "'Failed to create Android (include.gradle) file.'", ")", ";", "console", ".", "log", "(", "e", ")", ";", "throw", "e", ";", "}", "}" ]
Create the Android Gradle for installing the Fabric Android dependencies and service dependencies @param {any} result The answers to the micro-service prompts
[ "Create", "the", "Android", "Gradle", "for", "installing", "the", "Fabric", "Android", "dependencies", "and", "service", "dependencies" ]
5de877615a94125bb677fa8a68646146285828dd
https://github.com/TobiasHennig/nativescript-toast/blob/5de877615a94125bb677fa8a68646146285828dd/publish/scripts/postinstall.js#L322-L360
21,322
TobiasHennig/nativescript-toast
publish/scripts/postinstall.js
writeFabricServiceGradleHook
function writeFabricServiceGradleHook(config) { console.log("Install Fabric-build-gradle hook."); try { if (!fs.existsSync(path.join(appRoot, "hooks"))) { fs.mkdirSync(path.join(appRoot, "hooks")); } if (!fs.existsSync(path.join(appRoot, "hooks", "after-prepare"))) { fs.mkdirSync(path.join(appRoot, "hooks", "after-prepare")); } var scriptContent = ` var path = require("path"); var fs = require("fs"); module.exports = function($logger, $projectData, hookArgs) { var platform = hookArgs.platform.toLowerCase(); function updateAppGradleScript(file) { var appBuildGradleContent = fs.readFileSync(file).toString(); if (!appBuildGradleContent.match(/.*fabric.*/)) { $logger.trace("Configuring Fabric for Android"); var search = -1; search = appBuildGradleContent.indexOf("repositories {", 0); if (search == -1) { return; } appBuildGradleContent = appBuildGradleContent.substr(0, search + 14) + ' maven { url "https://maven.fabric.io/public" }\\n' + appBuildGradleContent.substr(search + 14); // TODO add to buildTypes entry // appBuildGradleContent = appBuildGradleContent + '\\ndebug { \\n ext.enableCrashlytics = false\\n}\\n'; search = appBuildGradleContent.indexOf("apply plugin: \\"com.android.application\\""); if (search == -1) { return; } appBuildGradleContent = appBuildGradleContent.substr(0, search + 39) + '\\napply plugin: "io.fabric"\\n' + appBuildGradleContent.substr(search + 39); fs.writeFileSync(file, appBuildGradleContent); $logger.trace('Written build.gradle'); } if (appBuildGradleContent.indexOf("buildMetadata.finalizedBy(copyMetadata)") === -1) { appBuildGradleContent = appBuildGradleContent.replace("ensureMetadataOutDir.finalizedBy(buildMetadata)", "ensureMetadataOutDir.finalizedBy(buildMetadata)\\n\\t\\tbuildMetadata.finalizedBy(copyMetadata)"); appBuildGradleContent += \` task copyMetadata { doLast { copy { from "$projectDir/src/main/assets/metadata" def toDir = project.hasProperty("release") ? "release" : "debug"; if (new File("$projectDir/build/intermediates/assets").listFiles() != null) { toDir = new File("$projectDir/build/intermediates/assets").listFiles()[0].name if (toDir != 'debug' && toDir != 'release') { toDir += "/release" } } into "$projectDir/build/intermediates/assets/" + toDir + "/metadata" } } } \`; fs.writeFileSync(file, appBuildGradleContent); $logger.trace('Written build.gradle'); } } function updateGradleScript(file) { var buildGradleContent = fs.readFileSync(file).toString(); if (!buildGradleContent.match(/.*fabric.*/)) { $logger.trace("Configuring Fabric for Android"); var search = -1; search = buildGradleContent.indexOf("repositories", 0); if (search == -1) { return; } search = buildGradleContent.indexOf("}", search); buildGradleContent = buildGradleContent.substr(0, search - 1) + ' maven { url "https://maven.fabric.io/public" }\\n' + buildGradleContent.substr(search - 1); search = buildGradleContent.indexOf("dependencies", search); if (search == -1) { return; } search = buildGradleContent.indexOf("}", search); if (search == -1) { return; } buildGradleContent = buildGradleContent.substr(0, search - 1) + ' classpath "io.fabric.tools:gradle:${FABRIC_GRADLE_TOOLS}"\\n' + buildGradleContent.substr(search - 1); fs.writeFileSync(file, buildGradleContent); $logger.trace('Written build.gradle'); } } if (platform === 'android') { var apiKey = "${config.api_key}"; var apiSecret = "${config.api_secret}"; var androidPlatformDir = path.join(__dirname, "..", "..", 'platforms', 'android'); var androidAppPlatformDir = path.join(__dirname, "..", "..", 'platforms', 'android', 'app'); var gradleScript = path.join(androidPlatformDir, 'build.gradle'); var gradleAppScript = path.join(androidAppPlatformDir, 'build.gradle'); if (fs.existsSync(gradleAppScript)) { updateAppGradleScript(gradleAppScript); updateGradleScript(gradleScript); } else { updateGradleScript(gradleScript); } var settingsJson = path.join(__dirname, "..", "..", "platforms", "android", "app", "src", "main", "res", "fabric.properties"); var propertiesContent = '# Contains API Secret used to validate your application. Commit to internal source control; avoid making secret public\\n'; propertiesContent+='apiKey = ' + apiKey + '\\n'; propertiesContent+='apiSecret = ' + apiSecret + '\\n'; fs.writeFileSync(settingsJson, propertiesContent); $logger.trace('Written fabric.properties'); } }; `; console.log("Writing 'nativescript-fabric-gradle.js' to " + appRoot + "hooks/after-prepare"); var scriptPath = path.join(appRoot, "hooks", "after-prepare", "nativescript-fabric-gradle.js"); fs.writeFileSync(scriptPath, scriptContent); } catch (e) { console.log("Failed to install nativescript-fabric-gradle hook."); console.log(e); throw e; } }
javascript
function writeFabricServiceGradleHook(config) { console.log("Install Fabric-build-gradle hook."); try { if (!fs.existsSync(path.join(appRoot, "hooks"))) { fs.mkdirSync(path.join(appRoot, "hooks")); } if (!fs.existsSync(path.join(appRoot, "hooks", "after-prepare"))) { fs.mkdirSync(path.join(appRoot, "hooks", "after-prepare")); } var scriptContent = ` var path = require("path"); var fs = require("fs"); module.exports = function($logger, $projectData, hookArgs) { var platform = hookArgs.platform.toLowerCase(); function updateAppGradleScript(file) { var appBuildGradleContent = fs.readFileSync(file).toString(); if (!appBuildGradleContent.match(/.*fabric.*/)) { $logger.trace("Configuring Fabric for Android"); var search = -1; search = appBuildGradleContent.indexOf("repositories {", 0); if (search == -1) { return; } appBuildGradleContent = appBuildGradleContent.substr(0, search + 14) + ' maven { url "https://maven.fabric.io/public" }\\n' + appBuildGradleContent.substr(search + 14); // TODO add to buildTypes entry // appBuildGradleContent = appBuildGradleContent + '\\ndebug { \\n ext.enableCrashlytics = false\\n}\\n'; search = appBuildGradleContent.indexOf("apply plugin: \\"com.android.application\\""); if (search == -1) { return; } appBuildGradleContent = appBuildGradleContent.substr(0, search + 39) + '\\napply plugin: "io.fabric"\\n' + appBuildGradleContent.substr(search + 39); fs.writeFileSync(file, appBuildGradleContent); $logger.trace('Written build.gradle'); } if (appBuildGradleContent.indexOf("buildMetadata.finalizedBy(copyMetadata)") === -1) { appBuildGradleContent = appBuildGradleContent.replace("ensureMetadataOutDir.finalizedBy(buildMetadata)", "ensureMetadataOutDir.finalizedBy(buildMetadata)\\n\\t\\tbuildMetadata.finalizedBy(copyMetadata)"); appBuildGradleContent += \` task copyMetadata { doLast { copy { from "$projectDir/src/main/assets/metadata" def toDir = project.hasProperty("release") ? "release" : "debug"; if (new File("$projectDir/build/intermediates/assets").listFiles() != null) { toDir = new File("$projectDir/build/intermediates/assets").listFiles()[0].name if (toDir != 'debug' && toDir != 'release') { toDir += "/release" } } into "$projectDir/build/intermediates/assets/" + toDir + "/metadata" } } } \`; fs.writeFileSync(file, appBuildGradleContent); $logger.trace('Written build.gradle'); } } function updateGradleScript(file) { var buildGradleContent = fs.readFileSync(file).toString(); if (!buildGradleContent.match(/.*fabric.*/)) { $logger.trace("Configuring Fabric for Android"); var search = -1; search = buildGradleContent.indexOf("repositories", 0); if (search == -1) { return; } search = buildGradleContent.indexOf("}", search); buildGradleContent = buildGradleContent.substr(0, search - 1) + ' maven { url "https://maven.fabric.io/public" }\\n' + buildGradleContent.substr(search - 1); search = buildGradleContent.indexOf("dependencies", search); if (search == -1) { return; } search = buildGradleContent.indexOf("}", search); if (search == -1) { return; } buildGradleContent = buildGradleContent.substr(0, search - 1) + ' classpath "io.fabric.tools:gradle:${FABRIC_GRADLE_TOOLS}"\\n' + buildGradleContent.substr(search - 1); fs.writeFileSync(file, buildGradleContent); $logger.trace('Written build.gradle'); } } if (platform === 'android') { var apiKey = "${config.api_key}"; var apiSecret = "${config.api_secret}"; var androidPlatformDir = path.join(__dirname, "..", "..", 'platforms', 'android'); var androidAppPlatformDir = path.join(__dirname, "..", "..", 'platforms', 'android', 'app'); var gradleScript = path.join(androidPlatformDir, 'build.gradle'); var gradleAppScript = path.join(androidAppPlatformDir, 'build.gradle'); if (fs.existsSync(gradleAppScript)) { updateAppGradleScript(gradleAppScript); updateGradleScript(gradleScript); } else { updateGradleScript(gradleScript); } var settingsJson = path.join(__dirname, "..", "..", "platforms", "android", "app", "src", "main", "res", "fabric.properties"); var propertiesContent = '# Contains API Secret used to validate your application. Commit to internal source control; avoid making secret public\\n'; propertiesContent+='apiKey = ' + apiKey + '\\n'; propertiesContent+='apiSecret = ' + apiSecret + '\\n'; fs.writeFileSync(settingsJson, propertiesContent); $logger.trace('Written fabric.properties'); } }; `; console.log("Writing 'nativescript-fabric-gradle.js' to " + appRoot + "hooks/after-prepare"); var scriptPath = path.join(appRoot, "hooks", "after-prepare", "nativescript-fabric-gradle.js"); fs.writeFileSync(scriptPath, scriptContent); } catch (e) { console.log("Failed to install nativescript-fabric-gradle hook."); console.log(e); throw e; } }
[ "function", "writeFabricServiceGradleHook", "(", "config", ")", "{", "console", ".", "log", "(", "\"Install Fabric-build-gradle hook.\"", ")", ";", "try", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "path", ".", "join", "(", "appRoot", ",", "\"hooks\"", ")", ")", ")", "{", "fs", ".", "mkdirSync", "(", "path", ".", "join", "(", "appRoot", ",", "\"hooks\"", ")", ")", ";", "}", "if", "(", "!", "fs", ".", "existsSync", "(", "path", ".", "join", "(", "appRoot", ",", "\"hooks\"", ",", "\"after-prepare\"", ")", ")", ")", "{", "fs", ".", "mkdirSync", "(", "path", ".", "join", "(", "appRoot", ",", "\"hooks\"", ",", "\"after-prepare\"", ")", ")", ";", "}", "var", "scriptContent", "=", "`", "\\\\", "\\\\", "\\\\", "\\\\", "\\\\", "\\\\", "\\\\", "\\\\", "\\\\", "\\\\", "\\\\", "\\\\", "\\`", "\\`", "\\\\", "${", "FABRIC_GRADLE_TOOLS", "}", "\\\\", "${", "config", ".", "api_key", "}", "${", "config", ".", "api_secret", "}", "\\\\", "\\\\", "\\\\", "`", ";", "console", ".", "log", "(", "\"Writing 'nativescript-fabric-gradle.js' to \"", "+", "appRoot", "+", "\"hooks/after-prepare\"", ")", ";", "var", "scriptPath", "=", "path", ".", "join", "(", "appRoot", ",", "\"hooks\"", ",", "\"after-prepare\"", ",", "\"nativescript-fabric-gradle.js\"", ")", ";", "fs", ".", "writeFileSync", "(", "scriptPath", ",", "scriptContent", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "\"Failed to install nativescript-fabric-gradle hook.\"", ")", ";", "console", ".", "log", "(", "e", ")", ";", "throw", "e", ";", "}", "}" ]
Create dev tools gradle runtime entry
[ "Create", "dev", "tools", "gradle", "runtime", "entry" ]
5de877615a94125bb677fa8a68646146285828dd
https://github.com/TobiasHennig/nativescript-toast/blob/5de877615a94125bb677fa8a68646146285828dd/publish/scripts/postinstall.js#L365-L493
21,323
felixge/node-combined-stream
lib/defer.js
defer
function defer(fn) { var nextTick = typeof setImmediate == 'function' ? setImmediate : ( typeof process == 'object' && typeof process.nextTick == 'function' ? process.nextTick : null ); if (nextTick) { nextTick(fn); } else { setTimeout(fn, 0); } }
javascript
function defer(fn) { var nextTick = typeof setImmediate == 'function' ? setImmediate : ( typeof process == 'object' && typeof process.nextTick == 'function' ? process.nextTick : null ); if (nextTick) { nextTick(fn); } else { setTimeout(fn, 0); } }
[ "function", "defer", "(", "fn", ")", "{", "var", "nextTick", "=", "typeof", "setImmediate", "==", "'function'", "?", "setImmediate", ":", "(", "typeof", "process", "==", "'object'", "&&", "typeof", "process", ".", "nextTick", "==", "'function'", "?", "process", ".", "nextTick", ":", "null", ")", ";", "if", "(", "nextTick", ")", "{", "nextTick", "(", "fn", ")", ";", "}", "else", "{", "setTimeout", "(", "fn", ",", "0", ")", ";", "}", "}" ]
Runs provided function on next iteration of the event loop @param {function} fn - function to run
[ "Runs", "provided", "function", "on", "next", "iteration", "of", "the", "event", "loop" ]
3593923e4126da3e00ca6c40b2d0636de7a66579
https://github.com/felixge/node-combined-stream/blob/3593923e4126da3e00ca6c40b2d0636de7a66579/lib/defer.js#L8-L26
21,324
beakerbrowser/pauls-dat-api
lib/read.js
readFile
function readFile (archive, name, opts, cb) { if (typeof opts === 'function') { cb = opts opts = {} } return maybe(cb, async function () { opts = opts || {} if (typeof opts === 'string') { opts = { encoding: opts } } opts.encoding = toValidEncoding(opts.encoding) // check that it's a file const st = await stat(archive, name) if (!st.isFile()) { throw new NotAFileError() } // read the file return new Promise((resolve, reject) => { archive.readFile(name, opts, (err, data) => { if (err) reject(toBeakerError(err, 'readFile')) else resolve(data) }) }) }) }
javascript
function readFile (archive, name, opts, cb) { if (typeof opts === 'function') { cb = opts opts = {} } return maybe(cb, async function () { opts = opts || {} if (typeof opts === 'string') { opts = { encoding: opts } } opts.encoding = toValidEncoding(opts.encoding) // check that it's a file const st = await stat(archive, name) if (!st.isFile()) { throw new NotAFileError() } // read the file return new Promise((resolve, reject) => { archive.readFile(name, opts, (err, data) => { if (err) reject(toBeakerError(err, 'readFile')) else resolve(data) }) }) }) }
[ "function", "readFile", "(", "archive", ",", "name", ",", "opts", ",", "cb", ")", "{", "if", "(", "typeof", "opts", "===", "'function'", ")", "{", "cb", "=", "opts", "opts", "=", "{", "}", "}", "return", "maybe", "(", "cb", ",", "async", "function", "(", ")", "{", "opts", "=", "opts", "||", "{", "}", "if", "(", "typeof", "opts", "===", "'string'", ")", "{", "opts", "=", "{", "encoding", ":", "opts", "}", "}", "opts", ".", "encoding", "=", "toValidEncoding", "(", "opts", ".", "encoding", ")", "// check that it's a file", "const", "st", "=", "await", "stat", "(", "archive", ",", "name", ")", "if", "(", "!", "st", ".", "isFile", "(", ")", ")", "{", "throw", "new", "NotAFileError", "(", ")", "}", "// read the file", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "archive", ".", "readFile", "(", "name", ",", "opts", ",", "(", "err", ",", "data", ")", "=>", "{", "if", "(", "err", ")", "reject", "(", "toBeakerError", "(", "err", ",", "'readFile'", ")", ")", "else", "resolve", "(", "data", ")", "}", ")", "}", ")", "}", ")", "}" ]
helper to pull file data from an archive
[ "helper", "to", "pull", "file", "data", "from", "an", "archive" ]
70eda444a1b55c58fda21a4a005a9ef096e068f0
https://github.com/beakerbrowser/pauls-dat-api/blob/70eda444a1b55c58fda21a4a005a9ef096e068f0/lib/read.js#L7-L34
21,325
beakerbrowser/pauls-dat-api
lib/read.js
readdir
function readdir (archive, name, opts, cb) { if (typeof opts === 'function') { cb = opts opts = {} } opts = opts || {} return maybe(cb, async function () { // options var recursive = (opts && !!opts.recursive) // run first readdir var promise = new Promise((resolve, reject) => { archive.readdir(name, (err, names) => { if (err) reject(toBeakerError(err, 'readdir')) else resolve(names) }) }) var results = await promise // recurse if requested if (recursive) { var rootPath = name const readdirSafe = name => new Promise(resolve => { archive.readdir(name, (_, names) => resolve(names || [])) }) const recurse = async function (names, parentPath) { await Promise.all(names.map(async function (name) { var thisPath = path.join(parentPath, name) var subnames = await readdirSafe(thisPath) await recurse(subnames, thisPath) results = results.concat(subnames.map(subname => normalize(rootPath, thisPath, subname))) })) } await recurse(results, name) } return results }) }
javascript
function readdir (archive, name, opts, cb) { if (typeof opts === 'function') { cb = opts opts = {} } opts = opts || {} return maybe(cb, async function () { // options var recursive = (opts && !!opts.recursive) // run first readdir var promise = new Promise((resolve, reject) => { archive.readdir(name, (err, names) => { if (err) reject(toBeakerError(err, 'readdir')) else resolve(names) }) }) var results = await promise // recurse if requested if (recursive) { var rootPath = name const readdirSafe = name => new Promise(resolve => { archive.readdir(name, (_, names) => resolve(names || [])) }) const recurse = async function (names, parentPath) { await Promise.all(names.map(async function (name) { var thisPath = path.join(parentPath, name) var subnames = await readdirSafe(thisPath) await recurse(subnames, thisPath) results = results.concat(subnames.map(subname => normalize(rootPath, thisPath, subname))) })) } await recurse(results, name) } return results }) }
[ "function", "readdir", "(", "archive", ",", "name", ",", "opts", ",", "cb", ")", "{", "if", "(", "typeof", "opts", "===", "'function'", ")", "{", "cb", "=", "opts", "opts", "=", "{", "}", "}", "opts", "=", "opts", "||", "{", "}", "return", "maybe", "(", "cb", ",", "async", "function", "(", ")", "{", "// options", "var", "recursive", "=", "(", "opts", "&&", "!", "!", "opts", ".", "recursive", ")", "// run first readdir", "var", "promise", "=", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "archive", ".", "readdir", "(", "name", ",", "(", "err", ",", "names", ")", "=>", "{", "if", "(", "err", ")", "reject", "(", "toBeakerError", "(", "err", ",", "'readdir'", ")", ")", "else", "resolve", "(", "names", ")", "}", ")", "}", ")", "var", "results", "=", "await", "promise", "// recurse if requested", "if", "(", "recursive", ")", "{", "var", "rootPath", "=", "name", "const", "readdirSafe", "=", "name", "=>", "new", "Promise", "(", "resolve", "=>", "{", "archive", ".", "readdir", "(", "name", ",", "(", "_", ",", "names", ")", "=>", "resolve", "(", "names", "||", "[", "]", ")", ")", "}", ")", "const", "recurse", "=", "async", "function", "(", "names", ",", "parentPath", ")", "{", "await", "Promise", ".", "all", "(", "names", ".", "map", "(", "async", "function", "(", "name", ")", "{", "var", "thisPath", "=", "path", ".", "join", "(", "parentPath", ",", "name", ")", "var", "subnames", "=", "await", "readdirSafe", "(", "thisPath", ")", "await", "recurse", "(", "subnames", ",", "thisPath", ")", "results", "=", "results", ".", "concat", "(", "subnames", ".", "map", "(", "subname", "=>", "normalize", "(", "rootPath", ",", "thisPath", ",", "subname", ")", ")", ")", "}", ")", ")", "}", "await", "recurse", "(", "results", ",", "name", ")", "}", "return", "results", "}", ")", "}" ]
helper to list the files in a directory
[ "helper", "to", "list", "the", "files", "in", "a", "directory" ]
70eda444a1b55c58fda21a4a005a9ef096e068f0
https://github.com/beakerbrowser/pauls-dat-api/blob/70eda444a1b55c58fda21a4a005a9ef096e068f0/lib/read.js#L37-L75
21,326
beakerbrowser/pauls-dat-api
lib/export.js
exportArchiveToFilesystem
function exportArchiveToFilesystem (opts, cb) { return maybe(cb, async function () { assert(opts && typeof opts === 'object', 'opts object is required') // core arguments, dstPath and srcArchive var srcArchive = opts.srcArchive var dstPath = opts.dstPath assert(srcArchive && typeof srcArchive === 'object', 'srcArchive is required') assert(dstPath && typeof dstPath === 'string', 'dstPath is required') // options var srcPath = typeof opts.srcPath === 'string' ? opts.srcPath : '/' var overwriteExisting = opts.overwriteExisting === true var skipUndownloadedFiles = opts.skipUndownloadedFiles === true var ignore = Array.isArray(opts.ignore) ? opts.ignore : DEFAULT_IGNORE // abort if nonempty and not overwriting existing if (!overwriteExisting) { let files try { files = await fse.readdir(dstPath) } catch (e) { // target probably doesnt exist, continue and let ensureDirectory handle it } if (files && files.length > 0) { throw new DestDirectoryNotEmpty() } } const statThenExport = async function (srcPath, dstPath) { // apply ignore filter if (ignore && match(ignore, srcPath)) { return } // export by type var srcStat = await stat(srcArchive, srcPath) if (srcStat.isFile()) { await exportFile(srcPath, srcStat, dstPath) } else if (srcStat.isDirectory()) { await exportDirectory(srcPath, dstPath) } } const exportFile = async function (srcPath, srcStat, dstPath) { // skip undownloaded files if (skipUndownloadedFiles && srcStat.downloaded < srcStat.blocks) { return } // fetch dest stats var dstFileStats = null try { dstFileStats = await fse.stat(dstPath) } catch (e) {} // track the stats stats.fileCount++ stats.totalSize += srcStat.size || 0 if (dstFileStats) { if (dstFileStats.isDirectory()) { // delete the directory-tree await fse.remove(dstPath) stats.addedFiles.push(dstPath) } else { stats.updatedFiles.push(dstPath) } } else { stats.addedFiles.push(dstPath) } // write the file return new Promise((resolve, reject) => { pump( srcArchive.createReadStream(srcPath), fse.createWriteStream(dstPath), err => { if (err) reject(err) else resolve() } ) }) } const exportDirectory = async function (srcPath, dstPath) { // make sure the destination folder exists await fse.ensureDir(dstPath) // list the directory var fileNames = await readdir(srcArchive, srcPath) // recurse into each var promises = fileNames.map(name => { return statThenExport(path.join(srcPath, name), path.join(dstPath, name)) }) await Promise.all(promises) } // recursively export var stats = { addedFiles: [], updatedFiles: [], skipCount: 0, fileCount: 0, totalSize: 0 } await statThenExport(srcPath, dstPath) return stats }) }
javascript
function exportArchiveToFilesystem (opts, cb) { return maybe(cb, async function () { assert(opts && typeof opts === 'object', 'opts object is required') // core arguments, dstPath and srcArchive var srcArchive = opts.srcArchive var dstPath = opts.dstPath assert(srcArchive && typeof srcArchive === 'object', 'srcArchive is required') assert(dstPath && typeof dstPath === 'string', 'dstPath is required') // options var srcPath = typeof opts.srcPath === 'string' ? opts.srcPath : '/' var overwriteExisting = opts.overwriteExisting === true var skipUndownloadedFiles = opts.skipUndownloadedFiles === true var ignore = Array.isArray(opts.ignore) ? opts.ignore : DEFAULT_IGNORE // abort if nonempty and not overwriting existing if (!overwriteExisting) { let files try { files = await fse.readdir(dstPath) } catch (e) { // target probably doesnt exist, continue and let ensureDirectory handle it } if (files && files.length > 0) { throw new DestDirectoryNotEmpty() } } const statThenExport = async function (srcPath, dstPath) { // apply ignore filter if (ignore && match(ignore, srcPath)) { return } // export by type var srcStat = await stat(srcArchive, srcPath) if (srcStat.isFile()) { await exportFile(srcPath, srcStat, dstPath) } else if (srcStat.isDirectory()) { await exportDirectory(srcPath, dstPath) } } const exportFile = async function (srcPath, srcStat, dstPath) { // skip undownloaded files if (skipUndownloadedFiles && srcStat.downloaded < srcStat.blocks) { return } // fetch dest stats var dstFileStats = null try { dstFileStats = await fse.stat(dstPath) } catch (e) {} // track the stats stats.fileCount++ stats.totalSize += srcStat.size || 0 if (dstFileStats) { if (dstFileStats.isDirectory()) { // delete the directory-tree await fse.remove(dstPath) stats.addedFiles.push(dstPath) } else { stats.updatedFiles.push(dstPath) } } else { stats.addedFiles.push(dstPath) } // write the file return new Promise((resolve, reject) => { pump( srcArchive.createReadStream(srcPath), fse.createWriteStream(dstPath), err => { if (err) reject(err) else resolve() } ) }) } const exportDirectory = async function (srcPath, dstPath) { // make sure the destination folder exists await fse.ensureDir(dstPath) // list the directory var fileNames = await readdir(srcArchive, srcPath) // recurse into each var promises = fileNames.map(name => { return statThenExport(path.join(srcPath, name), path.join(dstPath, name)) }) await Promise.all(promises) } // recursively export var stats = { addedFiles: [], updatedFiles: [], skipCount: 0, fileCount: 0, totalSize: 0 } await statThenExport(srcPath, dstPath) return stats }) }
[ "function", "exportArchiveToFilesystem", "(", "opts", ",", "cb", ")", "{", "return", "maybe", "(", "cb", ",", "async", "function", "(", ")", "{", "assert", "(", "opts", "&&", "typeof", "opts", "===", "'object'", ",", "'opts object is required'", ")", "// core arguments, dstPath and srcArchive", "var", "srcArchive", "=", "opts", ".", "srcArchive", "var", "dstPath", "=", "opts", ".", "dstPath", "assert", "(", "srcArchive", "&&", "typeof", "srcArchive", "===", "'object'", ",", "'srcArchive is required'", ")", "assert", "(", "dstPath", "&&", "typeof", "dstPath", "===", "'string'", ",", "'dstPath is required'", ")", "// options", "var", "srcPath", "=", "typeof", "opts", ".", "srcPath", "===", "'string'", "?", "opts", ".", "srcPath", ":", "'/'", "var", "overwriteExisting", "=", "opts", ".", "overwriteExisting", "===", "true", "var", "skipUndownloadedFiles", "=", "opts", ".", "skipUndownloadedFiles", "===", "true", "var", "ignore", "=", "Array", ".", "isArray", "(", "opts", ".", "ignore", ")", "?", "opts", ".", "ignore", ":", "DEFAULT_IGNORE", "// abort if nonempty and not overwriting existing", "if", "(", "!", "overwriteExisting", ")", "{", "let", "files", "try", "{", "files", "=", "await", "fse", ".", "readdir", "(", "dstPath", ")", "}", "catch", "(", "e", ")", "{", "// target probably doesnt exist, continue and let ensureDirectory handle it", "}", "if", "(", "files", "&&", "files", ".", "length", ">", "0", ")", "{", "throw", "new", "DestDirectoryNotEmpty", "(", ")", "}", "}", "const", "statThenExport", "=", "async", "function", "(", "srcPath", ",", "dstPath", ")", "{", "// apply ignore filter", "if", "(", "ignore", "&&", "match", "(", "ignore", ",", "srcPath", ")", ")", "{", "return", "}", "// export by type", "var", "srcStat", "=", "await", "stat", "(", "srcArchive", ",", "srcPath", ")", "if", "(", "srcStat", ".", "isFile", "(", ")", ")", "{", "await", "exportFile", "(", "srcPath", ",", "srcStat", ",", "dstPath", ")", "}", "else", "if", "(", "srcStat", ".", "isDirectory", "(", ")", ")", "{", "await", "exportDirectory", "(", "srcPath", ",", "dstPath", ")", "}", "}", "const", "exportFile", "=", "async", "function", "(", "srcPath", ",", "srcStat", ",", "dstPath", ")", "{", "// skip undownloaded files", "if", "(", "skipUndownloadedFiles", "&&", "srcStat", ".", "downloaded", "<", "srcStat", ".", "blocks", ")", "{", "return", "}", "// fetch dest stats", "var", "dstFileStats", "=", "null", "try", "{", "dstFileStats", "=", "await", "fse", ".", "stat", "(", "dstPath", ")", "}", "catch", "(", "e", ")", "{", "}", "// track the stats", "stats", ".", "fileCount", "++", "stats", ".", "totalSize", "+=", "srcStat", ".", "size", "||", "0", "if", "(", "dstFileStats", ")", "{", "if", "(", "dstFileStats", ".", "isDirectory", "(", ")", ")", "{", "// delete the directory-tree", "await", "fse", ".", "remove", "(", "dstPath", ")", "stats", ".", "addedFiles", ".", "push", "(", "dstPath", ")", "}", "else", "{", "stats", ".", "updatedFiles", ".", "push", "(", "dstPath", ")", "}", "}", "else", "{", "stats", ".", "addedFiles", ".", "push", "(", "dstPath", ")", "}", "// write the file", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "pump", "(", "srcArchive", ".", "createReadStream", "(", "srcPath", ")", ",", "fse", ".", "createWriteStream", "(", "dstPath", ")", ",", "err", "=>", "{", "if", "(", "err", ")", "reject", "(", "err", ")", "else", "resolve", "(", ")", "}", ")", "}", ")", "}", "const", "exportDirectory", "=", "async", "function", "(", "srcPath", ",", "dstPath", ")", "{", "// make sure the destination folder exists", "await", "fse", ".", "ensureDir", "(", "dstPath", ")", "// list the directory", "var", "fileNames", "=", "await", "readdir", "(", "srcArchive", ",", "srcPath", ")", "// recurse into each", "var", "promises", "=", "fileNames", ".", "map", "(", "name", "=>", "{", "return", "statThenExport", "(", "path", ".", "join", "(", "srcPath", ",", "name", ")", ",", "path", ".", "join", "(", "dstPath", ",", "name", ")", ")", "}", ")", "await", "Promise", ".", "all", "(", "promises", ")", "}", "// recursively export", "var", "stats", "=", "{", "addedFiles", ":", "[", "]", ",", "updatedFiles", ":", "[", "]", ",", "skipCount", ":", "0", ",", "fileCount", ":", "0", ",", "totalSize", ":", "0", "}", "await", "statThenExport", "(", "srcPath", ",", "dstPath", ")", "return", "stats", "}", ")", "}" ]
copy files from an archive into the filesystem
[ "copy", "files", "from", "an", "archive", "into", "the", "filesystem" ]
70eda444a1b55c58fda21a4a005a9ef096e068f0
https://github.com/beakerbrowser/pauls-dat-api/blob/70eda444a1b55c58fda21a4a005a9ef096e068f0/lib/export.js#L172-L275
21,327
beakerbrowser/pauls-dat-api
lib/manifest.js
readManifest
function readManifest (archive, cb) { return maybe(cb, async function () { var data = await readFile(archive, DAT_MANIFEST_FILENAME) data = JSON.parse(data.toString()) if (data.links) data.links = massageLinks(data.links) return data }) }
javascript
function readManifest (archive, cb) { return maybe(cb, async function () { var data = await readFile(archive, DAT_MANIFEST_FILENAME) data = JSON.parse(data.toString()) if (data.links) data.links = massageLinks(data.links) return data }) }
[ "function", "readManifest", "(", "archive", ",", "cb", ")", "{", "return", "maybe", "(", "cb", ",", "async", "function", "(", ")", "{", "var", "data", "=", "await", "readFile", "(", "archive", ",", "DAT_MANIFEST_FILENAME", ")", "data", "=", "JSON", ".", "parse", "(", "data", ".", "toString", "(", ")", ")", "if", "(", "data", ".", "links", ")", "data", ".", "links", "=", "massageLinks", "(", "data", ".", "links", ")", "return", "data", "}", ")", "}" ]
helper to read the manifest into an object
[ "helper", "to", "read", "the", "manifest", "into", "an", "object" ]
70eda444a1b55c58fda21a4a005a9ef096e068f0
https://github.com/beakerbrowser/pauls-dat-api/blob/70eda444a1b55c58fda21a4a005a9ef096e068f0/lib/manifest.js#L7-L14
21,328
beakerbrowser/pauls-dat-api
lib/manifest.js
writeManifest
function writeManifest (archive, manifest, cb) { manifest = generateManifest(manifest) return writeFile(archive, DAT_MANIFEST_FILENAME, JSON.stringify(manifest, null, 2), cb) }
javascript
function writeManifest (archive, manifest, cb) { manifest = generateManifest(manifest) return writeFile(archive, DAT_MANIFEST_FILENAME, JSON.stringify(manifest, null, 2), cb) }
[ "function", "writeManifest", "(", "archive", ",", "manifest", ",", "cb", ")", "{", "manifest", "=", "generateManifest", "(", "manifest", ")", "return", "writeFile", "(", "archive", ",", "DAT_MANIFEST_FILENAME", ",", "JSON", ".", "stringify", "(", "manifest", ",", "null", ",", "2", ")", ",", "cb", ")", "}" ]
helper to write a manifest object
[ "helper", "to", "write", "a", "manifest", "object" ]
70eda444a1b55c58fda21a4a005a9ef096e068f0
https://github.com/beakerbrowser/pauls-dat-api/blob/70eda444a1b55c58fda21a4a005a9ef096e068f0/lib/manifest.js#L17-L20
21,329
beakerbrowser/pauls-dat-api
lib/manifest.js
updateManifest
function updateManifest (archive, updates, cb) { return maybe(cb, async function () { var manifest try { manifest = await readManifest(archive) } catch (e) { manifest = {} } Object.assign(manifest, generateManifest(updates)) return writeManifest(archive, manifest) }) }
javascript
function updateManifest (archive, updates, cb) { return maybe(cb, async function () { var manifest try { manifest = await readManifest(archive) } catch (e) { manifest = {} } Object.assign(manifest, generateManifest(updates)) return writeManifest(archive, manifest) }) }
[ "function", "updateManifest", "(", "archive", ",", "updates", ",", "cb", ")", "{", "return", "maybe", "(", "cb", ",", "async", "function", "(", ")", "{", "var", "manifest", "try", "{", "manifest", "=", "await", "readManifest", "(", "archive", ")", "}", "catch", "(", "e", ")", "{", "manifest", "=", "{", "}", "}", "Object", ".", "assign", "(", "manifest", ",", "generateManifest", "(", "updates", ")", ")", "return", "writeManifest", "(", "archive", ",", "manifest", ")", "}", ")", "}" ]
helper to write updates to a manifest object
[ "helper", "to", "write", "updates", "to", "a", "manifest", "object" ]
70eda444a1b55c58fda21a4a005a9ef096e068f0
https://github.com/beakerbrowser/pauls-dat-api/blob/70eda444a1b55c58fda21a4a005a9ef096e068f0/lib/manifest.js#L23-L34
21,330
beakerbrowser/pauls-dat-api
lib/manifest.js
generateManifest
function generateManifest (manifest = {}) { var { url, title, description, type, author, links, web_root, fallback_page } = manifest if (isString(url)) manifest.url = url else delete manifest.url if (isString(title)) manifest.title = title else delete manifest.title if (isString(description)) manifest.description = description else delete manifest.description if (isString(type)) type = type.split(' ') if (isArrayOfStrings(type)) manifest.type = type else delete manifest.type if (isObject(links)) manifest.links = massageLinks(links) else delete manifest.links if (isString(web_root)) manifest.web_root = web_root else delete manifest.web_root if (isString(fallback_page)) manifest.fallback_page = fallback_page else delete manifest.fallback_page if (isString(author)) { if (author.startsWith('dat://') || DAT_HASH_REGEX.test(author)) { author = {url: author} } else { author = {name: author} } } if (isObject(author)) { manifest.author = {} if (isString(author.name)) manifest.author.name = author.name if (isString(author.url) && (author.url.startsWith('dat://') || DAT_HASH_REGEX.test(author.url))) { manifest.author.url = author.url } } else { delete manifest.author } return manifest }
javascript
function generateManifest (manifest = {}) { var { url, title, description, type, author, links, web_root, fallback_page } = manifest if (isString(url)) manifest.url = url else delete manifest.url if (isString(title)) manifest.title = title else delete manifest.title if (isString(description)) manifest.description = description else delete manifest.description if (isString(type)) type = type.split(' ') if (isArrayOfStrings(type)) manifest.type = type else delete manifest.type if (isObject(links)) manifest.links = massageLinks(links) else delete manifest.links if (isString(web_root)) manifest.web_root = web_root else delete manifest.web_root if (isString(fallback_page)) manifest.fallback_page = fallback_page else delete manifest.fallback_page if (isString(author)) { if (author.startsWith('dat://') || DAT_HASH_REGEX.test(author)) { author = {url: author} } else { author = {name: author} } } if (isObject(author)) { manifest.author = {} if (isString(author.name)) manifest.author.name = author.name if (isString(author.url) && (author.url.startsWith('dat://') || DAT_HASH_REGEX.test(author.url))) { manifest.author.url = author.url } } else { delete manifest.author } return manifest }
[ "function", "generateManifest", "(", "manifest", "=", "{", "}", ")", "{", "var", "{", "url", ",", "title", ",", "description", ",", "type", ",", "author", ",", "links", ",", "web_root", ",", "fallback_page", "}", "=", "manifest", "if", "(", "isString", "(", "url", ")", ")", "manifest", ".", "url", "=", "url", "else", "delete", "manifest", ".", "url", "if", "(", "isString", "(", "title", ")", ")", "manifest", ".", "title", "=", "title", "else", "delete", "manifest", ".", "title", "if", "(", "isString", "(", "description", ")", ")", "manifest", ".", "description", "=", "description", "else", "delete", "manifest", ".", "description", "if", "(", "isString", "(", "type", ")", ")", "type", "=", "type", ".", "split", "(", "' '", ")", "if", "(", "isArrayOfStrings", "(", "type", ")", ")", "manifest", ".", "type", "=", "type", "else", "delete", "manifest", ".", "type", "if", "(", "isObject", "(", "links", ")", ")", "manifest", ".", "links", "=", "massageLinks", "(", "links", ")", "else", "delete", "manifest", ".", "links", "if", "(", "isString", "(", "web_root", ")", ")", "manifest", ".", "web_root", "=", "web_root", "else", "delete", "manifest", ".", "web_root", "if", "(", "isString", "(", "fallback_page", ")", ")", "manifest", ".", "fallback_page", "=", "fallback_page", "else", "delete", "manifest", ".", "fallback_page", "if", "(", "isString", "(", "author", ")", ")", "{", "if", "(", "author", ".", "startsWith", "(", "'dat://'", ")", "||", "DAT_HASH_REGEX", ".", "test", "(", "author", ")", ")", "{", "author", "=", "{", "url", ":", "author", "}", "}", "else", "{", "author", "=", "{", "name", ":", "author", "}", "}", "}", "if", "(", "isObject", "(", "author", ")", ")", "{", "manifest", ".", "author", "=", "{", "}", "if", "(", "isString", "(", "author", ".", "name", ")", ")", "manifest", ".", "author", ".", "name", "=", "author", ".", "name", "if", "(", "isString", "(", "author", ".", "url", ")", "&&", "(", "author", ".", "url", ".", "startsWith", "(", "'dat://'", ")", "||", "DAT_HASH_REGEX", ".", "test", "(", "author", ".", "url", ")", ")", ")", "{", "manifest", ".", "author", ".", "url", "=", "author", ".", "url", "}", "}", "else", "{", "delete", "manifest", ".", "author", "}", "return", "manifest", "}" ]
helper to generate a new dat.json object
[ "helper", "to", "generate", "a", "new", "dat", ".", "json", "object" ]
70eda444a1b55c58fda21a4a005a9ef096e068f0
https://github.com/beakerbrowser/pauls-dat-api/blob/70eda444a1b55c58fda21a4a005a9ef096e068f0/lib/manifest.js#L37-L71
21,331
beakerbrowser/pauls-dat-api
lib/lookup.js
stat
function stat (archive, name, cb) { return maybe(cb, new Promise((resolve, reject) => { // run stat operation archive.stat(name, (err, st) => { if (err) reject(toBeakerError(err, 'stat')) else { // read download status st.downloaded = 0 if (!archive.key) { // fs, not an archive st.downloaded = st.blocks } else if (st.isFile()) { if (archive.content && archive.content.length) { st.downloaded = archive.content.downloaded(st.offset, st.offset + st.blocks) } } resolve(st) } }) })) }
javascript
function stat (archive, name, cb) { return maybe(cb, new Promise((resolve, reject) => { // run stat operation archive.stat(name, (err, st) => { if (err) reject(toBeakerError(err, 'stat')) else { // read download status st.downloaded = 0 if (!archive.key) { // fs, not an archive st.downloaded = st.blocks } else if (st.isFile()) { if (archive.content && archive.content.length) { st.downloaded = archive.content.downloaded(st.offset, st.offset + st.blocks) } } resolve(st) } }) })) }
[ "function", "stat", "(", "archive", ",", "name", ",", "cb", ")", "{", "return", "maybe", "(", "cb", ",", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "// run stat operation", "archive", ".", "stat", "(", "name", ",", "(", "err", ",", "st", ")", "=>", "{", "if", "(", "err", ")", "reject", "(", "toBeakerError", "(", "err", ",", "'stat'", ")", ")", "else", "{", "// read download status", "st", ".", "downloaded", "=", "0", "if", "(", "!", "archive", ".", "key", ")", "{", "// fs, not an archive", "st", ".", "downloaded", "=", "st", ".", "blocks", "}", "else", "if", "(", "st", ".", "isFile", "(", ")", ")", "{", "if", "(", "archive", ".", "content", "&&", "archive", ".", "content", ".", "length", ")", "{", "st", ".", "downloaded", "=", "archive", ".", "content", ".", "downloaded", "(", "st", ".", "offset", ",", "st", ".", "offset", "+", "st", ".", "blocks", ")", "}", "}", "resolve", "(", "st", ")", "}", "}", ")", "}", ")", ")", "}" ]
lookup information about a file
[ "lookup", "information", "about", "a", "file" ]
70eda444a1b55c58fda21a4a005a9ef096e068f0
https://github.com/beakerbrowser/pauls-dat-api/blob/70eda444a1b55c58fda21a4a005a9ef096e068f0/lib/lookup.js#L4-L24
21,332
crosswalk-project/crosswalk-app-tools
src/util/Version.js
Version
function Version(major, minor, micro, build) { if (typeof major === "number" && major % 1 === 0) this._major = major; else throw new Error("Invalid major version number '" + major + "'"); if (typeof minor === "number" && minor % 1 === 0) this._minor = minor; else throw new Error("Invalid minor version number '" + minor + "'"); if (typeof micro === "number" && micro % 1 === 0) this._micro = micro; else throw new Error("Invalid micro version number '" + micro + "'"); if (typeof build === "number" && build % 1 === 0) this._build = build; else throw new Error("Invalid build version number '" + build + "'"); }
javascript
function Version(major, minor, micro, build) { if (typeof major === "number" && major % 1 === 0) this._major = major; else throw new Error("Invalid major version number '" + major + "'"); if (typeof minor === "number" && minor % 1 === 0) this._minor = minor; else throw new Error("Invalid minor version number '" + minor + "'"); if (typeof micro === "number" && micro % 1 === 0) this._micro = micro; else throw new Error("Invalid micro version number '" + micro + "'"); if (typeof build === "number" && build % 1 === 0) this._build = build; else throw new Error("Invalid build version number '" + build + "'"); }
[ "function", "Version", "(", "major", ",", "minor", ",", "micro", ",", "build", ")", "{", "if", "(", "typeof", "major", "===", "\"number\"", "&&", "major", "%", "1", "===", "0", ")", "this", ".", "_major", "=", "major", ";", "else", "throw", "new", "Error", "(", "\"Invalid major version number '\"", "+", "major", "+", "\"'\"", ")", ";", "if", "(", "typeof", "minor", "===", "\"number\"", "&&", "minor", "%", "1", "===", "0", ")", "this", ".", "_minor", "=", "minor", ";", "else", "throw", "new", "Error", "(", "\"Invalid minor version number '\"", "+", "minor", "+", "\"'\"", ")", ";", "if", "(", "typeof", "micro", "===", "\"number\"", "&&", "micro", "%", "1", "===", "0", ")", "this", ".", "_micro", "=", "micro", ";", "else", "throw", "new", "Error", "(", "\"Invalid micro version number '\"", "+", "micro", "+", "\"'\"", ")", ";", "if", "(", "typeof", "build", "===", "\"number\"", "&&", "build", "%", "1", "===", "0", ")", "this", ".", "_build", "=", "build", ";", "else", "throw", "new", "Error", "(", "\"Invalid build version number '\"", "+", "build", "+", "\"'\"", ")", ";", "}" ]
Representation of a four part Crosswalk version number. @param {Number} major @param {Number} minor @param {Number} micro @param {Number} build @constructor
[ "Representation", "of", "a", "four", "part", "Crosswalk", "version", "number", "." ]
2771b2fa4326c2453b41de393284de68a2fe7eac
https://github.com/crosswalk-project/crosswalk-app-tools/blob/2771b2fa4326c2453b41de393284de68a2fe7eac/src/util/Version.js#L16-L37
21,333
crosswalk-project/crosswalk-app-tools
src/Application.js
initMembers
function initMembers(rootPath) { this._rootPath = rootPath; ShellJS.mkdir(this._rootPath); this._appPath = this._rootPath + Path.sep + "app"; ShellJS.mkdir(this._appPath); this._logPath = Path.join(OS.tmpdir(), "crosswalk-app-tools-" + this._packageId); ShellJS.mkdir(this._logPath); // Packages end up in working dir this._pkgPath = process.cwd(); this._prjPath = this._rootPath + Path.sep + "prj"; ShellJS.mkdir(this._prjPath); }
javascript
function initMembers(rootPath) { this._rootPath = rootPath; ShellJS.mkdir(this._rootPath); this._appPath = this._rootPath + Path.sep + "app"; ShellJS.mkdir(this._appPath); this._logPath = Path.join(OS.tmpdir(), "crosswalk-app-tools-" + this._packageId); ShellJS.mkdir(this._logPath); // Packages end up in working dir this._pkgPath = process.cwd(); this._prjPath = this._rootPath + Path.sep + "prj"; ShellJS.mkdir(this._prjPath); }
[ "function", "initMembers", "(", "rootPath", ")", "{", "this", ".", "_rootPath", "=", "rootPath", ";", "ShellJS", ".", "mkdir", "(", "this", ".", "_rootPath", ")", ";", "this", ".", "_appPath", "=", "this", ".", "_rootPath", "+", "Path", ".", "sep", "+", "\"app\"", ";", "ShellJS", ".", "mkdir", "(", "this", ".", "_appPath", ")", ";", "this", ".", "_logPath", "=", "Path", ".", "join", "(", "OS", ".", "tmpdir", "(", ")", ",", "\"crosswalk-app-tools-\"", "+", "this", ".", "_packageId", ")", ";", "ShellJS", ".", "mkdir", "(", "this", ".", "_logPath", ")", ";", "// Packages end up in working dir", "this", ".", "_pkgPath", "=", "process", ".", "cwd", "(", ")", ";", "this", ".", "_prjPath", "=", "this", ".", "_rootPath", "+", "Path", ".", "sep", "+", "\"prj\"", ";", "ShellJS", ".", "mkdir", "(", "this", ".", "_prjPath", ")", ";", "}" ]
Initialize paths. @param {String} rootPath Root path inside the project
[ "Initialize", "paths", "." ]
2771b2fa4326c2453b41de393284de68a2fe7eac
https://github.com/crosswalk-project/crosswalk-app-tools/blob/2771b2fa4326c2453b41de393284de68a2fe7eac/src/Application.js#L112-L128
21,334
crosswalk-project/crosswalk-app-tools
src/util/TemplateFile.js
TemplateFile
function TemplateFile(path) { this._buffer = FS.readFileSync(path, {"encoding": "utf8"}); if (!this._buffer || this._buffer.length === 0) { throw new Error("Could not read " + path); } }
javascript
function TemplateFile(path) { this._buffer = FS.readFileSync(path, {"encoding": "utf8"}); if (!this._buffer || this._buffer.length === 0) { throw new Error("Could not read " + path); } }
[ "function", "TemplateFile", "(", "path", ")", "{", "this", ".", "_buffer", "=", "FS", ".", "readFileSync", "(", "path", ",", "{", "\"encoding\"", ":", "\"utf8\"", "}", ")", ";", "if", "(", "!", "this", ".", "_buffer", "||", "this", ".", "_buffer", ".", "length", "===", "0", ")", "{", "throw", "new", "Error", "(", "\"Could not read \"", "+", "path", ")", ";", "}", "}" ]
Class to handle reading and writing template files. @constructor @param {String} path Path to template file @throws {Error} If file could not be read.
[ "Class", "to", "handle", "reading", "and", "writing", "template", "files", "." ]
2771b2fa4326c2453b41de393284de68a2fe7eac
https://github.com/crosswalk-project/crosswalk-app-tools/blob/2771b2fa4326c2453b41de393284de68a2fe7eac/src/util/TemplateFile.js#L14-L20
21,335
crosswalk-project/crosswalk-app-tools
src/OutputTee.js
OutputTee
function OutputTee(logfileOutput, terminalOutput) { this._outputs = []; this._outputs[_OUTPUT_TEE_LOGFILE] = logfileOutput; this._outputs[_OUTPUT_TEE_TERMINAL] = terminalOutput; }
javascript
function OutputTee(logfileOutput, terminalOutput) { this._outputs = []; this._outputs[_OUTPUT_TEE_LOGFILE] = logfileOutput; this._outputs[_OUTPUT_TEE_TERMINAL] = terminalOutput; }
[ "function", "OutputTee", "(", "logfileOutput", ",", "terminalOutput", ")", "{", "this", ".", "_outputs", "=", "[", "]", ";", "this", ".", "_outputs", "[", "_OUTPUT_TEE_LOGFILE", "]", "=", "logfileOutput", ";", "this", ".", "_outputs", "[", "_OUTPUT_TEE_TERMINAL", "]", "=", "terminalOutput", ";", "}" ]
Console output interface. @constructor @param {OutputIface} logfileOutput @extends OutputIface
[ "Console", "output", "interface", "." ]
2771b2fa4326c2453b41de393284de68a2fe7eac
https://github.com/crosswalk-project/crosswalk-app-tools/blob/2771b2fa4326c2453b41de393284de68a2fe7eac/src/OutputTee.js#L16-L21
21,336
crosswalk-project/crosswalk-app-tools
windows/lib/WinPlatform.js
WinPlatform
function WinPlatform(PlatformBase, baseData) { // Create base instance. var instance = new PlatformBase(baseData); // Override manually, because Object.extend() is not yet available on node. var names = Object.getOwnPropertyNames(WinPlatform.prototype); for (var i = 0; i < names.length; i++) { var key = names[i]; if (key != "constructor") { instance[key] = WinPlatform.prototype[key]; } } return instance; }
javascript
function WinPlatform(PlatformBase, baseData) { // Create base instance. var instance = new PlatformBase(baseData); // Override manually, because Object.extend() is not yet available on node. var names = Object.getOwnPropertyNames(WinPlatform.prototype); for (var i = 0; i < names.length; i++) { var key = names[i]; if (key != "constructor") { instance[key] = WinPlatform.prototype[key]; } } return instance; }
[ "function", "WinPlatform", "(", "PlatformBase", ",", "baseData", ")", "{", "// Create base instance.", "var", "instance", "=", "new", "PlatformBase", "(", "baseData", ")", ";", "// Override manually, because Object.extend() is not yet available on node.", "var", "names", "=", "Object", ".", "getOwnPropertyNames", "(", "WinPlatform", ".", "prototype", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "names", ".", "length", ";", "i", "++", ")", "{", "var", "key", "=", "names", "[", "i", "]", ";", "if", "(", "key", "!=", "\"constructor\"", ")", "{", "instance", "[", "key", "]", "=", "WinPlatform", ".", "prototype", "[", "key", "]", ";", "}", "}", "return", "instance", ";", "}" ]
Interface for project implementations. @constructor @param {Function} PlatformBase Base class constructor {@link PlatformBase} @param {PlatformData} platformData Init data passed to the platform @protected
[ "Interface", "for", "project", "implementations", "." ]
2771b2fa4326c2453b41de393284de68a2fe7eac
https://github.com/crosswalk-project/crosswalk-app-tools/blob/2771b2fa4326c2453b41de393284de68a2fe7eac/windows/lib/WinPlatform.js#L18-L33
21,337
crosswalk-project/crosswalk-app-tools
src/util/CrosswalkZip.js
CrosswalkZip
function CrosswalkZip(path) { this._adm = new AdmZip(path); // Derive root entry name from the filename var base = Path.basename(path, ".zip"); this._root = base + "/"; // Extract version var version = base.split("-")[1]; var numbers = version.split("."); this._version = new Version(+numbers[0], +numbers[1], +numbers[2], +numbers[3]); }
javascript
function CrosswalkZip(path) { this._adm = new AdmZip(path); // Derive root entry name from the filename var base = Path.basename(path, ".zip"); this._root = base + "/"; // Extract version var version = base.split("-")[1]; var numbers = version.split("."); this._version = new Version(+numbers[0], +numbers[1], +numbers[2], +numbers[3]); }
[ "function", "CrosswalkZip", "(", "path", ")", "{", "this", ".", "_adm", "=", "new", "AdmZip", "(", "path", ")", ";", "// Derive root entry name from the filename", "var", "base", "=", "Path", ".", "basename", "(", "path", ",", "\".zip\"", ")", ";", "this", ".", "_root", "=", "base", "+", "\"/\"", ";", "// Extract version", "var", "version", "=", "base", ".", "split", "(", "\"-\"", ")", "[", "1", "]", ";", "var", "numbers", "=", "version", ".", "split", "(", "\".\"", ")", ";", "this", ".", "_version", "=", "new", "Version", "(", "+", "numbers", "[", "0", "]", ",", "+", "numbers", "[", "1", "]", ",", "+", "numbers", "[", "2", "]", ",", "+", "numbers", "[", "3", "]", ")", ";", "}" ]
Creates a CrosswalkZip object. @param {String} path Path to downloaded release @constructor
[ "Creates", "a", "CrosswalkZip", "object", "." ]
2771b2fa4326c2453b41de393284de68a2fe7eac
https://github.com/crosswalk-project/crosswalk-app-tools/blob/2771b2fa4326c2453b41de393284de68a2fe7eac/src/util/CrosswalkZip.js#L19-L31
21,338
crosswalk-project/crosswalk-app-tools
android/lib/AndroidPlatform.js
AndroidPlatform
function AndroidPlatform(PlatformBase, baseData) { // Create base instance. var instance = new PlatformBase(baseData); var o = instance.output; // Override manually, because Object.extend() is not yet available on node. var names = Object.getOwnPropertyNames(AndroidPlatform.prototype); for (var i = 0; i < names.length; i++) { var key = names[i]; if (key != "constructor") { instance[key] = AndroidPlatform.prototype[key]; } } instance._sdk = new AndroidSDK(instance.application); instance._channel = "stable"; instance._lite = false; instance._shared = false; instance._apiTarget = null; return instance; }
javascript
function AndroidPlatform(PlatformBase, baseData) { // Create base instance. var instance = new PlatformBase(baseData); var o = instance.output; // Override manually, because Object.extend() is not yet available on node. var names = Object.getOwnPropertyNames(AndroidPlatform.prototype); for (var i = 0; i < names.length; i++) { var key = names[i]; if (key != "constructor") { instance[key] = AndroidPlatform.prototype[key]; } } instance._sdk = new AndroidSDK(instance.application); instance._channel = "stable"; instance._lite = false; instance._shared = false; instance._apiTarget = null; return instance; }
[ "function", "AndroidPlatform", "(", "PlatformBase", ",", "baseData", ")", "{", "// Create base instance.", "var", "instance", "=", "new", "PlatformBase", "(", "baseData", ")", ";", "var", "o", "=", "instance", ".", "output", ";", "// Override manually, because Object.extend() is not yet available on node.", "var", "names", "=", "Object", ".", "getOwnPropertyNames", "(", "AndroidPlatform", ".", "prototype", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "names", ".", "length", ";", "i", "++", ")", "{", "var", "key", "=", "names", "[", "i", "]", ";", "if", "(", "key", "!=", "\"constructor\"", ")", "{", "instance", "[", "key", "]", "=", "AndroidPlatform", ".", "prototype", "[", "key", "]", ";", "}", "}", "instance", ".", "_sdk", "=", "new", "AndroidSDK", "(", "instance", ".", "application", ")", ";", "instance", ".", "_channel", "=", "\"stable\"", ";", "instance", ".", "_lite", "=", "false", ";", "instance", ".", "_shared", "=", "false", ";", "instance", ".", "_apiTarget", "=", "null", ";", "return", "instance", ";", "}" ]
Android project class. @extends PlatformBase @constructor @param {Function} PlatformBase Base class constructor {@link PlatformBase} @param {PlatformData} baseData Init data passed to the platform @throws {@link AndroidSDK~SDKNotFoundError} If the Android SDK was not found in the environment.
[ "Android", "project", "class", "." ]
2771b2fa4326c2453b41de393284de68a2fe7eac
https://github.com/crosswalk-project/crosswalk-app-tools/blob/2771b2fa4326c2453b41de393284de68a2fe7eac/android/lib/AndroidPlatform.js#L27-L49
21,339
crosswalk-project/crosswalk-app-tools
src/util/CrosswalkDir.js
CrosswalkDir
function CrosswalkDir(path) { this._path = path; this._root = "./"; var versionFilePath = Path.join(path, "VERSION"); if (ShellJS.test("-f", versionFilePath)) { this._version = Version.createFromFile(versionFilePath); } else { this._version = Version.createFromPath(path); } if (!this._version) { throw new Error("Failed to determine crosswalk version"); } }
javascript
function CrosswalkDir(path) { this._path = path; this._root = "./"; var versionFilePath = Path.join(path, "VERSION"); if (ShellJS.test("-f", versionFilePath)) { this._version = Version.createFromFile(versionFilePath); } else { this._version = Version.createFromPath(path); } if (!this._version) { throw new Error("Failed to determine crosswalk version"); } }
[ "function", "CrosswalkDir", "(", "path", ")", "{", "this", ".", "_path", "=", "path", ";", "this", ".", "_root", "=", "\"./\"", ";", "var", "versionFilePath", "=", "Path", ".", "join", "(", "path", ",", "\"VERSION\"", ")", ";", "if", "(", "ShellJS", ".", "test", "(", "\"-f\"", ",", "versionFilePath", ")", ")", "{", "this", ".", "_version", "=", "Version", ".", "createFromFile", "(", "versionFilePath", ")", ";", "}", "else", "{", "this", ".", "_version", "=", "Version", ".", "createFromPath", "(", "path", ")", ";", "}", "if", "(", "!", "this", ".", "_version", ")", "{", "throw", "new", "Error", "(", "\"Failed to determine crosswalk version\"", ")", ";", "}", "}" ]
Creates a CrosswalkDir object. @param {String} path Path to crosswalk build xwalk_app_template @constructor
[ "Creates", "a", "CrosswalkDir", "object", "." ]
2771b2fa4326c2453b41de393284de68a2fe7eac
https://github.com/crosswalk-project/crosswalk-app-tools/blob/2771b2fa4326c2453b41de393284de68a2fe7eac/src/util/CrosswalkDir.js#L59-L74
21,340
crosswalk-project/crosswalk-app-tools
src/util/Download01Org.js
Download01Org
function Download01Org(application, platform, channel) { this._application = application; if (Download01Org.PLATFORMS.indexOf(platform) == -1) { throw new Error("Unknown platform " + platform); } this._platform = platform; if (Download01Org.CHANNELS.indexOf(channel) == -1) { throw new Error("Unknown channel " + channel); } this._channel = channel; this._flavor = "crosswalk"; this._androidWordSize = "32"; }
javascript
function Download01Org(application, platform, channel) { this._application = application; if (Download01Org.PLATFORMS.indexOf(platform) == -1) { throw new Error("Unknown platform " + platform); } this._platform = platform; if (Download01Org.CHANNELS.indexOf(channel) == -1) { throw new Error("Unknown channel " + channel); } this._channel = channel; this._flavor = "crosswalk"; this._androidWordSize = "32"; }
[ "function", "Download01Org", "(", "application", ",", "platform", ",", "channel", ")", "{", "this", ".", "_application", "=", "application", ";", "if", "(", "Download01Org", ".", "PLATFORMS", ".", "indexOf", "(", "platform", ")", "==", "-", "1", ")", "{", "throw", "new", "Error", "(", "\"Unknown platform \"", "+", "platform", ")", ";", "}", "this", ".", "_platform", "=", "platform", ";", "if", "(", "Download01Org", ".", "CHANNELS", ".", "indexOf", "(", "channel", ")", "==", "-", "1", ")", "{", "throw", "new", "Error", "(", "\"Unknown channel \"", "+", "channel", ")", ";", "}", "this", ".", "_channel", "=", "channel", ";", "this", ".", "_flavor", "=", "\"crosswalk\"", ";", "this", ".", "_androidWordSize", "=", "\"32\"", ";", "}" ]
Crosswalk release lookup and download. @constructor @param {Application} application application instance @param {String} platform Crosswalk release platform android/windows @param {String} channel Crosswalk channel beta/canary/stable @throws {Error} If no valid channel was specified.
[ "Crosswalk", "release", "lookup", "and", "download", "." ]
2771b2fa4326c2453b41de393284de68a2fe7eac
https://github.com/crosswalk-project/crosswalk-app-tools/blob/2771b2fa4326c2453b41de393284de68a2fe7eac/src/util/Download01Org.js#L43-L60
21,341
crosswalk-project/crosswalk-app-tools
src/LogfileOutput.js
LogfileOutput
function LogfileOutput(path) { this._path = path; var options = { flags: "w", mode: 0600 }; FS.writeFileSync(this._path, ""); /* TODO if (!this._fp) { throw new FileCreationFailed("Could not open file " + path); } */ }
javascript
function LogfileOutput(path) { this._path = path; var options = { flags: "w", mode: 0600 }; FS.writeFileSync(this._path, ""); /* TODO if (!this._fp) { throw new FileCreationFailed("Could not open file " + path); } */ }
[ "function", "LogfileOutput", "(", "path", ")", "{", "this", ".", "_path", "=", "path", ";", "var", "options", "=", "{", "flags", ":", "\"w\"", ",", "mode", ":", "0600", "}", ";", "FS", ".", "writeFileSync", "(", "this", ".", "_path", ",", "\"\"", ")", ";", "/* TODO\n if (!this._fp) {\n throw new FileCreationFailed(\"Could not open file \" + path);\n }\n*/", "}" ]
Creates an output writing to a file. @extends OutputIface @constructor @param {String} path Path to logfile. Existing content will be overwritten. @throws {exceptions.FileCreationFailed} If file at path could not be opened for writing.
[ "Creates", "an", "output", "writing", "to", "a", "file", "." ]
2771b2fa4326c2453b41de393284de68a2fe7eac
https://github.com/crosswalk-project/crosswalk-app-tools/blob/2771b2fa4326c2453b41de393284de68a2fe7eac/src/LogfileOutput.js#L19-L35
21,342
crosswalk-project/crosswalk-app-tools
src/PlatformInfo.js
PlatformInfo
function PlatformInfo(PlatformCtor, platformId) { this._Ctor = PlatformCtor; this._platformId = platformId; // Prefix all platform-specific args with the platform name var argSpec = PlatformCtor.getArgs ? PlatformCtor.getArgs() : {}; this._argSpec = {}; for (var cmd in argSpec) { var cmdArgSpec = argSpec[cmd]; var platformCmdArgSpec = {}; for (var key in cmdArgSpec) { platformCmdArgSpec["--" + platformId + "-" + key] = cmdArgSpec[key]; } this._argSpec[cmd] = platformCmdArgSpec; } // Look for platforms env vars this._envSpec = PlatformCtor.getEnv ? PlatformCtor.getEnv() : {}; }
javascript
function PlatformInfo(PlatformCtor, platformId) { this._Ctor = PlatformCtor; this._platformId = platformId; // Prefix all platform-specific args with the platform name var argSpec = PlatformCtor.getArgs ? PlatformCtor.getArgs() : {}; this._argSpec = {}; for (var cmd in argSpec) { var cmdArgSpec = argSpec[cmd]; var platformCmdArgSpec = {}; for (var key in cmdArgSpec) { platformCmdArgSpec["--" + platformId + "-" + key] = cmdArgSpec[key]; } this._argSpec[cmd] = platformCmdArgSpec; } // Look for platforms env vars this._envSpec = PlatformCtor.getEnv ? PlatformCtor.getEnv() : {}; }
[ "function", "PlatformInfo", "(", "PlatformCtor", ",", "platformId", ")", "{", "this", ".", "_Ctor", "=", "PlatformCtor", ";", "this", ".", "_platformId", "=", "platformId", ";", "// Prefix all platform-specific args with the platform name", "var", "argSpec", "=", "PlatformCtor", ".", "getArgs", "?", "PlatformCtor", ".", "getArgs", "(", ")", ":", "{", "}", ";", "this", ".", "_argSpec", "=", "{", "}", ";", "for", "(", "var", "cmd", "in", "argSpec", ")", "{", "var", "cmdArgSpec", "=", "argSpec", "[", "cmd", "]", ";", "var", "platformCmdArgSpec", "=", "{", "}", ";", "for", "(", "var", "key", "in", "cmdArgSpec", ")", "{", "platformCmdArgSpec", "[", "\"--\"", "+", "platformId", "+", "\"-\"", "+", "key", "]", "=", "cmdArgSpec", "[", "key", "]", ";", "}", "this", ".", "_argSpec", "[", "cmd", "]", "=", "platformCmdArgSpec", ";", "}", "// Look for platforms env vars", "this", ".", "_envSpec", "=", "PlatformCtor", ".", "getEnv", "?", "PlatformCtor", ".", "getEnv", "(", ")", ":", "{", "}", ";", "}" ]
Encapsulates static backend information, does not depend on an instance. @param {Function} PlatformCtor Constructor function for the platform @param {String} platformId Name for the platform, "android", "ios", ... @constructor
[ "Encapsulates", "static", "backend", "information", "does", "not", "depend", "on", "an", "instance", "." ]
2771b2fa4326c2453b41de393284de68a2fe7eac
https://github.com/crosswalk-project/crosswalk-app-tools/blob/2771b2fa4326c2453b41de393284de68a2fe7eac/src/PlatformInfo.js#L13-L32
21,343
crosswalk-project/crosswalk-app-tools
src/CommandParser.js
CommandParser
function CommandParser(output, argv) { this._output = output; if (!(argv instanceof Array)) { throw new TypeError("CommandParser(argv) must be of type Array."); } this._argv = argv; }
javascript
function CommandParser(output, argv) { this._output = output; if (!(argv instanceof Array)) { throw new TypeError("CommandParser(argv) must be of type Array."); } this._argv = argv; }
[ "function", "CommandParser", "(", "output", ",", "argv", ")", "{", "this", ".", "_output", "=", "output", ";", "if", "(", "!", "(", "argv", "instanceof", "Array", ")", ")", "{", "throw", "new", "TypeError", "(", "\"CommandParser(argv) must be of type Array.\"", ")", ";", "}", "this", ".", "_argv", "=", "argv", ";", "}" ]
Parsing and validation of command-line arguments. @constructor @param {OutputIface} output Output implementation @param {String[]} argv Command-line arguments @throws {TypeError} If argv is not an array.
[ "Parsing", "and", "validation", "of", "command", "-", "line", "arguments", "." ]
2771b2fa4326c2453b41de393284de68a2fe7eac
https://github.com/crosswalk-project/crosswalk-app-tools/blob/2771b2fa4326c2453b41de393284de68a2fe7eac/src/CommandParser.js#L17-L26
21,344
crosswalk-project/crosswalk-app-tools
android/lib/AndroidManifest.js
AndroidManifest
function AndroidManifest(output, path) { this._output = output; this._path = path; var doc = this.read(); this._package = doc.documentElement.getAttribute("package"); this._versionCode = doc.documentElement.getAttribute("android:versionCode"); this._versionName = doc.documentElement.getAttribute("android:versionName"); this._applicationIcon = null; var appNode = this.findApplicationNode(doc); if (appNode) { this._applicationIcon = appNode.getAttribute("android:icon"); } this._applicationLabel = null; appNode = this.findApplicationNode(doc); if (appNode) { this._applicationLabel = appNode.getAttribute("android:label"); } var activityNode = this.findChildNode(appNode, "activity"); if (activityNode) { this._screenOrientation = activityNode.getAttribute("android:screenOrientation"); } // TODO read other values from manifest and initialize members }
javascript
function AndroidManifest(output, path) { this._output = output; this._path = path; var doc = this.read(); this._package = doc.documentElement.getAttribute("package"); this._versionCode = doc.documentElement.getAttribute("android:versionCode"); this._versionName = doc.documentElement.getAttribute("android:versionName"); this._applicationIcon = null; var appNode = this.findApplicationNode(doc); if (appNode) { this._applicationIcon = appNode.getAttribute("android:icon"); } this._applicationLabel = null; appNode = this.findApplicationNode(doc); if (appNode) { this._applicationLabel = appNode.getAttribute("android:label"); } var activityNode = this.findChildNode(appNode, "activity"); if (activityNode) { this._screenOrientation = activityNode.getAttribute("android:screenOrientation"); } // TODO read other values from manifest and initialize members }
[ "function", "AndroidManifest", "(", "output", ",", "path", ")", "{", "this", ".", "_output", "=", "output", ";", "this", ".", "_path", "=", "path", ";", "var", "doc", "=", "this", ".", "read", "(", ")", ";", "this", ".", "_package", "=", "doc", ".", "documentElement", ".", "getAttribute", "(", "\"package\"", ")", ";", "this", ".", "_versionCode", "=", "doc", ".", "documentElement", ".", "getAttribute", "(", "\"android:versionCode\"", ")", ";", "this", ".", "_versionName", "=", "doc", ".", "documentElement", ".", "getAttribute", "(", "\"android:versionName\"", ")", ";", "this", ".", "_applicationIcon", "=", "null", ";", "var", "appNode", "=", "this", ".", "findApplicationNode", "(", "doc", ")", ";", "if", "(", "appNode", ")", "{", "this", ".", "_applicationIcon", "=", "appNode", ".", "getAttribute", "(", "\"android:icon\"", ")", ";", "}", "this", ".", "_applicationLabel", "=", "null", ";", "appNode", "=", "this", ".", "findApplicationNode", "(", "doc", ")", ";", "if", "(", "appNode", ")", "{", "this", ".", "_applicationLabel", "=", "appNode", ".", "getAttribute", "(", "\"android:label\"", ")", ";", "}", "var", "activityNode", "=", "this", ".", "findChildNode", "(", "appNode", ",", "\"activity\"", ")", ";", "if", "(", "activityNode", ")", "{", "this", ".", "_screenOrientation", "=", "activityNode", ".", "getAttribute", "(", "\"android:screenOrientation\"", ")", ";", "}", "// TODO read other values from manifest and initialize members", "}" ]
AndroidManifest wrapper. @param {OutputIface} output Output implementation @param {String} path Path to manifest.json @constructor
[ "AndroidManifest", "wrapper", "." ]
2771b2fa4326c2453b41de393284de68a2fe7eac
https://github.com/crosswalk-project/crosswalk-app-tools/blob/2771b2fa4326c2453b41de393284de68a2fe7eac/android/lib/AndroidManifest.js#L15-L43
21,345
crosswalk-project/crosswalk-app-tools
windows/lib/WixSDK.js
WixSDK
function WixSDK(rootPath, manifest, output) { this._rootPath = rootPath; this._manifest = manifest; this._output = output; this._existing_ids = {}; }
javascript
function WixSDK(rootPath, manifest, output) { this._rootPath = rootPath; this._manifest = manifest; this._output = output; this._existing_ids = {}; }
[ "function", "WixSDK", "(", "rootPath", ",", "manifest", ",", "output", ")", "{", "this", ".", "_rootPath", "=", "rootPath", ";", "this", ".", "_manifest", "=", "manifest", ";", "this", ".", "_output", "=", "output", ";", "this", ".", "_existing_ids", "=", "{", "}", ";", "}" ]
Creates WixSDK object. @param {String} rootPath Root path for project @param {Manifest} manifest Web manifest @param {OutputIface} output Output @constructor
[ "Creates", "WixSDK", "object", "." ]
2771b2fa4326c2453b41de393284de68a2fe7eac
https://github.com/crosswalk-project/crosswalk-app-tools/blob/2771b2fa4326c2453b41de393284de68a2fe7eac/windows/lib/WixSDK.js#L20-L27
21,346
crosswalk-project/crosswalk-app-tools
windows/lib/WixSDK.js
installExtensionDlls
function installExtensionDlls(source_dir_path, dest_folder_object) { var app_files = readDir.readSync(source_dir_path); app_files.forEach(function (name) { var suffix = name.substring(name.length - ".dll".length); if (suffix && suffix.toLowerCase() === ".dll") { AddFileComponent(dest_folder_object, source_dir_path, name); } }); }
javascript
function installExtensionDlls(source_dir_path, dest_folder_object) { var app_files = readDir.readSync(source_dir_path); app_files.forEach(function (name) { var suffix = name.substring(name.length - ".dll".length); if (suffix && suffix.toLowerCase() === ".dll") { AddFileComponent(dest_folder_object, source_dir_path, name); } }); }
[ "function", "installExtensionDlls", "(", "source_dir_path", ",", "dest_folder_object", ")", "{", "var", "app_files", "=", "readDir", ".", "readSync", "(", "source_dir_path", ")", ";", "app_files", ".", "forEach", "(", "function", "(", "name", ")", "{", "var", "suffix", "=", "name", ".", "substring", "(", "name", ".", "length", "-", "\".dll\"", ".", "length", ")", ";", "if", "(", "suffix", "&&", "suffix", ".", "toLowerCase", "(", ")", "===", "\".dll\"", ")", "{", "AddFileComponent", "(", "dest_folder_object", ",", "source_dir_path", ",", "name", ")", ";", "}", "}", ")", ";", "}" ]
Install all files with suffix .dll from @source_dir_path
[ "Install", "all", "files", "with", "suffix", ".", "dll", "from" ]
2771b2fa4326c2453b41de393284de68a2fe7eac
https://github.com/crosswalk-project/crosswalk-app-tools/blob/2771b2fa4326c2453b41de393284de68a2fe7eac/windows/lib/WixSDK.js#L259-L267
21,347
raml-org/ramldt2jsonschema
src/utils.js
updateObjWith
function updateObjWith (obj, upd) { for (const key in upd) { obj[key] = upd[key] } return obj }
javascript
function updateObjWith (obj, upd) { for (const key in upd) { obj[key] = upd[key] } return obj }
[ "function", "updateObjWith", "(", "obj", ",", "upd", ")", "{", "for", "(", "const", "key", "in", "upd", ")", "{", "obj", "[", "key", "]", "=", "upd", "[", "key", "]", "}", "return", "obj", "}" ]
Merge second object into first one. @param {Object} obj @param {Object} upd @returns {Object}
[ "Merge", "second", "object", "into", "first", "one", "." ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/utils.js#L10-L15
21,348
raml-org/ramldt2jsonschema
src/utils.js
inferRAMLTypeName
function inferRAMLTypeName (fileName) { const cleanName = fileName.replace(/^.*[\\/]/, '') const filename = cleanName.split('.')[0] return capitalize(filename) }
javascript
function inferRAMLTypeName (fileName) { const cleanName = fileName.replace(/^.*[\\/]/, '') const filename = cleanName.split('.')[0] return capitalize(filename) }
[ "function", "inferRAMLTypeName", "(", "fileName", ")", "{", "const", "cleanName", "=", "fileName", ".", "replace", "(", "/", "^.*[\\\\/]", "/", ",", "''", ")", "const", "filename", "=", "cleanName", ".", "split", "(", "'.'", ")", "[", "0", "]", "return", "capitalize", "(", "filename", ")", "}" ]
Infer RAML type name from file name @param {string} fileName - File in which type is located. @returns {string}
[ "Infer", "RAML", "type", "name", "from", "file", "name" ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/utils.js#L44-L48
21,349
raml-org/ramldt2jsonschema
src/dt2js_cli.js
dt2jsCLI
function dt2jsCLI (ramlFile, ramlTypeName) { const rootFileDir = ramlFile.split(path.sep).slice(0, -1).join(path.sep) const ramlData = fs.readFileSync(ramlFile).toString() dt2js.setBasePath(rootFileDir) return dt2js.dt2js(ramlData, ramlTypeName) }
javascript
function dt2jsCLI (ramlFile, ramlTypeName) { const rootFileDir = ramlFile.split(path.sep).slice(0, -1).join(path.sep) const ramlData = fs.readFileSync(ramlFile).toString() dt2js.setBasePath(rootFileDir) return dt2js.dt2js(ramlData, ramlTypeName) }
[ "function", "dt2jsCLI", "(", "ramlFile", ",", "ramlTypeName", ")", "{", "const", "rootFileDir", "=", "ramlFile", ".", "split", "(", "path", ".", "sep", ")", ".", "slice", "(", "0", ",", "-", "1", ")", ".", "join", "(", "path", ".", "sep", ")", "const", "ramlData", "=", "fs", ".", "readFileSync", "(", "ramlFile", ")", ".", "toString", "(", ")", "dt2js", ".", "setBasePath", "(", "rootFileDir", ")", "return", "dt2js", ".", "dt2js", "(", "ramlData", ",", "ramlTypeName", ")", "}" ]
Just call dt2js. @param {string} ramlFile @param {string} ramlTypeName
[ "Just", "call", "dt2js", "." ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/dt2js_cli.js#L13-L18
21,350
raml-org/ramldt2jsonschema
src/js2dt_cli.js
js2dtCLI
function js2dtCLI (jsonFile, ramlTypeName) { const jsonData = fs.readFileSync(jsonFile).toString() if (ramlTypeName != null) { const raml = js2dt.js2dt(jsonData, ramlTypeName) return `#%RAML 1.0 Library\n${yaml.safeDump({ types: raml }, { 'noRefs': true })}` } else { const typeName = 'this__should__be__the__only__type' const raml = js2dt.js2dt(jsonData, typeName) const keys = Object.keys(raml) if (keys.length !== 1 || !keys.includes(typeName)) { throw new Error(`There is more than one type (${JSON.stringify(keys)}), please specify a name for the raml library`) } return `#%RAML 1.0 DataType\n${yaml.safeDump(raml[typeName], { 'noRefs': true })}` } }
javascript
function js2dtCLI (jsonFile, ramlTypeName) { const jsonData = fs.readFileSync(jsonFile).toString() if (ramlTypeName != null) { const raml = js2dt.js2dt(jsonData, ramlTypeName) return `#%RAML 1.0 Library\n${yaml.safeDump({ types: raml }, { 'noRefs': true })}` } else { const typeName = 'this__should__be__the__only__type' const raml = js2dt.js2dt(jsonData, typeName) const keys = Object.keys(raml) if (keys.length !== 1 || !keys.includes(typeName)) { throw new Error(`There is more than one type (${JSON.stringify(keys)}), please specify a name for the raml library`) } return `#%RAML 1.0 DataType\n${yaml.safeDump(raml[typeName], { 'noRefs': true })}` } }
[ "function", "js2dtCLI", "(", "jsonFile", ",", "ramlTypeName", ")", "{", "const", "jsonData", "=", "fs", ".", "readFileSync", "(", "jsonFile", ")", ".", "toString", "(", ")", "if", "(", "ramlTypeName", "!=", "null", ")", "{", "const", "raml", "=", "js2dt", ".", "js2dt", "(", "jsonData", ",", "ramlTypeName", ")", "return", "`", "\\n", "${", "yaml", ".", "safeDump", "(", "{", "types", ":", "raml", "}", ",", "{", "'noRefs'", ":", "true", "}", ")", "}", "`", "}", "else", "{", "const", "typeName", "=", "'this__should__be__the__only__type'", "const", "raml", "=", "js2dt", ".", "js2dt", "(", "jsonData", ",", "typeName", ")", "const", "keys", "=", "Object", ".", "keys", "(", "raml", ")", "if", "(", "keys", ".", "length", "!==", "1", "||", "!", "keys", ".", "includes", "(", "typeName", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "JSON", ".", "stringify", "(", "keys", ")", "}", "`", ")", "}", "return", "`", "\\n", "${", "yaml", ".", "safeDump", "(", "raml", "[", "typeName", "]", ",", "{", "'noRefs'", ":", "true", "}", ")", "}", "`", "}", "}" ]
Just call js2dt. @param {string} jsonFile @param {string} ramlTypeName
[ "Just", "call", "js2dt", "." ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/js2dt_cli.js#L13-L30
21,351
raml-org/ramldt2jsonschema
src/dt2js.js
getRAMLContext
function getRAMLContext (ramlData, rootFileDir) { rootFileDir = rootFileDir || '.' const ast = yap.load(ramlData) const libraries = extractLibraries(ast, rootFileDir) const jsContent = {} traverse(jsContent, ast, rootFileDir, libraries) return jsContent.types }
javascript
function getRAMLContext (ramlData, rootFileDir) { rootFileDir = rootFileDir || '.' const ast = yap.load(ramlData) const libraries = extractLibraries(ast, rootFileDir) const jsContent = {} traverse(jsContent, ast, rootFileDir, libraries) return jsContent.types }
[ "function", "getRAMLContext", "(", "ramlData", ",", "rootFileDir", ")", "{", "rootFileDir", "=", "rootFileDir", "||", "'.'", "const", "ast", "=", "yap", ".", "load", "(", "ramlData", ")", "const", "libraries", "=", "extractLibraries", "(", "ast", ",", "rootFileDir", ")", "const", "jsContent", "=", "{", "}", "traverse", "(", "jsContent", ",", "ast", ",", "rootFileDir", ",", "libraries", ")", "return", "jsContent", ".", "types", "}" ]
Get RAML Data Types context. @param {string} ramlData - RAML file content. @param {string} rootFileDir - RAML file directory. @returns {Object} - RAML data types context.
[ "Get", "RAML", "Data", "Types", "context", "." ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/dt2js.js#L22-L29
21,352
raml-org/ramldt2jsonschema
src/dt2js.js
destringify
function destringify (val) { if (!isNaN(Number(val))) return Number(val) if (val === 'true') return true if (val === 'false') return false return val }
javascript
function destringify (val) { if (!isNaN(Number(val))) return Number(val) if (val === 'true') return true if (val === 'false') return false return val }
[ "function", "destringify", "(", "val", ")", "{", "if", "(", "!", "isNaN", "(", "Number", "(", "val", ")", ")", ")", "return", "Number", "(", "val", ")", "if", "(", "val", "===", "'true'", ")", "return", "true", "if", "(", "val", "===", "'false'", ")", "return", "false", "return", "val", "}" ]
restore ints and booleans stored as strings @param {String} val - the value to be tested and possibly converted @returns {Mixed} - either a string, int or boolean.
[ "restore", "ints", "and", "booleans", "stored", "as", "strings" ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/dt2js.js#L37-L42
21,353
raml-org/ramldt2jsonschema
src/dt2js.js
traverse
function traverse (obj, ast, rootFileDir, libraries) { function recurse (keys, currentNode, nodeFileDir) { if (currentNode.key) { keys = keys.concat([currentNode.key.value]) } // kind 5 is an include if (currentNode.value && currentNode.value.kind === 5) { const location = currentNode.value.value const [include, contentType, newNodeFileDir] = resolveInclude(rootFileDir, nodeFileDir, location) // If it's json, parse it const ramlContentTypes = [ 'application/raml+yaml', 'text/yaml', 'text/x-yaml', 'application/yaml', 'application/x-yaml' ] if (path.extname(location) === '.json' || contentType === 'application/json') { deep(obj, keys.join('.'), JSON.parse(include)) // If it's raml or yaml, parse it as raml } else if (['.raml', '.yaml', '.yml'].indexOf(path.extname(location)) > -1 || ramlContentTypes.indexOf(contentType) > -1) { currentNode.value = yap.load(include) if (currentNode.value.errors.length > 0) { throw new Error('Invalid RAML data in one of the included files') } recurse(keys, currentNode.value, newNodeFileDir) // If it's anything else, just add it as a string. } else { currentNode.value = include } // a leaf node to be added } else if (currentNode.value && currentNode.value.value) { let val = !currentNode.value.doubleQuoted // convert back from string type ? destringify(currentNode.value.value) : currentNode.value.value val = libraryOrValue(libraries, val) deep(obj, keys.join('.'), val) // a leaf that is an array } else if (currentNode.value && currentNode.value.items) { const values = currentNode.value.items.map(function (el) { return el.value }) deep(obj, keys.join('.'), values) // an object that needs further traversal } else if (currentNode.mappings) { for (let i = 0; i < currentNode.mappings.length; i++) { recurse(keys, currentNode.mappings[i], nodeFileDir) } } else if (currentNode.key && currentNode.key.value === 'examples') { const vals = currentNode.value.mappings.map(function (el) { return el.value.value }) deep(obj, keys.join('.'), vals) // an object that needs further traversal } else if (currentNode.value && currentNode.value.mappings) { for (let o = 0; o < currentNode.value.mappings.length; o++) { recurse(keys, currentNode.value.mappings[o], nodeFileDir) } } } recurse([], ast, rootFileDir) }
javascript
function traverse (obj, ast, rootFileDir, libraries) { function recurse (keys, currentNode, nodeFileDir) { if (currentNode.key) { keys = keys.concat([currentNode.key.value]) } // kind 5 is an include if (currentNode.value && currentNode.value.kind === 5) { const location = currentNode.value.value const [include, contentType, newNodeFileDir] = resolveInclude(rootFileDir, nodeFileDir, location) // If it's json, parse it const ramlContentTypes = [ 'application/raml+yaml', 'text/yaml', 'text/x-yaml', 'application/yaml', 'application/x-yaml' ] if (path.extname(location) === '.json' || contentType === 'application/json') { deep(obj, keys.join('.'), JSON.parse(include)) // If it's raml or yaml, parse it as raml } else if (['.raml', '.yaml', '.yml'].indexOf(path.extname(location)) > -1 || ramlContentTypes.indexOf(contentType) > -1) { currentNode.value = yap.load(include) if (currentNode.value.errors.length > 0) { throw new Error('Invalid RAML data in one of the included files') } recurse(keys, currentNode.value, newNodeFileDir) // If it's anything else, just add it as a string. } else { currentNode.value = include } // a leaf node to be added } else if (currentNode.value && currentNode.value.value) { let val = !currentNode.value.doubleQuoted // convert back from string type ? destringify(currentNode.value.value) : currentNode.value.value val = libraryOrValue(libraries, val) deep(obj, keys.join('.'), val) // a leaf that is an array } else if (currentNode.value && currentNode.value.items) { const values = currentNode.value.items.map(function (el) { return el.value }) deep(obj, keys.join('.'), values) // an object that needs further traversal } else if (currentNode.mappings) { for (let i = 0; i < currentNode.mappings.length; i++) { recurse(keys, currentNode.mappings[i], nodeFileDir) } } else if (currentNode.key && currentNode.key.value === 'examples') { const vals = currentNode.value.mappings.map(function (el) { return el.value.value }) deep(obj, keys.join('.'), vals) // an object that needs further traversal } else if (currentNode.value && currentNode.value.mappings) { for (let o = 0; o < currentNode.value.mappings.length; o++) { recurse(keys, currentNode.value.mappings[o], nodeFileDir) } } } recurse([], ast, rootFileDir) }
[ "function", "traverse", "(", "obj", ",", "ast", ",", "rootFileDir", ",", "libraries", ")", "{", "function", "recurse", "(", "keys", ",", "currentNode", ",", "nodeFileDir", ")", "{", "if", "(", "currentNode", ".", "key", ")", "{", "keys", "=", "keys", ".", "concat", "(", "[", "currentNode", ".", "key", ".", "value", "]", ")", "}", "// kind 5 is an include", "if", "(", "currentNode", ".", "value", "&&", "currentNode", ".", "value", ".", "kind", "===", "5", ")", "{", "const", "location", "=", "currentNode", ".", "value", ".", "value", "const", "[", "include", ",", "contentType", ",", "newNodeFileDir", "]", "=", "resolveInclude", "(", "rootFileDir", ",", "nodeFileDir", ",", "location", ")", "// If it's json, parse it", "const", "ramlContentTypes", "=", "[", "'application/raml+yaml'", ",", "'text/yaml'", ",", "'text/x-yaml'", ",", "'application/yaml'", ",", "'application/x-yaml'", "]", "if", "(", "path", ".", "extname", "(", "location", ")", "===", "'.json'", "||", "contentType", "===", "'application/json'", ")", "{", "deep", "(", "obj", ",", "keys", ".", "join", "(", "'.'", ")", ",", "JSON", ".", "parse", "(", "include", ")", ")", "// If it's raml or yaml, parse it as raml", "}", "else", "if", "(", "[", "'.raml'", ",", "'.yaml'", ",", "'.yml'", "]", ".", "indexOf", "(", "path", ".", "extname", "(", "location", ")", ")", ">", "-", "1", "||", "ramlContentTypes", ".", "indexOf", "(", "contentType", ")", ">", "-", "1", ")", "{", "currentNode", ".", "value", "=", "yap", ".", "load", "(", "include", ")", "if", "(", "currentNode", ".", "value", ".", "errors", ".", "length", ">", "0", ")", "{", "throw", "new", "Error", "(", "'Invalid RAML data in one of the included files'", ")", "}", "recurse", "(", "keys", ",", "currentNode", ".", "value", ",", "newNodeFileDir", ")", "// If it's anything else, just add it as a string.", "}", "else", "{", "currentNode", ".", "value", "=", "include", "}", "// a leaf node to be added", "}", "else", "if", "(", "currentNode", ".", "value", "&&", "currentNode", ".", "value", ".", "value", ")", "{", "let", "val", "=", "!", "currentNode", ".", "value", ".", "doubleQuoted", "// convert back from string type", "?", "destringify", "(", "currentNode", ".", "value", ".", "value", ")", ":", "currentNode", ".", "value", ".", "value", "val", "=", "libraryOrValue", "(", "libraries", ",", "val", ")", "deep", "(", "obj", ",", "keys", ".", "join", "(", "'.'", ")", ",", "val", ")", "// a leaf that is an array", "}", "else", "if", "(", "currentNode", ".", "value", "&&", "currentNode", ".", "value", ".", "items", ")", "{", "const", "values", "=", "currentNode", ".", "value", ".", "items", ".", "map", "(", "function", "(", "el", ")", "{", "return", "el", ".", "value", "}", ")", "deep", "(", "obj", ",", "keys", ".", "join", "(", "'.'", ")", ",", "values", ")", "// an object that needs further traversal", "}", "else", "if", "(", "currentNode", ".", "mappings", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "currentNode", ".", "mappings", ".", "length", ";", "i", "++", ")", "{", "recurse", "(", "keys", ",", "currentNode", ".", "mappings", "[", "i", "]", ",", "nodeFileDir", ")", "}", "}", "else", "if", "(", "currentNode", ".", "key", "&&", "currentNode", ".", "key", ".", "value", "===", "'examples'", ")", "{", "const", "vals", "=", "currentNode", ".", "value", ".", "mappings", ".", "map", "(", "function", "(", "el", ")", "{", "return", "el", ".", "value", ".", "value", "}", ")", "deep", "(", "obj", ",", "keys", ".", "join", "(", "'.'", ")", ",", "vals", ")", "// an object that needs further traversal", "}", "else", "if", "(", "currentNode", ".", "value", "&&", "currentNode", ".", "value", ".", "mappings", ")", "{", "for", "(", "let", "o", "=", "0", ";", "o", "<", "currentNode", ".", "value", ".", "mappings", ".", "length", ";", "o", "++", ")", "{", "recurse", "(", "keys", ",", "currentNode", ".", "value", ".", "mappings", "[", "o", "]", ",", "nodeFileDir", ")", "}", "}", "}", "recurse", "(", "[", "]", ",", "ast", ",", "rootFileDir", ")", "}" ]
traverses AST generated by yaml-ast-parser and create json object.. @param {Object} obj - The object to hold the parsed raml @param {Object} ast - The ast from yaml-ast-parser @param {String} rootFileDir - a directory to be used as cwd while resolving includes @param {Object} libraries - an object holding libraries to be used @returns {Object} - js object representing raml
[ "traverses", "AST", "generated", "by", "yaml", "-", "ast", "-", "parser", "and", "create", "json", "object", ".." ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/dt2js.js#L127-L187
21,354
raml-org/ramldt2jsonschema
src/dt2js.js
dt2js
function dt2js (ramlData, typeName) { const ctx = getRAMLContext(ramlData, basePath) if (!(ctx instanceof Object)) throw new Error('Invalid RAML data') if (ctx[typeName] === undefined) throw new Error('type ' + typeName + ' does not exist') const expanded = expandedForm(ctx[typeName], ctx) const canonical = canonicalForm(expanded) let schema = schemaForm(canonical) schema = addRootKeywords(schema) return schema }
javascript
function dt2js (ramlData, typeName) { const ctx = getRAMLContext(ramlData, basePath) if (!(ctx instanceof Object)) throw new Error('Invalid RAML data') if (ctx[typeName] === undefined) throw new Error('type ' + typeName + ' does not exist') const expanded = expandedForm(ctx[typeName], ctx) const canonical = canonicalForm(expanded) let schema = schemaForm(canonical) schema = addRootKeywords(schema) return schema }
[ "function", "dt2js", "(", "ramlData", ",", "typeName", ")", "{", "const", "ctx", "=", "getRAMLContext", "(", "ramlData", ",", "basePath", ")", "if", "(", "!", "(", "ctx", "instanceof", "Object", ")", ")", "throw", "new", "Error", "(", "'Invalid RAML data'", ")", "if", "(", "ctx", "[", "typeName", "]", "===", "undefined", ")", "throw", "new", "Error", "(", "'type '", "+", "typeName", "+", "' does not exist'", ")", "const", "expanded", "=", "expandedForm", "(", "ctx", "[", "typeName", "]", ",", "ctx", ")", "const", "canonical", "=", "canonicalForm", "(", "expanded", ")", "let", "schema", "=", "schemaForm", "(", "canonical", ")", "schema", "=", "addRootKeywords", "(", "schema", ")", "return", "schema", "}" ]
Convert RAML data type to JSON schema. @param {string} ramlData - RAML file content. @param {string} typeName - Name of the type to be converted.
[ "Convert", "RAML", "data", "type", "to", "JSON", "schema", "." ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/dt2js.js#L212-L225
21,355
raml-org/ramldt2jsonschema
src/dt2js.js
processArray
function processArray (arr, reqStack) { const accum = [] arr.forEach(function (el) { accum.push(schemaForm(el, reqStack)) }) return accum }
javascript
function processArray (arr, reqStack) { const accum = [] arr.forEach(function (el) { accum.push(schemaForm(el, reqStack)) }) return accum }
[ "function", "processArray", "(", "arr", ",", "reqStack", ")", "{", "const", "accum", "=", "[", "]", "arr", ".", "forEach", "(", "function", "(", "el", ")", "{", "accum", ".", "push", "(", "schemaForm", "(", "el", ",", "reqStack", ")", ")", "}", ")", "return", "accum", "}" ]
Call `schemaForm` for each element of array. @param {Array} arr @param {Array} reqStack - Stack of required properties. @returns {Array}
[ "Call", "schemaForm", "for", "each", "element", "of", "array", "." ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/dt2js.js#L245-L251
21,356
raml-org/ramldt2jsonschema
src/dt2js.js
convertType
function convertType (data) { switch (data.type) { case 'union': // If union of arrays if (Array.isArray(data.anyOf) && data.anyOf[0].type === 'array') { const items = data.anyOf.map(function (e) { return e.items }) data.items = { anyOf: [] } data.items.anyOf = items data['type'] = 'array' delete data.anyOf } else { data['type'] = 'object' } break case 'nil': data['type'] = 'null' break case 'file': data = convertFileType(data) break } return data }
javascript
function convertType (data) { switch (data.type) { case 'union': // If union of arrays if (Array.isArray(data.anyOf) && data.anyOf[0].type === 'array') { const items = data.anyOf.map(function (e) { return e.items }) data.items = { anyOf: [] } data.items.anyOf = items data['type'] = 'array' delete data.anyOf } else { data['type'] = 'object' } break case 'nil': data['type'] = 'null' break case 'file': data = convertFileType(data) break } return data }
[ "function", "convertType", "(", "data", ")", "{", "switch", "(", "data", ".", "type", ")", "{", "case", "'union'", ":", "// If union of arrays", "if", "(", "Array", ".", "isArray", "(", "data", ".", "anyOf", ")", "&&", "data", ".", "anyOf", "[", "0", "]", ".", "type", "===", "'array'", ")", "{", "const", "items", "=", "data", ".", "anyOf", ".", "map", "(", "function", "(", "e", ")", "{", "return", "e", ".", "items", "}", ")", "data", ".", "items", "=", "{", "anyOf", ":", "[", "]", "}", "data", ".", "items", ".", "anyOf", "=", "items", "data", "[", "'type'", "]", "=", "'array'", "delete", "data", ".", "anyOf", "}", "else", "{", "data", "[", "'type'", "]", "=", "'object'", "}", "break", "case", "'nil'", ":", "data", "[", "'type'", "]", "=", "'null'", "break", "case", "'file'", ":", "data", "=", "convertFileType", "(", "data", ")", "break", "}", "return", "data", "}" ]
Change RAML type of data to valid JSON schema type. @param {Object} data @returns {Object}
[ "Change", "RAML", "type", "of", "data", "to", "valid", "JSON", "schema", "type", "." ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/dt2js.js#L259-L281
21,357
raml-org/ramldt2jsonschema
src/dt2js.js
convertFileType
function convertFileType (data) { data['type'] = 'string' data['media'] = { 'binaryEncoding': 'binary' } if (data.fileTypes) { data['media']['anyOf'] = [] data.fileTypes.forEach(function (el) { data['media']['anyOf'].push({ 'mediaType': el }) }) delete data.fileTypes } return data }
javascript
function convertFileType (data) { data['type'] = 'string' data['media'] = { 'binaryEncoding': 'binary' } if (data.fileTypes) { data['media']['anyOf'] = [] data.fileTypes.forEach(function (el) { data['media']['anyOf'].push({ 'mediaType': el }) }) delete data.fileTypes } return data }
[ "function", "convertFileType", "(", "data", ")", "{", "data", "[", "'type'", "]", "=", "'string'", "data", "[", "'media'", "]", "=", "{", "'binaryEncoding'", ":", "'binary'", "}", "if", "(", "data", ".", "fileTypes", ")", "{", "data", "[", "'media'", "]", "[", "'anyOf'", "]", "=", "[", "]", "data", ".", "fileTypes", ".", "forEach", "(", "function", "(", "el", ")", "{", "data", "[", "'media'", "]", "[", "'anyOf'", "]", ".", "push", "(", "{", "'mediaType'", ":", "el", "}", ")", "}", ")", "delete", "data", ".", "fileTypes", "}", "return", "data", "}" ]
Change RAML `file` type to proper JSON type. @param {Object} data @returns {Object}
[ "Change", "RAML", "file", "type", "to", "proper", "JSON", "type", "." ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/dt2js.js#L289-L300
21,358
raml-org/ramldt2jsonschema
src/dt2js.js
convertDateType
function convertDateType (data) { switch (data.type) { case 'date-only': data['type'] = 'string' data['pattern'] = constants.dateOnlyPattern break case 'time-only': data['type'] = 'string' data['pattern'] = constants.timeOnlyPattern break case 'datetime-only': data['type'] = 'string' data['pattern'] = constants.dateTimeOnlyPattern break case 'datetime': data['type'] = 'string' if (data.format === undefined || data.format.toLowerCase() === constants.RFC3339) { data['pattern'] = constants.RFC3339DatetimePattern } else if (data.format.toLowerCase() === constants.RFC2616) { data['pattern'] = constants.RFC2616DatetimePattern } delete data.format break } return data }
javascript
function convertDateType (data) { switch (data.type) { case 'date-only': data['type'] = 'string' data['pattern'] = constants.dateOnlyPattern break case 'time-only': data['type'] = 'string' data['pattern'] = constants.timeOnlyPattern break case 'datetime-only': data['type'] = 'string' data['pattern'] = constants.dateTimeOnlyPattern break case 'datetime': data['type'] = 'string' if (data.format === undefined || data.format.toLowerCase() === constants.RFC3339) { data['pattern'] = constants.RFC3339DatetimePattern } else if (data.format.toLowerCase() === constants.RFC2616) { data['pattern'] = constants.RFC2616DatetimePattern } delete data.format break } return data }
[ "function", "convertDateType", "(", "data", ")", "{", "switch", "(", "data", ".", "type", ")", "{", "case", "'date-only'", ":", "data", "[", "'type'", "]", "=", "'string'", "data", "[", "'pattern'", "]", "=", "constants", ".", "dateOnlyPattern", "break", "case", "'time-only'", ":", "data", "[", "'type'", "]", "=", "'string'", "data", "[", "'pattern'", "]", "=", "constants", ".", "timeOnlyPattern", "break", "case", "'datetime-only'", ":", "data", "[", "'type'", "]", "=", "'string'", "data", "[", "'pattern'", "]", "=", "constants", ".", "dateTimeOnlyPattern", "break", "case", "'datetime'", ":", "data", "[", "'type'", "]", "=", "'string'", "if", "(", "data", ".", "format", "===", "undefined", "||", "data", ".", "format", ".", "toLowerCase", "(", ")", "===", "constants", ".", "RFC3339", ")", "{", "data", "[", "'pattern'", "]", "=", "constants", ".", "RFC3339DatetimePattern", "}", "else", "if", "(", "data", ".", "format", ".", "toLowerCase", "(", ")", "===", "constants", ".", "RFC2616", ")", "{", "data", "[", "'pattern'", "]", "=", "constants", ".", "RFC2616DatetimePattern", "}", "delete", "data", ".", "format", "break", "}", "return", "data", "}" ]
Change RAML date type of data to valid JSON schema type. @param {Object} data @returns {Object}
[ "Change", "RAML", "date", "type", "of", "data", "to", "valid", "JSON", "schema", "type", "." ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/dt2js.js#L308-L333
21,359
raml-org/ramldt2jsonschema
src/dt2js.js
convertPatternProperties
function convertPatternProperties (data) { Object.keys(data.properties).map(function (key) { if (/^\/.*\/$/.test(key)) { data.patternProperties = data.patternProperties || {} const stringRegex = key.slice(1, -1) data.patternProperties[stringRegex] = data.properties[key] delete data.properties[key] } }) return data }
javascript
function convertPatternProperties (data) { Object.keys(data.properties).map(function (key) { if (/^\/.*\/$/.test(key)) { data.patternProperties = data.patternProperties || {} const stringRegex = key.slice(1, -1) data.patternProperties[stringRegex] = data.properties[key] delete data.properties[key] } }) return data }
[ "function", "convertPatternProperties", "(", "data", ")", "{", "Object", ".", "keys", "(", "data", ".", "properties", ")", ".", "map", "(", "function", "(", "key", ")", "{", "if", "(", "/", "^\\/.*\\/$", "/", ".", "test", "(", "key", ")", ")", "{", "data", ".", "patternProperties", "=", "data", ".", "patternProperties", "||", "{", "}", "const", "stringRegex", "=", "key", ".", "slice", "(", "1", ",", "-", "1", ")", "data", ".", "patternProperties", "[", "stringRegex", "]", "=", "data", ".", "properties", "[", "key", "]", "delete", "data", ".", "properties", "[", "key", "]", "}", "}", ")", "return", "data", "}" ]
Change RAML pattern properties to JSON patternProperties. @param {Object} data - the library fragment to convert @returns {Object}
[ "Change", "RAML", "pattern", "properties", "to", "JSON", "patternProperties", "." ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/dt2js.js#L341-L351
21,360
raml-org/ramldt2jsonschema
src/dt2js.js
processNested
function processNested (data, reqStack) { const updateWith = {} for (const key in data) { const val = data[key] if (val instanceof Array) { updateWith[key] = processArray(val, reqStack) continue } if (val instanceof Object) { updateWith[key] = schemaForm(val, reqStack, key) continue } } return updateWith }
javascript
function processNested (data, reqStack) { const updateWith = {} for (const key in data) { const val = data[key] if (val instanceof Array) { updateWith[key] = processArray(val, reqStack) continue } if (val instanceof Object) { updateWith[key] = schemaForm(val, reqStack, key) continue } } return updateWith }
[ "function", "processNested", "(", "data", ",", "reqStack", ")", "{", "const", "updateWith", "=", "{", "}", "for", "(", "const", "key", "in", "data", ")", "{", "const", "val", "=", "data", "[", "key", "]", "if", "(", "val", "instanceof", "Array", ")", "{", "updateWith", "[", "key", "]", "=", "processArray", "(", "val", ",", "reqStack", ")", "continue", "}", "if", "(", "val", "instanceof", "Object", ")", "{", "updateWith", "[", "key", "]", "=", "schemaForm", "(", "val", ",", "reqStack", ",", "key", ")", "continue", "}", "}", "return", "updateWith", "}" ]
Call `schemaForm` for all nested objects. @param {Object} data @param {Array} reqStack - Stack of required properties. @returns {Object}
[ "Call", "schemaForm", "for", "all", "nested", "objects", "." ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/dt2js.js#L372-L388
21,361
raml-org/ramldt2jsonschema
src/dt2js.js
schemaForm
function schemaForm (data, reqStack = [], prop) { if (!(data instanceof Object)) { return data } const lastEl = reqStack[reqStack.length - 1] if (data.type && data.required !== false && lastEl && prop) { if (lastEl.props.indexOf(prop) > -1 && (prop[0] + prop[prop.length - 1]) !== '//') { lastEl.reqs.push(prop) } } delete data.required const isObj = data.type === 'object' if (isObj) { reqStack.push({ 'reqs': [], 'props': Object.keys(data.properties || {}) }) } const updateWith = processNested(data, reqStack) data = utils.updateObjWith(data, updateWith) if (isObj) { let reqs = reqStack.pop().reqs // Strip duplicates from reqs reqs = reqs.filter(function (value, index, self) { return self.indexOf(value) === index }) if (reqs.length > 0) { data.required = reqs } } if (data.type) { data = convertType(data) data = convertDateType(data) } if (data.displayName) { data = convertDisplayName(data) } if (data.properties) { convertPatternProperties(data) } return data }
javascript
function schemaForm (data, reqStack = [], prop) { if (!(data instanceof Object)) { return data } const lastEl = reqStack[reqStack.length - 1] if (data.type && data.required !== false && lastEl && prop) { if (lastEl.props.indexOf(prop) > -1 && (prop[0] + prop[prop.length - 1]) !== '//') { lastEl.reqs.push(prop) } } delete data.required const isObj = data.type === 'object' if (isObj) { reqStack.push({ 'reqs': [], 'props': Object.keys(data.properties || {}) }) } const updateWith = processNested(data, reqStack) data = utils.updateObjWith(data, updateWith) if (isObj) { let reqs = reqStack.pop().reqs // Strip duplicates from reqs reqs = reqs.filter(function (value, index, self) { return self.indexOf(value) === index }) if (reqs.length > 0) { data.required = reqs } } if (data.type) { data = convertType(data) data = convertDateType(data) } if (data.displayName) { data = convertDisplayName(data) } if (data.properties) { convertPatternProperties(data) } return data }
[ "function", "schemaForm", "(", "data", ",", "reqStack", "=", "[", "]", ",", "prop", ")", "{", "if", "(", "!", "(", "data", "instanceof", "Object", ")", ")", "{", "return", "data", "}", "const", "lastEl", "=", "reqStack", "[", "reqStack", ".", "length", "-", "1", "]", "if", "(", "data", ".", "type", "&&", "data", ".", "required", "!==", "false", "&&", "lastEl", "&&", "prop", ")", "{", "if", "(", "lastEl", ".", "props", ".", "indexOf", "(", "prop", ")", ">", "-", "1", "&&", "(", "prop", "[", "0", "]", "+", "prop", "[", "prop", ".", "length", "-", "1", "]", ")", "!==", "'//'", ")", "{", "lastEl", ".", "reqs", ".", "push", "(", "prop", ")", "}", "}", "delete", "data", ".", "required", "const", "isObj", "=", "data", ".", "type", "===", "'object'", "if", "(", "isObj", ")", "{", "reqStack", ".", "push", "(", "{", "'reqs'", ":", "[", "]", ",", "'props'", ":", "Object", ".", "keys", "(", "data", ".", "properties", "||", "{", "}", ")", "}", ")", "}", "const", "updateWith", "=", "processNested", "(", "data", ",", "reqStack", ")", "data", "=", "utils", ".", "updateObjWith", "(", "data", ",", "updateWith", ")", "if", "(", "isObj", ")", "{", "let", "reqs", "=", "reqStack", ".", "pop", "(", ")", ".", "reqs", "// Strip duplicates from reqs", "reqs", "=", "reqs", ".", "filter", "(", "function", "(", "value", ",", "index", ",", "self", ")", "{", "return", "self", ".", "indexOf", "(", "value", ")", "===", "index", "}", ")", "if", "(", "reqs", ".", "length", ">", "0", ")", "{", "data", ".", "required", "=", "reqs", "}", "}", "if", "(", "data", ".", "type", ")", "{", "data", "=", "convertType", "(", "data", ")", "data", "=", "convertDateType", "(", "data", ")", "}", "if", "(", "data", ".", "displayName", ")", "{", "data", "=", "convertDisplayName", "(", "data", ")", "}", "if", "(", "data", ".", "properties", ")", "{", "convertPatternProperties", "(", "data", ")", "}", "return", "data", "}" ]
Convert canonical form of RAML type to valid JSON schema. @param {Object} data - Data to be converted. @param {Array} reqStack - Stack of required properties. @param {string} [prop] - Property name nested objects of which are processed. @returns {Object}
[ "Convert", "canonical", "form", "of", "RAML", "type", "to", "valid", "JSON", "schema", "." ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/dt2js.js#L398-L442
21,362
raml-org/ramldt2jsonschema
src/js2dt.js
js2dt
function js2dt (jsonData, typeName) { const data = JSON.parse(jsonData) const raml = new RamlConverter(data, typeName).toRaml() return raml }
javascript
function js2dt (jsonData, typeName) { const data = JSON.parse(jsonData) const raml = new RamlConverter(data, typeName).toRaml() return raml }
[ "function", "js2dt", "(", "jsonData", ",", "typeName", ")", "{", "const", "data", "=", "JSON", ".", "parse", "(", "jsonData", ")", "const", "raml", "=", "new", "RamlConverter", "(", "data", ",", "typeName", ")", ".", "toRaml", "(", ")", "return", "raml", "}" ]
Convert JSON schema to RAML data type. @param {string} jsonData - JSON file content. @param {string} typeName - Name of RAML data type to hold converted data.
[ "Convert", "JSON", "schema", "to", "RAML", "data", "type", "." ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/js2dt.js#L27-L33
21,363
raml-org/ramldt2jsonschema
src/js2dt.js
convertAdditionalProperties
function convertAdditionalProperties (data, additionalProperties) { if (additionalProperties !== undefined) { let val = data if (typeof additionalProperties === 'boolean') val = additionalProperties if (typeof additionalProperties === 'object' && Object.keys(additionalProperties).length === 0) val = true if (typeof additionalProperties === 'object' && Object.keys(additionalProperties).length > 0) { const type = additionalProperties.type data.properties['//'] = { type: type } val = false } data.additionalProperties = val } return data }
javascript
function convertAdditionalProperties (data, additionalProperties) { if (additionalProperties !== undefined) { let val = data if (typeof additionalProperties === 'boolean') val = additionalProperties if (typeof additionalProperties === 'object' && Object.keys(additionalProperties).length === 0) val = true if (typeof additionalProperties === 'object' && Object.keys(additionalProperties).length > 0) { const type = additionalProperties.type data.properties['//'] = { type: type } val = false } data.additionalProperties = val } return data }
[ "function", "convertAdditionalProperties", "(", "data", ",", "additionalProperties", ")", "{", "if", "(", "additionalProperties", "!==", "undefined", ")", "{", "let", "val", "=", "data", "if", "(", "typeof", "additionalProperties", "===", "'boolean'", ")", "val", "=", "additionalProperties", "if", "(", "typeof", "additionalProperties", "===", "'object'", "&&", "Object", ".", "keys", "(", "additionalProperties", ")", ".", "length", "===", "0", ")", "val", "=", "true", "if", "(", "typeof", "additionalProperties", "===", "'object'", "&&", "Object", ".", "keys", "(", "additionalProperties", ")", ".", "length", ">", "0", ")", "{", "const", "type", "=", "additionalProperties", ".", "type", "data", ".", "properties", "[", "'//'", "]", "=", "{", "type", ":", "type", "}", "val", "=", "false", "}", "data", ".", "additionalProperties", "=", "val", "}", "return", "data", "}" ]
convert additionalProperties from jsonSchema to raml form @param {Object} data - current data @param {*} additionalProperties - potential additional properties @returns {Object} raml form
[ "convert", "additionalProperties", "from", "jsonSchema", "to", "raml", "form" ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/js2dt.js#L239-L252
21,364
raml-org/ramldt2jsonschema
src/js2dt.js
convertFileType
function convertFileType (data) { data['type'] = 'file' const anyOf = data.media.anyOf if (anyOf && anyOf.length > 0) { data['fileTypes'] = [] anyOf.forEach(function (el) { if (el.mediaType) { data.fileTypes.push(el.mediaType) } }) if (data.fileTypes.length < 1) { delete data.fileTypes } } delete data.media return data }
javascript
function convertFileType (data) { data['type'] = 'file' const anyOf = data.media.anyOf if (anyOf && anyOf.length > 0) { data['fileTypes'] = [] anyOf.forEach(function (el) { if (el.mediaType) { data.fileTypes.push(el.mediaType) } }) if (data.fileTypes.length < 1) { delete data.fileTypes } } delete data.media return data }
[ "function", "convertFileType", "(", "data", ")", "{", "data", "[", "'type'", "]", "=", "'file'", "const", "anyOf", "=", "data", ".", "media", ".", "anyOf", "if", "(", "anyOf", "&&", "anyOf", ".", "length", ">", "0", ")", "{", "data", "[", "'fileTypes'", "]", "=", "[", "]", "anyOf", ".", "forEach", "(", "function", "(", "el", ")", "{", "if", "(", "el", ".", "mediaType", ")", "{", "data", ".", "fileTypes", ".", "push", "(", "el", ".", "mediaType", ")", "}", "}", ")", "if", "(", "data", ".", "fileTypes", ".", "length", "<", "1", ")", "{", "delete", "data", ".", "fileTypes", "}", "}", "delete", "data", ".", "media", "return", "data", "}" ]
Change JSON type to RAML file type. @param {Object} data @returns {Object}
[ "Change", "JSON", "type", "to", "RAML", "file", "type", "." ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/js2dt.js#L286-L302
21,365
raml-org/ramldt2jsonschema
src/js2dt.js
convertDateType
function convertDateType (data) { if (!(data.type === 'string' && data.pattern)) { return data } const pattern = data.pattern delete data.pattern switch (pattern) { case constants.dateOnlyPattern: data['type'] = 'date-only' break case constants.timeOnlyPattern: data['type'] = 'time-only' break case constants.dateTimeOnlyPattern: data['type'] = 'datetime-only' break case constants.RFC3339DatetimePattern: data['type'] = 'datetime' data['format'] = constants.RFC3339 break case constants.RFC2616DatetimePattern: data['type'] = 'datetime' data['format'] = constants.RFC2616 break default: data['pattern'] = pattern } return data }
javascript
function convertDateType (data) { if (!(data.type === 'string' && data.pattern)) { return data } const pattern = data.pattern delete data.pattern switch (pattern) { case constants.dateOnlyPattern: data['type'] = 'date-only' break case constants.timeOnlyPattern: data['type'] = 'time-only' break case constants.dateTimeOnlyPattern: data['type'] = 'datetime-only' break case constants.RFC3339DatetimePattern: data['type'] = 'datetime' data['format'] = constants.RFC3339 break case constants.RFC2616DatetimePattern: data['type'] = 'datetime' data['format'] = constants.RFC2616 break default: data['pattern'] = pattern } return data }
[ "function", "convertDateType", "(", "data", ")", "{", "if", "(", "!", "(", "data", ".", "type", "===", "'string'", "&&", "data", ".", "pattern", ")", ")", "{", "return", "data", "}", "const", "pattern", "=", "data", ".", "pattern", "delete", "data", ".", "pattern", "switch", "(", "pattern", ")", "{", "case", "constants", ".", "dateOnlyPattern", ":", "data", "[", "'type'", "]", "=", "'date-only'", "break", "case", "constants", ".", "timeOnlyPattern", ":", "data", "[", "'type'", "]", "=", "'time-only'", "break", "case", "constants", ".", "dateTimeOnlyPattern", ":", "data", "[", "'type'", "]", "=", "'datetime-only'", "break", "case", "constants", ".", "RFC3339DatetimePattern", ":", "data", "[", "'type'", "]", "=", "'datetime'", "data", "[", "'format'", "]", "=", "constants", ".", "RFC3339", "break", "case", "constants", ".", "RFC2616DatetimePattern", ":", "data", "[", "'type'", "]", "=", "'datetime'", "data", "[", "'format'", "]", "=", "constants", ".", "RFC2616", "break", "default", ":", "data", "[", "'pattern'", "]", "=", "pattern", "}", "return", "data", "}" ]
Change JSON date type of data to valid RAML date type. @param {Object} data @returns {Object}
[ "Change", "JSON", "date", "type", "of", "data", "to", "valid", "RAML", "date", "type", "." ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/js2dt.js#L310-L338
21,366
raml-org/ramldt2jsonschema
src/js2dt.js
convertDefinedFormat
function convertDefinedFormat (data) { if (!(data.type === 'string' && data.format)) { return data } const format = data.format delete data.format switch (format) { case 'date-time': data['pattern'] = constants.FORMAT_REGEXPS['date-time'] break case 'email': data['pattern'] = constants.FORMAT_REGEXPS['email'] break case 'hostname': data['pattern'] = constants.FORMAT_REGEXPS['hostname'] break case 'ipv4': data['pattern'] = constants.FORMAT_REGEXPS['ipv4'] break case 'ipv6': data['pattern'] = constants.FORMAT_REGEXPS['ipv6'] break case 'uri': data['pattern'] = constants.FORMAT_REGEXPS['uri'] break case 'uri-reference': data['pattern'] = constants.FORMAT_REGEXPS['uri-reference'] break case 'json-pointer': data['pattern'] = constants.FORMAT_REGEXPS['json-pointer'] break case 'uri-template': data['pattern'] = constants.FORMAT_REGEXPS['uri-template'] break default: data['pattern'] = format } return data }
javascript
function convertDefinedFormat (data) { if (!(data.type === 'string' && data.format)) { return data } const format = data.format delete data.format switch (format) { case 'date-time': data['pattern'] = constants.FORMAT_REGEXPS['date-time'] break case 'email': data['pattern'] = constants.FORMAT_REGEXPS['email'] break case 'hostname': data['pattern'] = constants.FORMAT_REGEXPS['hostname'] break case 'ipv4': data['pattern'] = constants.FORMAT_REGEXPS['ipv4'] break case 'ipv6': data['pattern'] = constants.FORMAT_REGEXPS['ipv6'] break case 'uri': data['pattern'] = constants.FORMAT_REGEXPS['uri'] break case 'uri-reference': data['pattern'] = constants.FORMAT_REGEXPS['uri-reference'] break case 'json-pointer': data['pattern'] = constants.FORMAT_REGEXPS['json-pointer'] break case 'uri-template': data['pattern'] = constants.FORMAT_REGEXPS['uri-template'] break default: data['pattern'] = format } return data }
[ "function", "convertDefinedFormat", "(", "data", ")", "{", "if", "(", "!", "(", "data", ".", "type", "===", "'string'", "&&", "data", ".", "format", ")", ")", "{", "return", "data", "}", "const", "format", "=", "data", ".", "format", "delete", "data", ".", "format", "switch", "(", "format", ")", "{", "case", "'date-time'", ":", "data", "[", "'pattern'", "]", "=", "constants", ".", "FORMAT_REGEXPS", "[", "'date-time'", "]", "break", "case", "'email'", ":", "data", "[", "'pattern'", "]", "=", "constants", ".", "FORMAT_REGEXPS", "[", "'email'", "]", "break", "case", "'hostname'", ":", "data", "[", "'pattern'", "]", "=", "constants", ".", "FORMAT_REGEXPS", "[", "'hostname'", "]", "break", "case", "'ipv4'", ":", "data", "[", "'pattern'", "]", "=", "constants", ".", "FORMAT_REGEXPS", "[", "'ipv4'", "]", "break", "case", "'ipv6'", ":", "data", "[", "'pattern'", "]", "=", "constants", ".", "FORMAT_REGEXPS", "[", "'ipv6'", "]", "break", "case", "'uri'", ":", "data", "[", "'pattern'", "]", "=", "constants", ".", "FORMAT_REGEXPS", "[", "'uri'", "]", "break", "case", "'uri-reference'", ":", "data", "[", "'pattern'", "]", "=", "constants", ".", "FORMAT_REGEXPS", "[", "'uri-reference'", "]", "break", "case", "'json-pointer'", ":", "data", "[", "'pattern'", "]", "=", "constants", ".", "FORMAT_REGEXPS", "[", "'json-pointer'", "]", "break", "case", "'uri-template'", ":", "data", "[", "'pattern'", "]", "=", "constants", ".", "FORMAT_REGEXPS", "[", "'uri-template'", "]", "break", "default", ":", "data", "[", "'pattern'", "]", "=", "format", "}", "return", "data", "}" ]
Change JSON defined formats to RAML regex. @param {Object} data @returns {Object}
[ "Change", "JSON", "defined", "formats", "to", "RAML", "regex", "." ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/js2dt.js#L346-L384
21,367
raml-org/ramldt2jsonschema
src/js2dt.js
convertPatternProperties
function convertPatternProperties (data) { if (!data.patternProperties) { return data } data.properties = data.properties || {} const patternProperties = data.patternProperties delete data.patternProperties Object.keys(patternProperties).map(function (pattern) { data.properties['/' + pattern + '/'] = patternProperties[pattern] }) if (data.additionalProperties) delete data.additionalProperties return data }
javascript
function convertPatternProperties (data) { if (!data.patternProperties) { return data } data.properties = data.properties || {} const patternProperties = data.patternProperties delete data.patternProperties Object.keys(patternProperties).map(function (pattern) { data.properties['/' + pattern + '/'] = patternProperties[pattern] }) if (data.additionalProperties) delete data.additionalProperties return data }
[ "function", "convertPatternProperties", "(", "data", ")", "{", "if", "(", "!", "data", ".", "patternProperties", ")", "{", "return", "data", "}", "data", ".", "properties", "=", "data", ".", "properties", "||", "{", "}", "const", "patternProperties", "=", "data", ".", "patternProperties", "delete", "data", ".", "patternProperties", "Object", ".", "keys", "(", "patternProperties", ")", ".", "map", "(", "function", "(", "pattern", ")", "{", "data", ".", "properties", "[", "'/'", "+", "pattern", "+", "'/'", "]", "=", "patternProperties", "[", "pattern", "]", "}", ")", "if", "(", "data", ".", "additionalProperties", ")", "delete", "data", ".", "additionalProperties", "return", "data", "}" ]
Change JSON patternProperties to RAML pattern properties. @param {Object} data @returns {Object}
[ "Change", "JSON", "patternProperties", "to", "RAML", "pattern", "properties", "." ]
1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7
https://github.com/raml-org/ramldt2jsonschema/blob/1e7a507bbf12e17a6ff6058d26ce3ba47cadd1a7/src/js2dt.js#L392-L404
21,368
VoliJS/NestedLink
linked-controls/js/hooks.js
useThrottle
function useThrottle(fun, timeout, changes) { if (changes === void 0) { changes = []; } // Create the ref to store timer. var timer = react_1.useRef(null); function cancel() { if (timer.current) { clearTimeout(timer.current); timer.current = null; } } // Register the react_1.useEffect(function () { return cancel; }, changes); return function () { var _this = this; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } cancel(); timer.current = setTimeout(function () { timer.current = null; fun.apply(_this, args); }, timeout); }; }
javascript
function useThrottle(fun, timeout, changes) { if (changes === void 0) { changes = []; } // Create the ref to store timer. var timer = react_1.useRef(null); function cancel() { if (timer.current) { clearTimeout(timer.current); timer.current = null; } } // Register the react_1.useEffect(function () { return cancel; }, changes); return function () { var _this = this; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } cancel(); timer.current = setTimeout(function () { timer.current = null; fun.apply(_this, args); }, timeout); }; }
[ "function", "useThrottle", "(", "fun", ",", "timeout", ",", "changes", ")", "{", "if", "(", "changes", "===", "void", "0", ")", "{", "changes", "=", "[", "]", ";", "}", "// Create the ref to store timer.", "var", "timer", "=", "react_1", ".", "useRef", "(", "null", ")", ";", "function", "cancel", "(", ")", "{", "if", "(", "timer", ".", "current", ")", "{", "clearTimeout", "(", "timer", ".", "current", ")", ";", "timer", ".", "current", "=", "null", ";", "}", "}", "// Register the ", "react_1", ".", "useEffect", "(", "function", "(", ")", "{", "return", "cancel", ";", "}", ",", "changes", ")", ";", "return", "function", "(", ")", "{", "var", "_this", "=", "this", ";", "var", "args", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "arguments", ".", "length", ";", "_i", "++", ")", "{", "args", "[", "_i", "]", "=", "arguments", "[", "_i", "]", ";", "}", "cancel", "(", ")", ";", "timer", ".", "current", "=", "setTimeout", "(", "function", "(", ")", "{", "timer", ".", "current", "=", "null", ";", "fun", ".", "apply", "(", "_this", ",", "args", ")", ";", "}", ",", "timeout", ")", ";", "}", ";", "}" ]
Delays function calls for a given timeout.
[ "Delays", "function", "calls", "for", "a", "given", "timeout", "." ]
0105d461d33108d2ab2d97b8f8da6967878844d6
https://github.com/VoliJS/NestedLink/blob/0105d461d33108d2ab2d97b8f8da6967878844d6/linked-controls/js/hooks.js#L5-L29
21,369
johannesjo/angular-promise-buttons
dist/angular-promise-buttons.js
initLoadingState
function initLoadingState(btnEl) { if (cfg.btnLoadingClass && !cfg.addClassToCurrentBtnOnly) { btnEl.addClass(cfg.btnLoadingClass); } if (cfg.disableBtn && !cfg.disableCurrentBtnOnly) { btnEl.attr('disabled', 'disabled'); } }
javascript
function initLoadingState(btnEl) { if (cfg.btnLoadingClass && !cfg.addClassToCurrentBtnOnly) { btnEl.addClass(cfg.btnLoadingClass); } if (cfg.disableBtn && !cfg.disableCurrentBtnOnly) { btnEl.attr('disabled', 'disabled'); } }
[ "function", "initLoadingState", "(", "btnEl", ")", "{", "if", "(", "cfg", ".", "btnLoadingClass", "&&", "!", "cfg", ".", "addClassToCurrentBtnOnly", ")", "{", "btnEl", ".", "addClass", "(", "cfg", ".", "btnLoadingClass", ")", ";", "}", "if", "(", "cfg", ".", "disableBtn", "&&", "!", "cfg", ".", "disableCurrentBtnOnly", ")", "{", "btnEl", ".", "attr", "(", "'disabled'", ",", "'disabled'", ")", ";", "}", "}" ]
Handles everything to be triggered when the button is set to loading state. @param {Object}btnEl
[ "Handles", "everything", "to", "be", "triggered", "when", "the", "button", "is", "set", "to", "loading", "state", "." ]
969197cfe8cbaea055b8d620016deb0c88dce7e4
https://github.com/johannesjo/angular-promise-buttons/blob/969197cfe8cbaea055b8d620016deb0c88dce7e4/dist/angular-promise-buttons.js#L32-L39
21,370
johannesjo/angular-promise-buttons
dist/angular-promise-buttons.js
handleLoadingFinished
function handleLoadingFinished(btnEl) { if ((!cfg.minDuration || minDurationTimeoutDone) && promiseDone) { if (cfg.btnLoadingClass) { btnEl.removeClass(cfg.btnLoadingClass); } if (cfg.disableBtn && !scope.ngDisabled) { btnEl.removeAttr('disabled'); } } }
javascript
function handleLoadingFinished(btnEl) { if ((!cfg.minDuration || minDurationTimeoutDone) && promiseDone) { if (cfg.btnLoadingClass) { btnEl.removeClass(cfg.btnLoadingClass); } if (cfg.disableBtn && !scope.ngDisabled) { btnEl.removeAttr('disabled'); } } }
[ "function", "handleLoadingFinished", "(", "btnEl", ")", "{", "if", "(", "(", "!", "cfg", ".", "minDuration", "||", "minDurationTimeoutDone", ")", "&&", "promiseDone", ")", "{", "if", "(", "cfg", ".", "btnLoadingClass", ")", "{", "btnEl", ".", "removeClass", "(", "cfg", ".", "btnLoadingClass", ")", ";", "}", "if", "(", "cfg", ".", "disableBtn", "&&", "!", "scope", ".", "ngDisabled", ")", "{", "btnEl", ".", "removeAttr", "(", "'disabled'", ")", ";", "}", "}", "}" ]
Handles everything to be triggered when loading is finished @param {Object}btnEl
[ "Handles", "everything", "to", "be", "triggered", "when", "loading", "is", "finished" ]
969197cfe8cbaea055b8d620016deb0c88dce7e4
https://github.com/johannesjo/angular-promise-buttons/blob/969197cfe8cbaea055b8d620016deb0c88dce7e4/dist/angular-promise-buttons.js#L45-L54
21,371
johannesjo/angular-promise-buttons
dist/angular-promise-buttons.js
initPromiseWatcher
function initPromiseWatcher(watchExpressionForPromise, btnEl) { // watch promise to resolve or fail scope.$watch(watchExpressionForPromise, function (mVal) { minDurationTimeoutDone = false; promiseDone = false; // create timeout if option is set if (cfg.minDuration) { minDurationTimeout = $timeout(function () { minDurationTimeoutDone = true; handleLoadingFinished(btnEl); }, cfg.minDuration); } // for regular promises if (mVal && mVal.then) { initLoadingState(btnEl); // angular promise if (mVal.finally) { mVal.finally(function () { promiseDone = true; handleLoadingFinished(btnEl); }); } // ES6 promises else { mVal.then(function () { promiseDone = true; handleLoadingFinished(btnEl); }) .catch(function () { promiseDone = true; handleLoadingFinished(btnEl); }); } } // for $resource else if (mVal && mVal.$promise) { initLoadingState(btnEl); mVal.$promise.finally(function () { promiseDone = true; handleLoadingFinished(btnEl); }); } }); }
javascript
function initPromiseWatcher(watchExpressionForPromise, btnEl) { // watch promise to resolve or fail scope.$watch(watchExpressionForPromise, function (mVal) { minDurationTimeoutDone = false; promiseDone = false; // create timeout if option is set if (cfg.minDuration) { minDurationTimeout = $timeout(function () { minDurationTimeoutDone = true; handleLoadingFinished(btnEl); }, cfg.minDuration); } // for regular promises if (mVal && mVal.then) { initLoadingState(btnEl); // angular promise if (mVal.finally) { mVal.finally(function () { promiseDone = true; handleLoadingFinished(btnEl); }); } // ES6 promises else { mVal.then(function () { promiseDone = true; handleLoadingFinished(btnEl); }) .catch(function () { promiseDone = true; handleLoadingFinished(btnEl); }); } } // for $resource else if (mVal && mVal.$promise) { initLoadingState(btnEl); mVal.$promise.finally(function () { promiseDone = true; handleLoadingFinished(btnEl); }); } }); }
[ "function", "initPromiseWatcher", "(", "watchExpressionForPromise", ",", "btnEl", ")", "{", "// watch promise to resolve or fail", "scope", ".", "$watch", "(", "watchExpressionForPromise", ",", "function", "(", "mVal", ")", "{", "minDurationTimeoutDone", "=", "false", ";", "promiseDone", "=", "false", ";", "// create timeout if option is set", "if", "(", "cfg", ".", "minDuration", ")", "{", "minDurationTimeout", "=", "$timeout", "(", "function", "(", ")", "{", "minDurationTimeoutDone", "=", "true", ";", "handleLoadingFinished", "(", "btnEl", ")", ";", "}", ",", "cfg", ".", "minDuration", ")", ";", "}", "// for regular promises", "if", "(", "mVal", "&&", "mVal", ".", "then", ")", "{", "initLoadingState", "(", "btnEl", ")", ";", "// angular promise", "if", "(", "mVal", ".", "finally", ")", "{", "mVal", ".", "finally", "(", "function", "(", ")", "{", "promiseDone", "=", "true", ";", "handleLoadingFinished", "(", "btnEl", ")", ";", "}", ")", ";", "}", "// ES6 promises", "else", "{", "mVal", ".", "then", "(", "function", "(", ")", "{", "promiseDone", "=", "true", ";", "handleLoadingFinished", "(", "btnEl", ")", ";", "}", ")", ".", "catch", "(", "function", "(", ")", "{", "promiseDone", "=", "true", ";", "handleLoadingFinished", "(", "btnEl", ")", ";", "}", ")", ";", "}", "}", "// for $resource", "else", "if", "(", "mVal", "&&", "mVal", ".", "$promise", ")", "{", "initLoadingState", "(", "btnEl", ")", ";", "mVal", ".", "$promise", ".", "finally", "(", "function", "(", ")", "{", "promiseDone", "=", "true", ";", "handleLoadingFinished", "(", "btnEl", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
Initializes a watcher for the promise. Also takes cfg.minDuration into account if given. @param {Function}watchExpressionForPromise @param {Object}btnEl
[ "Initializes", "a", "watcher", "for", "the", "promise", ".", "Also", "takes", "cfg", ".", "minDuration", "into", "account", "if", "given", "." ]
969197cfe8cbaea055b8d620016deb0c88dce7e4
https://github.com/johannesjo/angular-promise-buttons/blob/969197cfe8cbaea055b8d620016deb0c88dce7e4/dist/angular-promise-buttons.js#L62-L109
21,372
johannesjo/angular-promise-buttons
dist/angular-promise-buttons.js
addHandlersForCurrentBtnOnly
function addHandlersForCurrentBtnOnly(btnEl) { // handle current button only options via click if (cfg.addClassToCurrentBtnOnly) { btnEl.on(cfg.CLICK_EVENT, function () { btnEl.addClass(cfg.btnLoadingClass); }); } if (cfg.disableCurrentBtnOnly) { btnEl.on(cfg.CLICK_EVENT, function () { btnEl.attr('disabled', 'disabled'); }); } }
javascript
function addHandlersForCurrentBtnOnly(btnEl) { // handle current button only options via click if (cfg.addClassToCurrentBtnOnly) { btnEl.on(cfg.CLICK_EVENT, function () { btnEl.addClass(cfg.btnLoadingClass); }); } if (cfg.disableCurrentBtnOnly) { btnEl.on(cfg.CLICK_EVENT, function () { btnEl.attr('disabled', 'disabled'); }); } }
[ "function", "addHandlersForCurrentBtnOnly", "(", "btnEl", ")", "{", "// handle current button only options via click", "if", "(", "cfg", ".", "addClassToCurrentBtnOnly", ")", "{", "btnEl", ".", "on", "(", "cfg", ".", "CLICK_EVENT", ",", "function", "(", ")", "{", "btnEl", ".", "addClass", "(", "cfg", ".", "btnLoadingClass", ")", ";", "}", ")", ";", "}", "if", "(", "cfg", ".", "disableCurrentBtnOnly", ")", "{", "btnEl", ".", "on", "(", "cfg", ".", "CLICK_EVENT", ",", "function", "(", ")", "{", "btnEl", ".", "attr", "(", "'disabled'", ",", "'disabled'", ")", ";", "}", ")", ";", "}", "}" ]
Used to limit loading state to show only for the currently clicked button. @param {Object}btnEl
[ "Used", "to", "limit", "loading", "state", "to", "show", "only", "for", "the", "currently", "clicked", "button", "." ]
969197cfe8cbaea055b8d620016deb0c88dce7e4
https://github.com/johannesjo/angular-promise-buttons/blob/969197cfe8cbaea055b8d620016deb0c88dce7e4/dist/angular-promise-buttons.js#L139-L152
21,373
johannesjo/angular-promise-buttons
dist/angular-promise-buttons.js
getSubmitBtnChildren
function getSubmitBtnChildren(formEl) { var submitBtnEls = []; var allButtonEls = formEl.find(angularPromiseButtons.config.BTN_SELECTOR); for (var i = 0; i < allButtonEls.length; i++) { var btnEl = allButtonEls[i]; if (angular.element(btnEl) .attr('type') === 'submit') { submitBtnEls.push(btnEl); } } return angular.element(submitBtnEls); }
javascript
function getSubmitBtnChildren(formEl) { var submitBtnEls = []; var allButtonEls = formEl.find(angularPromiseButtons.config.BTN_SELECTOR); for (var i = 0; i < allButtonEls.length; i++) { var btnEl = allButtonEls[i]; if (angular.element(btnEl) .attr('type') === 'submit') { submitBtnEls.push(btnEl); } } return angular.element(submitBtnEls); }
[ "function", "getSubmitBtnChildren", "(", "formEl", ")", "{", "var", "submitBtnEls", "=", "[", "]", ";", "var", "allButtonEls", "=", "formEl", ".", "find", "(", "angularPromiseButtons", ".", "config", ".", "BTN_SELECTOR", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "allButtonEls", ".", "length", ";", "i", "++", ")", "{", "var", "btnEl", "=", "allButtonEls", "[", "i", "]", ";", "if", "(", "angular", ".", "element", "(", "btnEl", ")", ".", "attr", "(", "'type'", ")", "===", "'submit'", ")", "{", "submitBtnEls", ".", "push", "(", "btnEl", ")", ";", "}", "}", "return", "angular", ".", "element", "(", "submitBtnEls", ")", ";", "}" ]
Get's all submit button children of the given element @param {Object}formEl @returns {Object}
[ "Get", "s", "all", "submit", "button", "children", "of", "the", "given", "element" ]
969197cfe8cbaea055b8d620016deb0c88dce7e4
https://github.com/johannesjo/angular-promise-buttons/blob/969197cfe8cbaea055b8d620016deb0c88dce7e4/dist/angular-promise-buttons.js#L221-L233
21,374
tkoenig89/express-static-gzip
util/options.js
sanitizeOptions
function sanitizeOptions(userOptions) { userOptions = userOptions || {}; let options = { index: getIndexValue(userOptions) } if(userOptions.index){ // required to not interfere with serve-static delete userOptions.index; } if (typeof (userOptions.enableBrotli) !== "undefined") { options.enableBrotli = !!userOptions.enableBrotli; } if (typeof (userOptions.customCompressions) === "object" ) { options.customCompressions = userOptions.customCompressions; } if (typeof (userOptions.orderPreference) === "object" ) { options.orderPreference = userOptions.orderPreference; } return options; }
javascript
function sanitizeOptions(userOptions) { userOptions = userOptions || {}; let options = { index: getIndexValue(userOptions) } if(userOptions.index){ // required to not interfere with serve-static delete userOptions.index; } if (typeof (userOptions.enableBrotli) !== "undefined") { options.enableBrotli = !!userOptions.enableBrotli; } if (typeof (userOptions.customCompressions) === "object" ) { options.customCompressions = userOptions.customCompressions; } if (typeof (userOptions.orderPreference) === "object" ) { options.orderPreference = userOptions.orderPreference; } return options; }
[ "function", "sanitizeOptions", "(", "userOptions", ")", "{", "userOptions", "=", "userOptions", "||", "{", "}", ";", "let", "options", "=", "{", "index", ":", "getIndexValue", "(", "userOptions", ")", "}", "if", "(", "userOptions", ".", "index", ")", "{", "// required to not interfere with serve-static", "delete", "userOptions", ".", "index", ";", "}", "if", "(", "typeof", "(", "userOptions", ".", "enableBrotli", ")", "!==", "\"undefined\"", ")", "{", "options", ".", "enableBrotli", "=", "!", "!", "userOptions", ".", "enableBrotli", ";", "}", "if", "(", "typeof", "(", "userOptions", ".", "customCompressions", ")", "===", "\"object\"", ")", "{", "options", ".", "customCompressions", "=", "userOptions", ".", "customCompressions", ";", "}", "if", "(", "typeof", "(", "userOptions", ".", "orderPreference", ")", "===", "\"object\"", ")", "{", "options", ".", "orderPreference", "=", "userOptions", ".", "orderPreference", ";", "}", "return", "options", ";", "}" ]
Prepares the options object for later use. Strips away any options used for serve-static. Removes problematic options from the input options object. @param {{enableBrotli?:boolean, customCompressions?:[{encodingName:string,fileExtension:string}], indexFromEmptyFile?:boolean, index?: boolean}} userOptions
[ "Prepares", "the", "options", "object", "for", "later", "use", ".", "Strips", "away", "any", "options", "used", "for", "serve", "-", "static", ".", "Removes", "problematic", "options", "from", "the", "input", "options", "object", "." ]
a08cffaa47632d3b94a48508fc97104de72f93e1
https://github.com/tkoenig89/express-static-gzip/blob/a08cffaa47632d3b94a48508fc97104de72f93e1/util/options.js#L7-L32
21,375
tkoenig89/express-static-gzip
index.js
setupCompressions
function setupCompressions() { //register all provided compressions if (opts.customCompressions && opts.customCompressions.length > 0) { for (var i = 0; i < opts.customCompressions.length; i++) { var customCompression = opts.customCompressions[i]; registerCompression(customCompression.encodingName, customCompression.fileExtension); } } //enable brotli compression if (opts.enableBrotli) { registerCompression("br", "br"); } //gzip compression is enabled by default registerCompression("gzip", "gz"); }
javascript
function setupCompressions() { //register all provided compressions if (opts.customCompressions && opts.customCompressions.length > 0) { for (var i = 0; i < opts.customCompressions.length; i++) { var customCompression = opts.customCompressions[i]; registerCompression(customCompression.encodingName, customCompression.fileExtension); } } //enable brotli compression if (opts.enableBrotli) { registerCompression("br", "br"); } //gzip compression is enabled by default registerCompression("gzip", "gz"); }
[ "function", "setupCompressions", "(", ")", "{", "//register all provided compressions", "if", "(", "opts", ".", "customCompressions", "&&", "opts", ".", "customCompressions", ".", "length", ">", "0", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "opts", ".", "customCompressions", ".", "length", ";", "i", "++", ")", "{", "var", "customCompression", "=", "opts", ".", "customCompressions", "[", "i", "]", ";", "registerCompression", "(", "customCompression", ".", "encodingName", ",", "customCompression", ".", "fileExtension", ")", ";", "}", "}", "//enable brotli compression", "if", "(", "opts", ".", "enableBrotli", ")", "{", "registerCompression", "(", "\"br\"", ",", "\"br\"", ")", ";", "}", "//gzip compression is enabled by default", "registerCompression", "(", "\"gzip\"", ",", "\"gz\"", ")", ";", "}" ]
Reads the options into a list of available compressions.
[ "Reads", "the", "options", "into", "a", "list", "of", "available", "compressions", "." ]
a08cffaa47632d3b94a48508fc97104de72f93e1
https://github.com/tkoenig89/express-static-gzip/blob/a08cffaa47632d3b94a48508fc97104de72f93e1/index.js#L59-L75
21,376
tkoenig89/express-static-gzip
index.js
convertToCompressedRequest
function convertToCompressedRequest(req, res, compression) { var type = mime.lookup(req.path); var charset = mime.charsets.lookup(type); var search = req.url.split('?').splice(1).join('?'); if (search !== "") { search = "?" + search; } req.url = req.path + compression.fileExtension + search; res.setHeader("Content-Encoding", compression.encodingName); res.setHeader("Content-Type", type + (charset ? "; charset=" + charset : "")); }
javascript
function convertToCompressedRequest(req, res, compression) { var type = mime.lookup(req.path); var charset = mime.charsets.lookup(type); var search = req.url.split('?').splice(1).join('?'); if (search !== "") { search = "?" + search; } req.url = req.path + compression.fileExtension + search; res.setHeader("Content-Encoding", compression.encodingName); res.setHeader("Content-Type", type + (charset ? "; charset=" + charset : "")); }
[ "function", "convertToCompressedRequest", "(", "req", ",", "res", ",", "compression", ")", "{", "var", "type", "=", "mime", ".", "lookup", "(", "req", ".", "path", ")", ";", "var", "charset", "=", "mime", ".", "charsets", ".", "lookup", "(", "type", ")", ";", "var", "search", "=", "req", ".", "url", ".", "split", "(", "'?'", ")", ".", "splice", "(", "1", ")", ".", "join", "(", "'?'", ")", ";", "if", "(", "search", "!==", "\"\"", ")", "{", "search", "=", "\"?\"", "+", "search", ";", "}", "req", ".", "url", "=", "req", ".", "path", "+", "compression", ".", "fileExtension", "+", "search", ";", "res", ".", "setHeader", "(", "\"Content-Encoding\"", ",", "compression", ".", "encodingName", ")", ";", "res", ".", "setHeader", "(", "\"Content-Type\"", ",", "type", "+", "(", "charset", "?", "\"; charset=\"", "+", "charset", ":", "\"\"", ")", ")", ";", "}" ]
Changes the url and adds required headers to serve a compressed file. @param {Object} req @param {Object} res
[ "Changes", "the", "url", "and", "adds", "required", "headers", "to", "serve", "a", "compressed", "file", "." ]
a08cffaa47632d3b94a48508fc97104de72f93e1
https://github.com/tkoenig89/express-static-gzip/blob/a08cffaa47632d3b94a48508fc97104de72f93e1/index.js#L82-L94
21,377
tkoenig89/express-static-gzip
index.js
findAvailableCompressionForFile
function findAvailableCompressionForFile(compressionList, acceptedEncoding) { if (acceptedEncoding) { for (var i = 0; i < compressionList.length; i++) { if (acceptedEncoding.indexOf(compressionList[i].encodingName) >= 0) { return compressionList[i]; } } } return null; }
javascript
function findAvailableCompressionForFile(compressionList, acceptedEncoding) { if (acceptedEncoding) { for (var i = 0; i < compressionList.length; i++) { if (acceptedEncoding.indexOf(compressionList[i].encodingName) >= 0) { return compressionList[i]; } } } return null; }
[ "function", "findAvailableCompressionForFile", "(", "compressionList", ",", "acceptedEncoding", ")", "{", "if", "(", "acceptedEncoding", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "compressionList", ".", "length", ";", "i", "++", ")", "{", "if", "(", "acceptedEncoding", ".", "indexOf", "(", "compressionList", "[", "i", "]", ".", "encodingName", ")", ">=", "0", ")", "{", "return", "compressionList", "[", "i", "]", ";", "}", "}", "}", "return", "null", ";", "}" ]
Searches for the first matching compression available from the given compressions. @param {[Compression]} compressionList @param {string} acceptedEncoding @returns
[ "Searches", "for", "the", "first", "matching", "compression", "available", "from", "the", "given", "compressions", "." ]
a08cffaa47632d3b94a48508fc97104de72f93e1
https://github.com/tkoenig89/express-static-gzip/blob/a08cffaa47632d3b94a48508fc97104de72f93e1/index.js#L112-L121
21,378
tkoenig89/express-static-gzip
index.js
findAllCompressionFiles
function findAllCompressionFiles(fs, folderPath) { // check if folder exists if (!fs.existsSync(folderPath)) return; var files = fs.readdirSync(folderPath); //iterate all files in the current folder for (var i = 0; i < files.length; i++) { var filePath = folderPath + "/" + files[i]; var stats = fs.statSync(filePath); if (stats.isDirectory()) { //recursively search folders and append the matching files findAllCompressionFiles(fs, filePath); } else { addAllMatchingCompressionsToFile(files[i], filePath); } } }
javascript
function findAllCompressionFiles(fs, folderPath) { // check if folder exists if (!fs.existsSync(folderPath)) return; var files = fs.readdirSync(folderPath); //iterate all files in the current folder for (var i = 0; i < files.length; i++) { var filePath = folderPath + "/" + files[i]; var stats = fs.statSync(filePath); if (stats.isDirectory()) { //recursively search folders and append the matching files findAllCompressionFiles(fs, filePath); } else { addAllMatchingCompressionsToFile(files[i], filePath); } } }
[ "function", "findAllCompressionFiles", "(", "fs", ",", "folderPath", ")", "{", "// check if folder exists", "if", "(", "!", "fs", ".", "existsSync", "(", "folderPath", ")", ")", "return", ";", "var", "files", "=", "fs", ".", "readdirSync", "(", "folderPath", ")", ";", "//iterate all files in the current folder", "for", "(", "var", "i", "=", "0", ";", "i", "<", "files", ".", "length", ";", "i", "++", ")", "{", "var", "filePath", "=", "folderPath", "+", "\"/\"", "+", "files", "[", "i", "]", ";", "var", "stats", "=", "fs", ".", "statSync", "(", "filePath", ")", ";", "if", "(", "stats", ".", "isDirectory", "(", ")", ")", "{", "//recursively search folders and append the matching files", "findAllCompressionFiles", "(", "fs", ",", "filePath", ")", ";", "}", "else", "{", "addAllMatchingCompressionsToFile", "(", "files", "[", "i", "]", ",", "filePath", ")", ";", "}", "}", "}" ]
Picks all files into the matching compression's file list. Search is done recursively! @param {Object} fs: node.fs @param {string} folderPath
[ "Picks", "all", "files", "into", "the", "matching", "compression", "s", "file", "list", ".", "Search", "is", "done", "recursively!" ]
a08cffaa47632d3b94a48508fc97104de72f93e1
https://github.com/tkoenig89/express-static-gzip/blob/a08cffaa47632d3b94a48508fc97104de72f93e1/index.js#L128-L144
21,379
tkoenig89/express-static-gzip
index.js
addAllMatchingCompressionsToFile
function addAllMatchingCompressionsToFile(fileName, fullFilePath) { for (var i = 0; i < compressions.length; i++) { if (fileName.endsWith(compressions[i].fileExtension)) { addCompressionToFile(fullFilePath, compressions[i]); return; } } }
javascript
function addAllMatchingCompressionsToFile(fileName, fullFilePath) { for (var i = 0; i < compressions.length; i++) { if (fileName.endsWith(compressions[i].fileExtension)) { addCompressionToFile(fullFilePath, compressions[i]); return; } } }
[ "function", "addAllMatchingCompressionsToFile", "(", "fileName", ",", "fullFilePath", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "compressions", ".", "length", ";", "i", "++", ")", "{", "if", "(", "fileName", ".", "endsWith", "(", "compressions", "[", "i", "]", ".", "fileExtension", ")", ")", "{", "addCompressionToFile", "(", "fullFilePath", ",", "compressions", "[", "i", "]", ")", ";", "return", ";", "}", "}", "}" ]
Takes a filename and checks if there is any compression type matching the file extension. Adds all matching compressions to the file. @param {string} fileName @param {string} fillFilePath
[ "Takes", "a", "filename", "and", "checks", "if", "there", "is", "any", "compression", "type", "matching", "the", "file", "extension", ".", "Adds", "all", "matching", "compressions", "to", "the", "file", "." ]
a08cffaa47632d3b94a48508fc97104de72f93e1
https://github.com/tkoenig89/express-static-gzip/blob/a08cffaa47632d3b94a48508fc97104de72f93e1/index.js#L152-L159
21,380
tkoenig89/express-static-gzip
index.js
addCompressionToFile
function addCompressionToFile(filePath, compression) { var srcFilePath = filePath.replace(rootFolder, "").replace(compression.fileExtension, ""); var existingFile = files[srcFilePath]; if (!existingFile) { files[srcFilePath] = { compressions: [compression] }; } else { existingFile.compressions.push(compression); } }
javascript
function addCompressionToFile(filePath, compression) { var srcFilePath = filePath.replace(rootFolder, "").replace(compression.fileExtension, ""); var existingFile = files[srcFilePath]; if (!existingFile) { files[srcFilePath] = { compressions: [compression] }; } else { existingFile.compressions.push(compression); } }
[ "function", "addCompressionToFile", "(", "filePath", ",", "compression", ")", "{", "var", "srcFilePath", "=", "filePath", ".", "replace", "(", "rootFolder", ",", "\"\"", ")", ".", "replace", "(", "compression", ".", "fileExtension", ",", "\"\"", ")", ";", "var", "existingFile", "=", "files", "[", "srcFilePath", "]", ";", "if", "(", "!", "existingFile", ")", "{", "files", "[", "srcFilePath", "]", "=", "{", "compressions", ":", "[", "compression", "]", "}", ";", "}", "else", "{", "existingFile", ".", "compressions", ".", "push", "(", "compression", ")", ";", "}", "}" ]
Adds the compression to the file's list of available compressions @param {string} filePath @param {Compression} compression
[ "Adds", "the", "compression", "to", "the", "file", "s", "list", "of", "available", "compressions" ]
a08cffaa47632d3b94a48508fc97104de72f93e1
https://github.com/tkoenig89/express-static-gzip/blob/a08cffaa47632d3b94a48508fc97104de72f93e1/index.js#L166-L174
21,381
tkoenig89/express-static-gzip
index.js
registerCompression
function registerCompression(encodingName, fileExtension) { if (!findCompressionByName(encodingName)) compressions.push(new Compression(encodingName, fileExtension)); }
javascript
function registerCompression(encodingName, fileExtension) { if (!findCompressionByName(encodingName)) compressions.push(new Compression(encodingName, fileExtension)); }
[ "function", "registerCompression", "(", "encodingName", ",", "fileExtension", ")", "{", "if", "(", "!", "findCompressionByName", "(", "encodingName", ")", ")", "compressions", ".", "push", "(", "new", "Compression", "(", "encodingName", ",", "fileExtension", ")", ")", ";", "}" ]
Registers a new compression to the module. @param {string} encodingName @param {string} fileExtension
[ "Registers", "a", "new", "compression", "to", "the", "module", "." ]
a08cffaa47632d3b94a48508fc97104de72f93e1
https://github.com/tkoenig89/express-static-gzip/blob/a08cffaa47632d3b94a48508fc97104de72f93e1/index.js#L181-L184
21,382
tkoenig89/express-static-gzip
index.js
findCompressionByName
function findCompressionByName(encodingName) { for (var i = 0; i < compressions.length; i++) { if (compressions[i].encodingName === encodingName) return compressions[i]; } return null; }
javascript
function findCompressionByName(encodingName) { for (var i = 0; i < compressions.length; i++) { if (compressions[i].encodingName === encodingName) return compressions[i]; } return null; }
[ "function", "findCompressionByName", "(", "encodingName", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "compressions", ".", "length", ";", "i", "++", ")", "{", "if", "(", "compressions", "[", "i", "]", ".", "encodingName", "===", "encodingName", ")", "return", "compressions", "[", "i", "]", ";", "}", "return", "null", ";", "}" ]
Compression lookup by name. @param {string} encodingName @returns {Compression}
[ "Compression", "lookup", "by", "name", "." ]
a08cffaa47632d3b94a48508fc97104de72f93e1
https://github.com/tkoenig89/express-static-gzip/blob/a08cffaa47632d3b94a48508fc97104de72f93e1/index.js#L202-L208
21,383
marko-js/marko-widgets
lib/init-widgets-browser.js
initClientRendered
function initClientRendered(widgetDefs, document) { // Ensure that event handlers to handle delegating events are // always attached before initializing any widgets eventDelegation.init(); document = document || window.document; for (var i=0,len=widgetDefs.length; i<len; i++) { var widgetDef = widgetDefs[i]; if (widgetDef.children.length) { initClientRendered(widgetDef.children, document); } var widget = initWidget( widgetDef.type, widgetDef.id, widgetDef.config, widgetDef.state, widgetDef.scope, widgetDef.domEvents, widgetDef.customEvents, widgetDef.extend, widgetDef.bodyElId, widgetDef.existingWidget, null, document); widgetDef.widget = widget; } }
javascript
function initClientRendered(widgetDefs, document) { // Ensure that event handlers to handle delegating events are // always attached before initializing any widgets eventDelegation.init(); document = document || window.document; for (var i=0,len=widgetDefs.length; i<len; i++) { var widgetDef = widgetDefs[i]; if (widgetDef.children.length) { initClientRendered(widgetDef.children, document); } var widget = initWidget( widgetDef.type, widgetDef.id, widgetDef.config, widgetDef.state, widgetDef.scope, widgetDef.domEvents, widgetDef.customEvents, widgetDef.extend, widgetDef.bodyElId, widgetDef.existingWidget, null, document); widgetDef.widget = widget; } }
[ "function", "initClientRendered", "(", "widgetDefs", ",", "document", ")", "{", "// Ensure that event handlers to handle delegating events are", "// always attached before initializing any widgets", "eventDelegation", ".", "init", "(", ")", ";", "document", "=", "document", "||", "window", ".", "document", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "widgetDefs", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "widgetDef", "=", "widgetDefs", "[", "i", "]", ";", "if", "(", "widgetDef", ".", "children", ".", "length", ")", "{", "initClientRendered", "(", "widgetDef", ".", "children", ",", "document", ")", ";", "}", "var", "widget", "=", "initWidget", "(", "widgetDef", ".", "type", ",", "widgetDef", ".", "id", ",", "widgetDef", ".", "config", ",", "widgetDef", ".", "state", ",", "widgetDef", ".", "scope", ",", "widgetDef", ".", "domEvents", ",", "widgetDef", ".", "customEvents", ",", "widgetDef", ".", "extend", ",", "widgetDef", ".", "bodyElId", ",", "widgetDef", ".", "existingWidget", ",", "null", ",", "document", ")", ";", "widgetDef", ".", "widget", "=", "widget", ";", "}", "}" ]
Create a helper function handle recursion
[ "Create", "a", "helper", "function", "handle", "recursion" ]
e97a7f73343101ff11f4e73bf6edfb5e1544c1f9
https://github.com/marko-js/marko-widgets/blob/e97a7f73343101ff11f4e73bf6edfb5e1544c1f9/lib/init-widgets-browser.js#L272-L301
21,384
marko-js/marko-widgets
lib/WidgetDef.js
function(type, targetMethod, elId) { if (!targetMethod) { // The event handler method is allowed to be conditional. At render time if the target // method is null then we do not attach any direct event listeners. return; } if (!this.domEvents) { this.domEvents = []; } this.domEvents.push(type); this.domEvents.push(targetMethod); this.domEvents.push(elId); }
javascript
function(type, targetMethod, elId) { if (!targetMethod) { // The event handler method is allowed to be conditional. At render time if the target // method is null then we do not attach any direct event listeners. return; } if (!this.domEvents) { this.domEvents = []; } this.domEvents.push(type); this.domEvents.push(targetMethod); this.domEvents.push(elId); }
[ "function", "(", "type", ",", "targetMethod", ",", "elId", ")", "{", "if", "(", "!", "targetMethod", ")", "{", "// The event handler method is allowed to be conditional. At render time if the target", "// method is null then we do not attach any direct event listeners.", "return", ";", "}", "if", "(", "!", "this", ".", "domEvents", ")", "{", "this", ".", "domEvents", "=", "[", "]", ";", "}", "this", ".", "domEvents", ".", "push", "(", "type", ")", ";", "this", ".", "domEvents", ".", "push", "(", "targetMethod", ")", ";", "this", ".", "domEvents", ".", "push", "(", "elId", ")", ";", "}" ]
Registers a DOM event for a nested HTML element associated with the widget. This is only done for non-bubbling events that require direct event listeners to be added. @param {String} type The DOM event type ("mouseover", "mousemove", etc.) @param {String} targetMethod The name of the method to invoke on the scoped widget @param {String} elId The DOM element ID of the DOM element that the event listener needs to be added too
[ "Registers", "a", "DOM", "event", "for", "a", "nested", "HTML", "element", "associated", "with", "the", "widget", ".", "This", "is", "only", "done", "for", "non", "-", "bubbling", "events", "that", "require", "direct", "event", "listeners", "to", "be", "added", "." ]
e97a7f73343101ff11f4e73bf6edfb5e1544c1f9
https://github.com/marko-js/marko-widgets/blob/e97a7f73343101ff11f4e73bf6edfb5e1544c1f9/lib/WidgetDef.js#L79-L93
21,385
marko-js/marko-widgets
lib/Widget.js
Widget
function Widget(id, document) { EventEmitter.call(this); this.id = id; this.el = null; this.bodyEl = null; this.state = null; this.__subscriptions = null; this.__evHandles = null; this.__lifecycleState = null; this.__customEvents = null; this.__scope = null; this.__dirty = false; this.__oldState = null; this.__stateChanges = null; this.__updateQueued = false; this.__dirtyState = null; this.__document = document; }
javascript
function Widget(id, document) { EventEmitter.call(this); this.id = id; this.el = null; this.bodyEl = null; this.state = null; this.__subscriptions = null; this.__evHandles = null; this.__lifecycleState = null; this.__customEvents = null; this.__scope = null; this.__dirty = false; this.__oldState = null; this.__stateChanges = null; this.__updateQueued = false; this.__dirtyState = null; this.__document = document; }
[ "function", "Widget", "(", "id", ",", "document", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "id", "=", "id", ";", "this", ".", "el", "=", "null", ";", "this", ".", "bodyEl", "=", "null", ";", "this", ".", "state", "=", "null", ";", "this", ".", "__subscriptions", "=", "null", ";", "this", ".", "__evHandles", "=", "null", ";", "this", ".", "__lifecycleState", "=", "null", ";", "this", ".", "__customEvents", "=", "null", ";", "this", ".", "__scope", "=", "null", ";", "this", ".", "__dirty", "=", "false", ";", "this", ".", "__oldState", "=", "null", ";", "this", ".", "__stateChanges", "=", "null", ";", "this", ".", "__updateQueued", "=", "false", ";", "this", ".", "__dirtyState", "=", "null", ";", "this", ".", "__document", "=", "document", ";", "}" ]
Base widget type. NOTE: Any methods that are prefixed with an underscore should be considered private!
[ "Base", "widget", "type", "." ]
e97a7f73343101ff11f4e73bf6edfb5e1544c1f9
https://github.com/marko-js/marko-widgets/blob/e97a7f73343101ff11f4e73bf6edfb5e1544c1f9/lib/Widget.js#L216-L233
21,386
marko-js/marko-widgets
taglib/widget-tag.js
getExistingWidget
function getExistingWidget(id, type) { var existingEl = document.getElementById(id); var existingWidget; if (existingEl && (existingWidget = existingEl.__widget) && existingWidget.__type === type) { return existingWidget; } return null; }
javascript
function getExistingWidget(id, type) { var existingEl = document.getElementById(id); var existingWidget; if (existingEl && (existingWidget = existingEl.__widget) && existingWidget.__type === type) { return existingWidget; } return null; }
[ "function", "getExistingWidget", "(", "id", ",", "type", ")", "{", "var", "existingEl", "=", "document", ".", "getElementById", "(", "id", ")", ";", "var", "existingWidget", ";", "if", "(", "existingEl", "&&", "(", "existingWidget", "=", "existingEl", ".", "__widget", ")", "&&", "existingWidget", ".", "__type", "===", "type", ")", "{", "return", "existingWidget", ";", "}", "return", "null", ";", "}" ]
Look in in the DOM to see if a widget with the same ID and type already exists.
[ "Look", "in", "in", "the", "DOM", "to", "see", "if", "a", "widget", "with", "the", "same", "ID", "and", "type", "already", "exists", "." ]
e97a7f73343101ff11f4e73bf6edfb5e1544c1f9
https://github.com/marko-js/marko-widgets/blob/e97a7f73343101ff11f4e73bf6edfb5e1544c1f9/taglib/widget-tag.js#L31-L40
21,387
marko-js/marko-widgets
lib/addEventListener.js
getIEEvent
function getIEEvent() { var event = window.event; // add event.target event.target = event.target || event.srcElement; event.preventDefault = event.preventDefault || function() { event.returnValue = false; }; event.stopPropagation = event.stopPropagation || function() { event.cancelBubble = true; }; event.key = (event.which + 1 || event.keyCode + 1) - 1 || 0; return event; }
javascript
function getIEEvent() { var event = window.event; // add event.target event.target = event.target || event.srcElement; event.preventDefault = event.preventDefault || function() { event.returnValue = false; }; event.stopPropagation = event.stopPropagation || function() { event.cancelBubble = true; }; event.key = (event.which + 1 || event.keyCode + 1) - 1 || 0; return event; }
[ "function", "getIEEvent", "(", ")", "{", "var", "event", "=", "window", ".", "event", ";", "// add event.target", "event", ".", "target", "=", "event", ".", "target", "||", "event", ".", "srcElement", ";", "event", ".", "preventDefault", "=", "event", ".", "preventDefault", "||", "function", "(", ")", "{", "event", ".", "returnValue", "=", "false", ";", "}", ";", "event", ".", "stopPropagation", "=", "event", ".", "stopPropagation", "||", "function", "(", ")", "{", "event", ".", "cancelBubble", "=", "true", ";", "}", ";", "event", ".", "key", "=", "(", "event", ".", "which", "+", "1", "||", "event", ".", "keyCode", "+", "1", ")", "-", "1", "||", "0", ";", "return", "event", ";", "}" ]
Adapt an native IE event to a new event by monkey patching it
[ "Adapt", "an", "native", "IE", "event", "to", "a", "new", "event", "by", "monkey", "patching", "it" ]
e97a7f73343101ff11f4e73bf6edfb5e1544c1f9
https://github.com/marko-js/marko-widgets/blob/e97a7f73343101ff11f4e73bf6edfb5e1544c1f9/lib/addEventListener.js#L57-L73
21,388
mad-gooze/Leaflet.Arc
src/leaflet-arc.js
_createLatLngs
function _createLatLngs(line, from) { if (line.geometries[0] && line.geometries[0].coords[0]) { /** * stores how many times arc is broken over 180 longitude * @type {number} */ let wrap = from.lng - line.geometries[0].coords[0][0] - 360; return line.geometries .map(subLine => { wrap += 360; return subLine.coords.map(point => L.latLng([point[1], point[0] + wrap])); }) .reduce((all, latlngs) => all.concat(latlngs)); } else { return []; } }
javascript
function _createLatLngs(line, from) { if (line.geometries[0] && line.geometries[0].coords[0]) { /** * stores how many times arc is broken over 180 longitude * @type {number} */ let wrap = from.lng - line.geometries[0].coords[0][0] - 360; return line.geometries .map(subLine => { wrap += 360; return subLine.coords.map(point => L.latLng([point[1], point[0] + wrap])); }) .reduce((all, latlngs) => all.concat(latlngs)); } else { return []; } }
[ "function", "_createLatLngs", "(", "line", ",", "from", ")", "{", "if", "(", "line", ".", "geometries", "[", "0", "]", "&&", "line", ".", "geometries", "[", "0", "]", ".", "coords", "[", "0", "]", ")", "{", "/**\n * stores how many times arc is broken over 180 longitude\n * @type {number}\n */", "let", "wrap", "=", "from", ".", "lng", "-", "line", ".", "geometries", "[", "0", "]", ".", "coords", "[", "0", "]", "[", "0", "]", "-", "360", ";", "return", "line", ".", "geometries", ".", "map", "(", "subLine", "=>", "{", "wrap", "+=", "360", ";", "return", "subLine", ".", "coords", ".", "map", "(", "point", "=>", "L", ".", "latLng", "(", "[", "point", "[", "1", "]", ",", "point", "[", "0", "]", "+", "wrap", "]", ")", ")", ";", "}", ")", ".", "reduce", "(", "(", "all", ",", "latlngs", ")", "=>", "all", ".", "concat", "(", "latlngs", ")", ")", ";", "}", "else", "{", "return", "[", "]", ";", "}", "}" ]
Create array of L.LatLng objects from line produced by arc.js @param {object} line @param {L.LatLng} from @private @returns {Array}
[ "Create", "array", "of", "L", ".", "LatLng", "objects", "from", "line", "produced", "by", "arc", ".", "js" ]
edaef40860b32ca22dfed8abd8c96d504d190d19
https://github.com/mad-gooze/Leaflet.Arc/blob/edaef40860b32ca22dfed8abd8c96d504d190d19/src/leaflet-arc.js#L20-L37
21,389
DynamoMTL/shopify-pipeline
lib/prompt-if-main-theme.js
promptIfMainTheme
function promptIfMainTheme(env) { return new Promise((resolve, reject) => { const c = config.shopify[env] if (!c.api_key) { console.log(chalk.yellow(`The "${env}" environment in config/shopify.yml does not specify an "api_key". Skipping check for if is main theme.`)) resolve() return } // c.theme_id is live or equal to mainThemeId if (c.theme_id === 'live' || (mainThemeId && mainThemeId === c.theme_id)) { const question = 'You are about to deploy to the main theme. Continue ?' prompt(question, false).then((isYes) => { if (isYes) { resolve() return } reject('Aborting. You aborted the deploy.') }) return } // we already have a mainThemeId and it's not c.theme_id if (mainThemeId && mainThemeId !== c.theme_id) { resolve() return } fetchMainThemeId(env) .then((id) => { mainThemeId = id promptIfMainTheme(env).then(resolve).catch(reject) }) .catch(reject) }) }
javascript
function promptIfMainTheme(env) { return new Promise((resolve, reject) => { const c = config.shopify[env] if (!c.api_key) { console.log(chalk.yellow(`The "${env}" environment in config/shopify.yml does not specify an "api_key". Skipping check for if is main theme.`)) resolve() return } // c.theme_id is live or equal to mainThemeId if (c.theme_id === 'live' || (mainThemeId && mainThemeId === c.theme_id)) { const question = 'You are about to deploy to the main theme. Continue ?' prompt(question, false).then((isYes) => { if (isYes) { resolve() return } reject('Aborting. You aborted the deploy.') }) return } // we already have a mainThemeId and it's not c.theme_id if (mainThemeId && mainThemeId !== c.theme_id) { resolve() return } fetchMainThemeId(env) .then((id) => { mainThemeId = id promptIfMainTheme(env).then(resolve).catch(reject) }) .catch(reject) }) }
[ "function", "promptIfMainTheme", "(", "env", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "c", "=", "config", ".", "shopify", "[", "env", "]", "if", "(", "!", "c", ".", "api_key", ")", "{", "console", ".", "log", "(", "chalk", ".", "yellow", "(", "`", "${", "env", "}", "`", ")", ")", "resolve", "(", ")", "return", "}", "// c.theme_id is live or equal to mainThemeId", "if", "(", "c", ".", "theme_id", "===", "'live'", "||", "(", "mainThemeId", "&&", "mainThemeId", "===", "c", ".", "theme_id", ")", ")", "{", "const", "question", "=", "'You are about to deploy to the main theme. Continue ?'", "prompt", "(", "question", ",", "false", ")", ".", "then", "(", "(", "isYes", ")", "=>", "{", "if", "(", "isYes", ")", "{", "resolve", "(", ")", "return", "}", "reject", "(", "'Aborting. You aborted the deploy.'", ")", "}", ")", "return", "}", "// we already have a mainThemeId and it's not c.theme_id", "if", "(", "mainThemeId", "&&", "mainThemeId", "!==", "c", ".", "theme_id", ")", "{", "resolve", "(", ")", "return", "}", "fetchMainThemeId", "(", "env", ")", ".", "then", "(", "(", "id", ")", "=>", "{", "mainThemeId", "=", "id", "promptIfMainTheme", "(", "env", ")", ".", "then", "(", "resolve", ")", ".", "catch", "(", "reject", ")", "}", ")", ".", "catch", "(", "reject", ")", "}", ")", "}" ]
Prompt the user to confirm if they are about to deploy to the main theme @param env String The environment to check against @return Promise Reason for abort or empty resolve
[ "Prompt", "the", "user", "to", "confirm", "if", "they", "are", "about", "to", "deploy", "to", "the", "main", "theme" ]
ca686c029dba787c48a664ff51d6de806697f98a
https://github.com/DynamoMTL/shopify-pipeline/blob/ca686c029dba787c48a664ff51d6de806697f98a/lib/prompt-if-main-theme.js#L68-L107
21,390
Multicolour/multicolour
lib/utils.js
hash_password
function hash_password(plain_text, salt, callback) { // Get the crypto library. const crypto = require("crypto") // These should be a *slow* as possible, higher = slower. // Slow it down until you tweak a bounce change. const password_iterations = process.env.PW_GEN_PW_ITERS || 4096 // Password length and algorithm. const password_length = process.env.PW_GEN_PW_LENGTH || 512 const password_algorithm = process.env.PW_GEN_PW_ALG || "sha256" // Create a hash, we're going to encrypt the password. // I wish Node had native support for good KDF functions // like bcrypt or scrypt but PBKDF2 is good for now. crypto.pbkdf2(plain_text, salt, password_iterations, password_length, password_algorithm, (err, key) => { // Move on. callback(key.toString("hex"), salt) }) }
javascript
function hash_password(plain_text, salt, callback) { // Get the crypto library. const crypto = require("crypto") // These should be a *slow* as possible, higher = slower. // Slow it down until you tweak a bounce change. const password_iterations = process.env.PW_GEN_PW_ITERS || 4096 // Password length and algorithm. const password_length = process.env.PW_GEN_PW_LENGTH || 512 const password_algorithm = process.env.PW_GEN_PW_ALG || "sha256" // Create a hash, we're going to encrypt the password. // I wish Node had native support for good KDF functions // like bcrypt or scrypt but PBKDF2 is good for now. crypto.pbkdf2(plain_text, salt, password_iterations, password_length, password_algorithm, (err, key) => { // Move on. callback(key.toString("hex"), salt) }) }
[ "function", "hash_password", "(", "plain_text", ",", "salt", ",", "callback", ")", "{", "// Get the crypto library.", "const", "crypto", "=", "require", "(", "\"crypto\"", ")", "// These should be a *slow* as possible, higher = slower.", "// Slow it down until you tweak a bounce change.", "const", "password_iterations", "=", "process", ".", "env", ".", "PW_GEN_PW_ITERS", "||", "4096", "// Password length and algorithm.", "const", "password_length", "=", "process", ".", "env", ".", "PW_GEN_PW_LENGTH", "||", "512", "const", "password_algorithm", "=", "process", ".", "env", ".", "PW_GEN_PW_ALG", "||", "\"sha256\"", "// Create a hash, we're going to encrypt the password.", "// I wish Node had native support for good KDF functions", "// like bcrypt or scrypt but PBKDF2 is good for now.", "crypto", ".", "pbkdf2", "(", "plain_text", ",", "salt", ",", "password_iterations", ",", "password_length", ",", "password_algorithm", ",", "(", "err", ",", "key", ")", "=>", "{", "// Move on.", "callback", "(", "key", ".", "toString", "(", "\"hex\"", ")", ",", "salt", ")", "}", ")", "}" ]
Hash a plain string with the salt and call the callback. @param {String} plain_text to hash. @param {String} salt to use during hash process. @param {Function} callback to execute with the new password. @return {void}
[ "Hash", "a", "plain", "string", "with", "the", "salt", "and", "call", "the", "callback", "." ]
fd4fb3454a928ab9829617be49ff341367252272
https://github.com/Multicolour/multicolour/blob/fd4fb3454a928ab9829617be49ff341367252272/lib/utils.js#L21-L40
21,391
Multicolour/multicolour
lib/utils.js
remove_null_undefined
function remove_null_undefined(object) { Object.keys(object).forEach(key => { if (object[key] === null || typeof object[key] === "undefined") { delete object[key] } }) return object }
javascript
function remove_null_undefined(object) { Object.keys(object).forEach(key => { if (object[key] === null || typeof object[key] === "undefined") { delete object[key] } }) return object }
[ "function", "remove_null_undefined", "(", "object", ")", "{", "Object", ".", "keys", "(", "object", ")", ".", "forEach", "(", "key", "=>", "{", "if", "(", "object", "[", "key", "]", "===", "null", "||", "typeof", "object", "[", "key", "]", "===", "\"undefined\"", ")", "{", "delete", "object", "[", "key", "]", "}", "}", ")", "return", "object", "}" ]
Remove any null or undefined values from an object and return it. @param {Object} object to remove empties from. @return {Object} object without empties.
[ "Remove", "any", "null", "or", "undefined", "values", "from", "an", "object", "and", "return", "it", "." ]
fd4fb3454a928ab9829617be49ff341367252272
https://github.com/Multicolour/multicolour/blob/fd4fb3454a928ab9829617be49ff341367252272/lib/utils.js#L48-L56
21,392
Multicolour/multicolour
lib/utils.js
get_related_columns
function get_related_columns(collection) { return Object.keys(collection.attributes) .filter(attribute => collection.attributes[attribute].collection || collection.attributes[attribute].model) }
javascript
function get_related_columns(collection) { return Object.keys(collection.attributes) .filter(attribute => collection.attributes[attribute].collection || collection.attributes[attribute].model) }
[ "function", "get_related_columns", "(", "collection", ")", "{", "return", "Object", ".", "keys", "(", "collection", ".", "attributes", ")", ".", "filter", "(", "attribute", "=>", "collection", ".", "attributes", "[", "attribute", "]", ".", "collection", "||", "collection", ".", "attributes", "[", "attribute", "]", ".", "model", ")", "}" ]
Get related column names from a collection. Does not include foreign key declarations. @param {Waterline.Collection} collection to get related attributes of. @return {Array<string>} array of related attribute names.
[ "Get", "related", "column", "names", "from", "a", "collection", ".", "Does", "not", "include", "foreign", "key", "declarations", "." ]
fd4fb3454a928ab9829617be49ff341367252272
https://github.com/Multicolour/multicolour/blob/fd4fb3454a928ab9829617be49ff341367252272/lib/utils.js#L65-L68
21,393
Multicolour/multicolour
lib/utils.js
compile_constraints
function compile_constraints(request, constraints) { const Constraints = require("./constraints") // Exit if there aren't any constraints. if (!constraints) return {} return new Constraints() .set_source(request) .set_rules(constraints) .compile() .results }
javascript
function compile_constraints(request, constraints) { const Constraints = require("./constraints") // Exit if there aren't any constraints. if (!constraints) return {} return new Constraints() .set_source(request) .set_rules(constraints) .compile() .results }
[ "function", "compile_constraints", "(", "request", ",", "constraints", ")", "{", "const", "Constraints", "=", "require", "(", "\"./constraints\"", ")", "// Exit if there aren't any constraints.", "if", "(", "!", "constraints", ")", "return", "{", "}", "return", "new", "Constraints", "(", ")", ".", "set_source", "(", "request", ")", ".", "set_rules", "(", "constraints", ")", ".", "compile", "(", ")", ".", "results", "}" ]
Compile any constraints and return an object. @param {Hapi.Request} request to the server. @param {Waterline.Collection} collection to get constraints from. @return {Object} compiled constraints.
[ "Compile", "any", "constraints", "and", "return", "an", "object", "." ]
fd4fb3454a928ab9829617be49ff341367252272
https://github.com/Multicolour/multicolour/blob/fd4fb3454a928ab9829617be49ff341367252272/lib/utils.js#L94-L106
21,394
Multicolour/multicolour
lib/cli/plugins/init.js
replace_env_values
function replace_env_values(val_in) { if (!val_in) return "" let val_out = val_in const matches = val_in.match(/\$\w+/g) if (matches) matches.forEach(env => { const value = process.env[env.substring(1, env.length)] val_out = value.replace(new RegExp(`${env}`, "g"), value) // eslint-disable-line }) return val_out }
javascript
function replace_env_values(val_in) { if (!val_in) return "" let val_out = val_in const matches = val_in.match(/\$\w+/g) if (matches) matches.forEach(env => { const value = process.env[env.substring(1, env.length)] val_out = value.replace(new RegExp(`${env}`, "g"), value) // eslint-disable-line }) return val_out }
[ "function", "replace_env_values", "(", "val_in", ")", "{", "if", "(", "!", "val_in", ")", "return", "\"\"", "let", "val_out", "=", "val_in", "const", "matches", "=", "val_in", ".", "match", "(", "/", "\\$\\w+", "/", "g", ")", "if", "(", "matches", ")", "matches", ".", "forEach", "(", "env", "=>", "{", "const", "value", "=", "process", ".", "env", "[", "env", ".", "substring", "(", "1", ",", "env", ".", "length", ")", "]", "val_out", "=", "value", ".", "replace", "(", "new", "RegExp", "(", "`", "${", "env", "}", "`", ",", "\"g\"", ")", ",", "value", ")", "// eslint-disable-line", "}", ")", "return", "val_out", "}" ]
Replace any environmentals that appear in the string. @param {string} val_in to do replace on. @return {string} String with replacements done.
[ "Replace", "any", "environmentals", "that", "appear", "in", "the", "string", "." ]
fd4fb3454a928ab9829617be49ff341367252272
https://github.com/Multicolour/multicolour/blob/fd4fb3454a928ab9829617be49ff341367252272/lib/cli/plugins/init.js#L28-L43
21,395
Multicolour/multicolour
lib/handlers/get.js
getJunctionTableFromModelAndRelatedColumn
function getJunctionTableFromModelAndRelatedColumn(model, parentTableName, relatedColumnTableName) { const junctionTableName = Object.keys(model.waterline.schema) .find(schemaName => { const tables = model.waterline.schema[schemaName].tables if (!tables) return false return tables[0] === parentTableName && tables[1] === relatedColumnTableName }) if (!junctionTableName) return false const junctionTableSchema = model.waterline.schema[junctionTableName] const junctionTableCollection = model.waterline.collections[junctionTableName] return { tableName: junctionTableName, tables: junctionTableSchema.tables, collection: junctionTableCollection, columns: Object.keys(junctionTableCollection.attributes).filter(name => name !== "id") } }
javascript
function getJunctionTableFromModelAndRelatedColumn(model, parentTableName, relatedColumnTableName) { const junctionTableName = Object.keys(model.waterline.schema) .find(schemaName => { const tables = model.waterline.schema[schemaName].tables if (!tables) return false return tables[0] === parentTableName && tables[1] === relatedColumnTableName }) if (!junctionTableName) return false const junctionTableSchema = model.waterline.schema[junctionTableName] const junctionTableCollection = model.waterline.collections[junctionTableName] return { tableName: junctionTableName, tables: junctionTableSchema.tables, collection: junctionTableCollection, columns: Object.keys(junctionTableCollection.attributes).filter(name => name !== "id") } }
[ "function", "getJunctionTableFromModelAndRelatedColumn", "(", "model", ",", "parentTableName", ",", "relatedColumnTableName", ")", "{", "const", "junctionTableName", "=", "Object", ".", "keys", "(", "model", ".", "waterline", ".", "schema", ")", ".", "find", "(", "schemaName", "=>", "{", "const", "tables", "=", "model", ".", "waterline", ".", "schema", "[", "schemaName", "]", ".", "tables", "if", "(", "!", "tables", ")", "return", "false", "return", "tables", "[", "0", "]", "===", "parentTableName", "&&", "tables", "[", "1", "]", "===", "relatedColumnTableName", "}", ")", "if", "(", "!", "junctionTableName", ")", "return", "false", "const", "junctionTableSchema", "=", "model", ".", "waterline", ".", "schema", "[", "junctionTableName", "]", "const", "junctionTableCollection", "=", "model", ".", "waterline", ".", "collections", "[", "junctionTableName", "]", "return", "{", "tableName", ":", "junctionTableName", ",", "tables", ":", "junctionTableSchema", ".", "tables", ",", "collection", ":", "junctionTableCollection", ",", "columns", ":", "Object", ".", "keys", "(", "junctionTableCollection", ".", "attributes", ")", ".", "filter", "(", "name", "=>", "name", "!==", "\"id\"", ")", "}", "}" ]
Get the junction table waterline generates for many-to-many related tables. @param { Waterline.Collection } model to get schemas from @param { string } parentTableName to check relationships @param { string } relatedColumnTableName to check relationships @return { Waterline.Collection | false } The junction table or undefined.
[ "Get", "the", "junction", "table", "waterline", "generates", "for", "many", "-", "to", "-", "many", "related", "tables", "." ]
fd4fb3454a928ab9829617be49ff341367252272
https://github.com/Multicolour/multicolour/blob/fd4fb3454a928ab9829617be49ff341367252272/lib/handlers/get.js#L61-L82
21,396
Multicolour/multicolour
lib/user-model.js
hash_password
function hash_password(values, next) { // If no password was provided, just move on and exit. if (!values.password || values.password.length > 1000) { return next() } this .findOne(values) .then(user => { // Create a salt for this user if they don't have one. const salt = user && user.salt ? user.salt : utils.create_salt() // We're going to encrypt the password. utils.hash_password(values.password, salt, (password, salt) => { // Apply the hash and salt to the inbound values. values.password = password.toString("hex") values.salt = salt values.requires_password = false // Move on. next() }) }) .catch(next) }
javascript
function hash_password(values, next) { // If no password was provided, just move on and exit. if (!values.password || values.password.length > 1000) { return next() } this .findOne(values) .then(user => { // Create a salt for this user if they don't have one. const salt = user && user.salt ? user.salt : utils.create_salt() // We're going to encrypt the password. utils.hash_password(values.password, salt, (password, salt) => { // Apply the hash and salt to the inbound values. values.password = password.toString("hex") values.salt = salt values.requires_password = false // Move on. next() }) }) .catch(next) }
[ "function", "hash_password", "(", "values", ",", "next", ")", "{", "// If no password was provided, just move on and exit.", "if", "(", "!", "values", ".", "password", "||", "values", ".", "password", ".", "length", ">", "1000", ")", "{", "return", "next", "(", ")", "}", "this", ".", "findOne", "(", "values", ")", ".", "then", "(", "user", "=>", "{", "// Create a salt for this user if they don't have one.", "const", "salt", "=", "user", "&&", "user", ".", "salt", "?", "user", ".", "salt", ":", "utils", ".", "create_salt", "(", ")", "// We're going to encrypt the password.", "utils", ".", "hash_password", "(", "values", ".", "password", ",", "salt", ",", "(", "password", ",", "salt", ")", "=>", "{", "// Apply the hash and salt to the inbound values.", "values", ".", "password", "=", "password", ".", "toString", "(", "\"hex\"", ")", "values", ".", "salt", "=", "salt", "values", ".", "requires_password", "=", "false", "// Move on.", "next", "(", ")", "}", ")", "}", ")", ".", "catch", "(", "next", ")", "}" ]
Hash a plain text password using PBKDF2 and SHA256. @param {Object} values to be written to the database. @param {Function} next callback, used to finish the operation. @return {void}
[ "Hash", "a", "plain", "text", "password", "using", "PBKDF2", "and", "SHA256", "." ]
fd4fb3454a928ab9829617be49ff341367252272
https://github.com/Multicolour/multicolour/blob/fd4fb3454a928ab9829617be49ff341367252272/lib/user-model.js#L12-L37
21,397
Multicolour/multicolour
lib/user-model.js
toJSON
function toJSON() { const model = this.toObject() delete model.password delete model.salt // Return the modified user object. return utils.remove_null_undefined(model) }
javascript
function toJSON() { const model = this.toObject() delete model.password delete model.salt // Return the modified user object. return utils.remove_null_undefined(model) }
[ "function", "toJSON", "(", ")", "{", "const", "model", "=", "this", ".", "toObject", "(", ")", "delete", "model", ".", "password", "delete", "model", ".", "salt", "// Return the modified user object.", "return", "utils", ".", "remove_null_undefined", "(", "model", ")", "}" ]
When returning a user from the database, we don't want the password to be exposed. @return {Object} modified user object.
[ "When", "returning", "a", "user", "from", "the", "database", "we", "don", "t", "want", "the", "password", "to", "be", "exposed", "." ]
fd4fb3454a928ab9829617be49ff341367252272
https://github.com/Multicolour/multicolour/blob/fd4fb3454a928ab9829617be49ff341367252272/lib/user-model.js#L87-L94
21,398
Multicolour/multicolour
lib/cli/init/content/blueprints/person.js
custom_routes
function custom_routes(hapi_server, multicolour) { // Joi is an amazing validation library, // read me at https://github.com/hapijs/joi/blob/v10.2.2/API.md const Joi = require("joi") // Set up a simple route that counts examples. hapi_server.route({ method: "GET", path: "/example/count", config: { // Get any auth config from core. auth: multicolour.get("server").request("auth_config"), // Add tags to appear in the /docs endpoint. tags: ["api", "example"], // Validate the params. validate: { // Get valid headers from Multicolour. headers: Joi.object( multicolour.get("server") .request("header_validator") .get() ).unknown(true) }, // Validate the response. response: { // Get the schema from Multicolour to validate the response. schema: Joi.object({ count: Joi.number().required(), message: Joi.string() }) .meta({className: "person_count"}) .label("person_count") }, handler: (request, reply) => { // `this` is the current model but only with // a full function () definition (no fat arrows) // on the custom_routes file. this.count(request.url.query) .then(count => reply({ count, message: "Try POST /person to increase this count result!" })) } } }) }
javascript
function custom_routes(hapi_server, multicolour) { // Joi is an amazing validation library, // read me at https://github.com/hapijs/joi/blob/v10.2.2/API.md const Joi = require("joi") // Set up a simple route that counts examples. hapi_server.route({ method: "GET", path: "/example/count", config: { // Get any auth config from core. auth: multicolour.get("server").request("auth_config"), // Add tags to appear in the /docs endpoint. tags: ["api", "example"], // Validate the params. validate: { // Get valid headers from Multicolour. headers: Joi.object( multicolour.get("server") .request("header_validator") .get() ).unknown(true) }, // Validate the response. response: { // Get the schema from Multicolour to validate the response. schema: Joi.object({ count: Joi.number().required(), message: Joi.string() }) .meta({className: "person_count"}) .label("person_count") }, handler: (request, reply) => { // `this` is the current model but only with // a full function () definition (no fat arrows) // on the custom_routes file. this.count(request.url.query) .then(count => reply({ count, message: "Try POST /person to increase this count result!" })) } } }) }
[ "function", "custom_routes", "(", "hapi_server", ",", "multicolour", ")", "{", "// Joi is an amazing validation library,", "// read me at https://github.com/hapijs/joi/blob/v10.2.2/API.md", "const", "Joi", "=", "require", "(", "\"joi\"", ")", "// Set up a simple route that counts examples.", "hapi_server", ".", "route", "(", "{", "method", ":", "\"GET\"", ",", "path", ":", "\"/example/count\"", ",", "config", ":", "{", "// Get any auth config from core.", "auth", ":", "multicolour", ".", "get", "(", "\"server\"", ")", ".", "request", "(", "\"auth_config\"", ")", ",", "// Add tags to appear in the /docs endpoint.", "tags", ":", "[", "\"api\"", ",", "\"example\"", "]", ",", "// Validate the params.", "validate", ":", "{", "// Get valid headers from Multicolour.", "headers", ":", "Joi", ".", "object", "(", "multicolour", ".", "get", "(", "\"server\"", ")", ".", "request", "(", "\"header_validator\"", ")", ".", "get", "(", ")", ")", ".", "unknown", "(", "true", ")", "}", ",", "// Validate the response.", "response", ":", "{", "// Get the schema from Multicolour to validate the response.", "schema", ":", "Joi", ".", "object", "(", "{", "count", ":", "Joi", ".", "number", "(", ")", ".", "required", "(", ")", ",", "message", ":", "Joi", ".", "string", "(", ")", "}", ")", ".", "meta", "(", "{", "className", ":", "\"person_count\"", "}", ")", ".", "label", "(", "\"person_count\"", ")", "}", ",", "handler", ":", "(", "request", ",", "reply", ")", "=>", "{", "// `this` is the current model but only with", "// a full function () definition (no fat arrows)", "// on the custom_routes file.", "this", ".", "count", "(", "request", ".", "url", ".", "query", ")", ".", "then", "(", "count", "=>", "reply", "(", "{", "count", ",", "message", ":", "\"Try POST /person to increase this count result!\"", "}", ")", ")", "}", "}", "}", ")", "}" ]
We can add any custom routes we like by defining them in the custom_routes function. There's no magic, no trade offs you simply write the code you would normally write here. Multicolour will not modify, read or actually do anything to your custom code, it's yours and yours only. @param {Hapi} hapi_server running your API. @param {Multicolour} multicolour instance this REST API is running in. @return {void}
[ "We", "can", "add", "any", "custom", "routes", "we", "like", "by", "defining", "them", "in", "the", "custom_routes", "function", "." ]
fd4fb3454a928ab9829617be49ff341367252272
https://github.com/Multicolour/multicolour/blob/fd4fb3454a928ab9829617be49ff341367252272/lib/cli/init/content/blueprints/person.js#L133-L182
21,399
bitcoinjs/coinselect
stats/strategies.js
random
function random (utxos, outputs, feeRate) { utxos = shuffle(utxos) return accumulative(utxos, outputs, feeRate) }
javascript
function random (utxos, outputs, feeRate) { utxos = shuffle(utxos) return accumulative(utxos, outputs, feeRate) }
[ "function", "random", "(", "utxos", ",", "outputs", ",", "feeRate", ")", "{", "utxos", "=", "shuffle", "(", "utxos", ")", "return", "accumulative", "(", "utxos", ",", "outputs", ",", "feeRate", ")", "}" ]
similar to bitcoind
[ "similar", "to", "bitcoind" ]
288f24d221e5f1e5beac883043cc706914b2b2bd
https://github.com/bitcoinjs/coinselect/blob/288f24d221e5f1e5beac883043cc706914b2b2bd/stats/strategies.js#L75-L79