code
stringlengths
28
313k
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
74
language
stringclasses
1 value
repo
stringlengths
5
60
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
function filterLeaks(ok, globals) { return filter(globals, function(key){ // Firefox and Chrome exposes iframes as index inside the window object if (/^d+/.test(key)) return false; // in firefox // if runner runs in an iframe, this iframe's window.getInterface method not init at first // it is assigned in some seconds if (global.navigator && /^getInterface/.test(key)) return false; // an iframe could be approached by window[iframeIndex] // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak if (global.navigator && /^\d+/.test(key)) return false; // Opera and IE expose global variables for HTML element IDs (issue #243) if (/^mocha-/.test(key)) return false; var matched = filter(ok, function(ok){ if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]); return key == ok; }); return matched.length == 0 && (!global.navigator || 'onerror' !== key); }); }
Filter leaks with the given globals flagged as `ok`. @param {Array} ok @param {Array} globals @return {Array} @api private
filterLeaks
javascript
alibaba/f2etest
f2etest-web/public/demo/lib/mocha.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/demo/lib/mocha.js
MIT
function Suite(title, ctx) { this.title = title; this.ctx = ctx; this.suites = []; this.tests = []; this.pending = false; this._beforeEach = []; this._beforeAll = []; this._afterEach = []; this._afterAll = []; this.root = !title; this._timeout = 2000; this._slow = 75; this._bail = false; }
Initialize a new `Suite` with the given `title` and `ctx`. @param {String} title @param {Context} ctx @api private
Suite
javascript
alibaba/f2etest
f2etest-web/public/demo/lib/mocha.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/demo/lib/mocha.js
MIT
function Test(title, fn) { Runnable.call(this, title, fn); this.pending = !fn; this.type = 'test'; }
Initialize a new `Test` with the given `title` and callback `fn`. @param {String} title @param {Function} fn @api private
Test
javascript
alibaba/f2etest
f2etest-web/public/demo/lib/mocha.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/demo/lib/mocha.js
MIT
function highlight(js) { return js .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>') .replace(/('.*?')/gm, '<span class="string">$1</span>') .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>') .replace(/(\d+)/gm, '<span class="number">$1</span>') .replace(/\bnew *(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>') .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>') }
Highlight the given string of `js`. @param {String} js @return {String} @api private
highlight
javascript
alibaba/f2etest
f2etest-web/public/demo/lib/mocha.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/demo/lib/mocha.js
MIT
errorString = function( error ) { var name, message, errorString = error.toString(); if ( errorString.substring( 0, 7 ) === "[object" ) { name = error.name ? error.name.toString() : "Error"; message = error.message ? error.message.toString() : ""; if ( name && message ) { return name + ": " + message; } else if ( name ) { return name; } else if ( message ) { return message; } else { return "Error"; } } else { return errorString; } }
Provides a normalized error string, correcting an issue with IE 7 (and prior) where Error.prototype.toString is not properly implemented Based on http://es5.github.com/#x15.11.4.4 @param {String|Error} error @return {String} error message
errorString
javascript
alibaba/f2etest
f2etest-web/public/demo/lib/qunit-1.14.0.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/demo/lib/qunit-1.14.0.js
MIT
objectValues = function( obj ) { // Grunt 0.3.x uses an older version of jshint that still has jshint/jshint#392. /*jshint newcap: false */ var key, val, vals = QUnit.is( "array", obj ) ? [] : {}; for ( key in obj ) { if ( hasOwn.call( obj, key ) ) { val = obj[key]; vals[key] = val === Object(val) ? objectValues(val) : val; } } return vals; }
Makes a clone of an object using only Array or Object as base, and copies over the own enumerable properties. @param {Object} obj @return {Object} New object with only the own properties (recursively).
objectValues
javascript
alibaba/f2etest
f2etest-web/public/demo/lib/qunit-1.14.0.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/demo/lib/qunit-1.14.0.js
MIT
function validTest( test ) { var include, filter = config.filter && config.filter.toLowerCase(), module = config.module && config.module.toLowerCase(), fullName = ( test.module + ": " + test.testName ).toLowerCase(); // Internally-generated tests are always valid if ( test.callback && test.callback.validTest === validTest ) { delete test.callback.validTest; return true; } if ( config.testNumber.length > 0 ) { if ( inArray( test.testNumber, config.testNumber ) < 0 ) { return false; } } if ( module && ( !test.module || test.module.toLowerCase() !== module ) ) { return false; } if ( !filter ) { return true; } include = filter.charAt( 0 ) !== "!"; if ( !include ) { filter = filter.slice( 1 ); } // If the filter matches, we need to honour include if ( fullName.indexOf( filter ) !== -1 ) { return include; } // Otherwise, do the opposite return !include; }
@return Boolean: true if this test should be ran
validTest
javascript
alibaba/f2etest
f2etest-web/public/demo/lib/qunit-1.14.0.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/demo/lib/qunit-1.14.0.js
MIT
function escapeText( s ) { if ( !s ) { return ""; } s = s + ""; // Both single quotes and double quotes (for attributes) return s.replace( /['"<>&]/g, function( s ) { switch( s ) { case "'": return "&#039;"; case "\"": return "&quot;"; case "<": return "&lt;"; case ">": return "&gt;"; case "&": return "&amp;"; } }); }
Escape text for attribute or text content.
escapeText
javascript
alibaba/f2etest
f2etest-web/public/demo/lib/qunit-1.14.0.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/demo/lib/qunit-1.14.0.js
MIT
function addEvent( elem, type, fn ) { if ( elem.addEventListener ) { // Standards-based browsers elem.addEventListener( type, fn, false ); } else if ( elem.attachEvent ) { // support: IE <9 elem.attachEvent( "on" + type, fn ); } else { // Caller must ensure support for event listeners is present throw new Error( "addEvent() was called in a context without event listener support" ); } }
@param {HTMLElement} elem @param {string} type @param {Function} fn
addEvent
javascript
alibaba/f2etest
f2etest-web/public/demo/lib/qunit-1.14.0.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/demo/lib/qunit-1.14.0.js
MIT
function addEvents( elems, type, fn ) { var i = elems.length; while ( i-- ) { addEvent( elems[i], type, fn ); } }
@param {Array|NodeList} elems @param {string} type @param {Function} fn
addEvents
javascript
alibaba/f2etest
f2etest-web/public/demo/lib/qunit-1.14.0.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/demo/lib/qunit-1.14.0.js
MIT
function run() { // each of these can by async synchronize(function() { test.setup(); }); synchronize(function() { test.run(); }); synchronize(function() { test.teardown(); }); synchronize(function() { test.finish(); }); }
Expose the current test environment. @deprecated since 1.12.0: Use QUnit.config.current.testEnvironment instead.
run
javascript
alibaba/f2etest
f2etest-web/public/demo/lib/qunit-1.14.0.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/demo/lib/qunit-1.14.0.js
MIT
function bindCallbacks( o, callbacks, args ) { var prop = QUnit.objectType( o ); if ( prop ) { if ( QUnit.objectType( callbacks[ prop ] ) === "function" ) { return callbacks[ prop ].apply( callbacks, args ); } else { return callbacks[ prop ]; // or undefined } } }
@deprecated since 1.0.0, replaced with error pushes since 1.3.0 Kept to avoid TypeErrors for undefined methods.
bindCallbacks
javascript
alibaba/f2etest
f2etest-web/public/demo/lib/qunit-1.14.0.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/demo/lib/qunit-1.14.0.js
MIT
function jscoverage_init(w) { try { // in Safari, "import" is a syntax error Components.utils['import']('resource://app/modules/jscoverage.jsm'); jscoverage_isInvertedMode = true; return; } catch (e) {} // check if we are in inverted mode if (w.opener) { try { if (w.opener.top._$jscoverage) { jscoverage_isInvertedMode = true; if (! w._$jscoverage) { w._$jscoverage = w.opener.top._$jscoverage; } } else { jscoverage_isInvertedMode = false; } } catch (e) { try { if (w.opener._$jscoverage) { jscoverage_isInvertedMode = true; if (! w._$jscoverage) { w._$jscoverage = w.opener._$jscoverage; } } else { jscoverage_isInvertedMode = false; } } catch (e2) { jscoverage_isInvertedMode = false; } } } else { jscoverage_isInvertedMode = false; } if (! jscoverage_isInvertedMode) { if (! w._$jscoverage) { w._$jscoverage = {}; } } }
Initializes the _$jscoverage object in a window. This should be the first function called in the page. @param w this should always be the global window object
jscoverage_init
javascript
alibaba/f2etest
f2etest-web/public/jscover/jscoverage.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/jscover/jscoverage.js
MIT
function jscoverage_beginLengthyOperation() { jscoverage_inLengthyOperation = true; /* blacklist buggy browsers */ //#JSCOVERAGE_IF if (! /Opera|WebKit/.test(navigator.userAgent)) { /* Change the cursor style of each element. Note that changing the class of the element (to one with a busy cursor) is buggy in IE. */ var tabs = document.getElementById('tabs').getElementsByTagName('div'); var i; for (i = 0; i < tabs.length; i++) { tabs.item(i).style.cursor = 'wait'; } } }
Indicates visually that a lengthy operation has begun. The progress bar is displayed, and the cursor is changed to busy (on browsers which support this).
jscoverage_beginLengthyOperation
javascript
alibaba/f2etest
f2etest-web/public/jscover/jscoverage.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/jscover/jscoverage.js
MIT
function jscoverage_endLengthyOperation() { setTimeout(function() { jscoverage_inLengthyOperation = false; var tabs = document.getElementById('tabs').getElementsByTagName('div'); var i; for (i = 0; i < tabs.length; i++) { tabs.item(i).style.cursor = ''; } }, 50); }
Removes the progress bar and busy cursor.
jscoverage_endLengthyOperation
javascript
alibaba/f2etest
f2etest-web/public/jscover/jscoverage.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/jscover/jscoverage.js
MIT
function jscoverage_getBooleanValue(s) { s = s.toLowerCase(); if (s === 'false' || s === 'f' || s === 'no' || s === 'n' || s === 'off' || s === '0') { return false; } return true; }
Returns the boolean value of a string. Values 'false', 'f', 'no', 'n', 'off', and '0' (upper or lower case) are false. @param s the string @return a boolean value
jscoverage_getBooleanValue
javascript
alibaba/f2etest
f2etest-web/public/jscover/jscoverage.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/jscover/jscoverage.js
MIT
function jscoverage_initTabContents(queryString) { var showMissingColumn = false; var url = null; var windowURL = null; var parameters, parameter, i, index, name, value; if (queryString.length > 0) { // chop off the question mark queryString = queryString.substring(1); parameters = queryString.split(/&|;/); for (i = 0; i < parameters.length; i++) { parameter = parameters[i]; index = parameter.indexOf('='); if (index === -1) { // still works with old syntax url = decodeURIComponent(parameter); } else { name = parameter.substr(0, index); value = decodeURIComponent(parameter.substr(index + 1)); if (name === 'missing' || name === 'm') { showMissingColumn = jscoverage_getBooleanValue(value); } else if (name === 'url' || name === 'u' || name === 'frame' || name === 'f') { url = value; } else if (name === 'window' || name === 'w') { windowURL = value; } } } } var checkbox = document.getElementById('checkbox'); checkbox.checked = showMissingColumn; if (showMissingColumn) { jscoverage_appendMissingColumn(); } var isValidURL = function (url) { var result = jscoverage_isValidURL(url); if (! result) { alert('Invalid URL: ' + url); } return result; }; if (url !== null && isValidURL(url)) { // this will automatically propagate to the input field frames[0].location = url; } else if (windowURL !== null && isValidURL(windowURL)) { window.open(windowURL); } // if the browser tab is absent, we have to initialize the summary tab if (! document.getElementById('browserTab')) { jscoverage_recalculateSummaryTab(); } }
Initializes the contents of the tabs. This sets the initial values of the input field and iframe in the "Browser" tab and the checkbox in the "Summary" tab. @param queryString this should always be location.search
jscoverage_initTabContents
javascript
alibaba/f2etest
f2etest-web/public/jscover/jscoverage.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/jscover/jscoverage.js
MIT
function jscoverage_get(file, line) { if (jscoverage_inLengthyOperation) { return; } jscoverage_beginLengthyOperation(); setTimeout(function() { var sourceDiv = document.getElementById('sourceDiv'); sourceDiv.innerHTML = ''; jscoverage_selectTab('sourceTab'); if (file === jscoverage_currentFile) { jscoverage_currentLine = line; jscoverage_recalculateSourceTab(); } else { if (jscoverage_currentFile === null) { var tab = document.getElementById('sourceTab'); tab.className = ''; tab.onclick = jscoverage_tab_click; } jscoverage_currentFile = file; jscoverage_currentLine = line || 1; // when changing the source, always scroll to top var fileDiv = document.getElementById('fileDiv'); fileDiv.innerHTML = jscoverage_currentFile; jscoverage_recalculateSourceTab(); return; } }, 50); }
Loads the given file (and optional line) in the source tab.
jscoverage_get
javascript
alibaba/f2etest
f2etest-web/public/jscover/jscoverage.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/jscover/jscoverage.js
MIT
function jscoverage_recalculateSourceTab() { if (! jscoverage_currentFile) { jscoverage_endLengthyOperation(); return; } setTimeout(jscoverage_makeTable, 0); }
Calculates coverage statistics for the current source file.
jscoverage_recalculateSourceTab
javascript
alibaba/f2etest
f2etest-web/public/jscover/jscoverage.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/jscover/jscoverage.js
MIT
function jscoverage_initTabControl() { var tabs = document.getElementById('tabs'); var i; var child; var tabNum = 0; for (i = 0; i < tabs.childNodes.length; i++) { child = tabs.childNodes.item(i); if (child.nodeType === 1) { if (child.className !== 'disabled') { child.onclick = jscoverage_tab_click; } tabNum++; } } jscoverage_selectTab(0); }
Initializes the tab control. This function must be called when the document is loaded.
jscoverage_initTabControl
javascript
alibaba/f2etest
f2etest-web/public/jscover/jscoverage.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/jscover/jscoverage.js
MIT
function jscoverage_selectTab(tab) { if (typeof tab !== 'number') { tab = jscoverage_tabIndexOf(tab); } var tabs = document.getElementById('tabs'); var tabPages = document.getElementById('tabPages'); var nodeList; var tabNum; var i; var node; nodeList = tabs.childNodes; tabNum = 0; for (i = 0; i < nodeList.length; i++) { node = nodeList.item(i); if (node.nodeType !== 1) { continue; } if (node.className !== 'disabled') { if (tabNum === tab) { node.className = 'selected'; } else { node.className = ''; } } tabNum++; } nodeList = tabPages.childNodes; tabNum = 0; for (i = 0; i < nodeList.length; i++) { node = nodeList.item(i); if (node.nodeType !== 1) { continue; } if (tabNum === tab) { node.className = 'selected TabPage'; } else { node.className = 'TabPage'; } tabNum++; } }
Selects a tab. @param tab the integer index of the tab (0, 1, 2, or 3) OR the ID of the tab element OR the tab element itself
jscoverage_selectTab
javascript
alibaba/f2etest
f2etest-web/public/jscover/jscoverage.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/jscover/jscoverage.js
MIT
function jscoverage_tabIndexOf(tab) { if (typeof tab === 'string') { tab = document.getElementById(tab); } var tabs = document.getElementById('tabs'); var i; var child; var tabNum = 0; for (i = 0; i < tabs.childNodes.length; i++) { child = tabs.childNodes.item(i); if (child.nodeType === 1) { if (child === tab) { return tabNum; } tabNum++; } } //#JSCOVERAGE_IF 0 throw "Tab not found"; //#JSCOVERAGE_ENDIF }
Returns an integer (0, 1, 2, or 3) representing the index of a given tab. @param tab the ID of the tab element OR the tab element itself
jscoverage_tabIndexOf
javascript
alibaba/f2etest
f2etest-web/public/jscover/jscoverage.js
https://github.com/alibaba/f2etest/blob/master/f2etest-web/public/jscover/jscoverage.js
MIT
constructor() { this.emitter = createNanoEvents(); /** @type {HTMLFormElement | null} */ this.container = null; domReady.then(() => { this.container = document.querySelector('.view-toggler'); // stop browsers remembering previous form state this.container.output[0].checked = true; this.container.addEventListener('change', () => { this.emitter.emit('change', { value: this.container.output.value, }); }); }); }
Tabs that toggle between showing the SVG image and XML markup.
constructor
javascript
jakearchibald/svgomg
src/js/page/ui/view-toggler.js
https://github.com/jakearchibald/svgomg/blob/master/src/js/page/ui/view-toggler.js
MIT
replyByType = function (name, json, request, h) { if (request.headers.accept === 'application/xml') { return h.response(Js2xmlparser(name, json)).type('application/xml'); } return h.response(json).type('application/json'); }
allows a reply to have either a json or xml response @param {String} name @param {Object} json @param {Object} request @param {Object} reply
replyByType
javascript
hapi-swagger/hapi-swagger
examples/assets/routes-complex.js
https://github.com/hapi-swagger/hapi-swagger/blob/master/examples/assets/routes-complex.js
MIT
defaultHandler = function (request, h) { const sum = { id: 'x78P9c', a: 5, b: 5, operator: '+', equals: 10, created: '2015-12-01', modified: '2015-12-01' }; const list = { items: [sum], count: 1, pageSize: 10, page: 1, pageCount: 1 }; if (request.path.indexOf('/v1/sum/') > -1) { return replyByType('result', { equals: 43 }, request, h); } if (request.path === '/v1/store/' && request.method === 'get') { return replyByType('list', list, request, h); } return replyByType('sum', sum, request, h); }
mock handler for routes @param {Object} request @param {Object} reply
defaultHandler
javascript
hapi-swagger/hapi-swagger
examples/assets/routes-complex.js
https://github.com/hapi-swagger/hapi-swagger/blob/master/examples/assets/routes-complex.js
MIT
appendDataContext = function (plugin, settings) { plugin.ext('onPostHandler', (request, h) => { const response = request.response; const routePrefix = plugin.realm.modifiers.route.prefix; // if the reply is a view add settings data into template system if (response.variety === 'view') { // skip if the request is not for this handler if (routePrefix && !request.path.startsWith(routePrefix)) { return h.continue; } // Added to fix bug that cannot yet be reproduced in test - REVIEW /* $lab:coverage:off$ */ if (!response.source.context) { response.source.context = {}; } /* $lab:coverage:on$ */ const prefixedSettings = Hoek.clone(settings); // append tags from document request to JSON request prefixedSettings.jsonPath = request.query.tags ? Utilities.appendQueryString(settings.jsonPath, 'tags', request.query.tags) : settings.jsonPath; if (routePrefix) { ['jsonPath', 'swaggerUIPath'].forEach((setting) => { prefixedSettings[setting] = routePrefix + prefixedSettings[setting]; }); } // Need JWT plugin to work with Hapi v17+ to test this again const prefix = findAPIKeyPrefix(settings); if (prefix) { prefixedSettings.keyPrefix = prefix; } prefixedSettings.stringified = JSON.stringify(prefixedSettings); response.source.context.hapiSwagger = prefixedSettings; } return h.continue; }); }
appends settings data in template context @param {Object} plugin @param {Object} settings @return {Object}
appendDataContext
javascript
hapi-swagger/hapi-swagger
lib/index.js
https://github.com/hapi-swagger/hapi-swagger/blob/master/lib/index.js
MIT
findAPIKeyPrefix = function (settings) { // Need JWT plugin to work with Hapi v17+ to test this again /* $lab:coverage:off$ */ let out = ''; if (settings.securityDefinitions) { Object.keys(settings.securityDefinitions).forEach((key) => { if (settings.securityDefinitions[key]['x-keyPrefix']) { out = settings.securityDefinitions[key]['x-keyPrefix']; } }); } return out; /* $lab:coverage:on$ */ }
finds any keyPrefix in securityDefinitions - also add x- to name @param {Object} settings @return {string}
findAPIKeyPrefix
javascript
hapi-swagger/hapi-swagger
lib/index.js
https://github.com/hapi-swagger/hapi-swagger/blob/master/lib/index.js
MIT
buildAlternativesArray = (schemas) => { return schemas .map((schema) => { const childMetaName = Utilities.getJoiMetaProperty(schema, 'swaggerLabel'); const altName = childMetaName || Utilities.getJoiLabel(schema) || name; //name, joiObj, parent, parameterType, useDefinitions, isAlt return this.parseProperty(altName, schema, property, parameterType, useDefinitions, true); }) .filter((obj) => obj); }
parse alternatives property @param {Object} property @param {Object} joiObj @param {string} name @param {string} parameterType @param {Boolean} useDefinitions @return {Object}
buildAlternativesArray
javascript
hapi-swagger/hapi-swagger
lib/properties.js
https://github.com/hapi-swagger/hapi-swagger/blob/master/lib/properties.js
MIT
tryRegexExec = function tryRegexExec(value) { try { regexExec.call(value); return true; } catch (e) { return false; } }
is passed item a regex @param {Object} obj @return {Boolean}
tryRegexExec
javascript
hapi-swagger/hapi-swagger
lib/utilities.js
https://github.com/hapi-swagger/hapi-swagger/blob/master/lib/utilities.js
MIT
makeCompareFunction = function (f, direction) { if (typeof f !== 'function') { const prop = f; // make unary function f = function (v1) { return v1[prop]; }; } if (f.length === 1) { // f is a unary function mapping a single item to its sort score const uf = f; f = function (v1, v2) { return uf(v1) < uf(v2) ? -1 : uf(v1) > uf(v2) ? 1 : 0; }; } if (direction === -1) { return function (v1, v2) { return -f(v1, v2); }; } return f; }
get chained functions for sorting @return {Function}
makeCompareFunction
javascript
hapi-swagger/hapi-swagger
lib/utilities.js
https://github.com/hapi-swagger/hapi-swagger/blob/master/lib/utilities.js
MIT
validateJWT = (decoded) => { if (!people[decoded.id]) { return { valid: false }; } return { valid: true }; }
creates a Hapi server using JWT auth @param {Object} swaggerOptions @param {Object} routes @param {Function} callback
validateJWT
javascript
hapi-swagger/hapi-swagger
test/helper.js
https://github.com/hapi-swagger/hapi-swagger/blob/master/test/helper.js
MIT
function px2dp(px) { return px * deviceW / basePx }
Sample React Native App https://github.com/facebook/react-native @flow
px2dp
javascript
ptomasroos/react-native-tab-navigator
example/TabDemo/launcher.js
https://github.com/ptomasroos/react-native-tab-navigator/blob/master/example/TabDemo/launcher.js
MIT
function parseTime(str) { if (!str) { return 0; } var strings = str.split(":"); var l = strings.length, i = l; var ms = 0, parsed; if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) { throw new Error("tick only understands numbers and 'h:m:s'"); } while (i--) { parsed = parseInt(strings[i], 10); if (parsed >= 60) { throw new Error("Invalid time " + str); } ms += parsed * Math.pow(60, (l - i - 1)); } return ms * 1000; }
Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into number of milliseconds. This is used to support human-readable strings passed to clock.tick()
parseTime
javascript
rowanmanning/joblint
build/test.js
https://github.com/rowanmanning/joblint/blob/master/build/test.js
MIT
function getEpoch(epoch) { if (!epoch) { return 0; } if (typeof epoch.getTime === "function") { return epoch.getTime(); } if (typeof epoch === "number") { return epoch; } throw new TypeError("now should be milliseconds since UNIX epoch"); }
Used to grok the `now` parameter to createClock.
getEpoch
javascript
rowanmanning/joblint
build/test.js
https://github.com/rowanmanning/joblint/blob/master/build/test.js
MIT
function isArguments(object) { if (getClass(object) === 'Arguments') { return true; } if (typeof object !== "object" || typeof object.length !== "number" || getClass(object) === "Array") { return false; } if (typeof object.callee == "function") { return true; } try { object[object.length] = 6; delete object[object.length]; } catch (e) { return true; } return false; }
@name samsam.isArguments @param Object object Returns ``true`` if ``object`` is an ``arguments`` object, ``false`` otherwise.
isArguments
javascript
rowanmanning/joblint
build/test.js
https://github.com/rowanmanning/joblint/blob/master/build/test.js
MIT
function isElement(object) { if (!object || object.nodeType !== 1 || !div) { return false; } try { object.appendChild(div); object.removeChild(div); } catch (e) { return false; } return true; }
@name samsam.isElement @param Object object Returns ``true`` if ``object`` is a DOM element node. Unlike Underscore.js/lodash, this function will return ``false`` if ``object`` is an *element-like* object, i.e. a regular object with a ``nodeType`` property that holds the value ``1``.
isElement
javascript
rowanmanning/joblint
build/test.js
https://github.com/rowanmanning/joblint/blob/master/build/test.js
MIT
function keys(object) { var ks = [], prop; for (prop in object) { if (o.hasOwnProperty.call(object, prop)) { ks.push(prop); } } return ks; }
@name samsam.keys @param Object object Return an array of own property names.
keys
javascript
rowanmanning/joblint
build/test.js
https://github.com/rowanmanning/joblint/blob/master/build/test.js
MIT
function isDate(value) { return typeof value.getTime == "function" && value.getTime() == value.valueOf(); }
@name samsam.isDate @param Object value Returns true if the object is a ``Date``, or *date-like*. Duck typing of date objects work by checking that the object has a ``getTime`` function whose return value equals the return value from the object's ``valueOf``.
isDate
javascript
rowanmanning/joblint
build/test.js
https://github.com/rowanmanning/joblint/blob/master/build/test.js
MIT
function isNegZero(value) { return value === 0 && 1 / value === -Infinity; }
@name samsam.isNegZero @param Object value Returns ``true`` if ``value`` is ``-0``.
isNegZero
javascript
rowanmanning/joblint
build/test.js
https://github.com/rowanmanning/joblint/blob/master/build/test.js
MIT
function identical(obj1, obj2) { if (obj1 === obj2 || (isNaN(obj1) && isNaN(obj2))) { return obj1 !== 0 || isNegZero(obj1) === isNegZero(obj2); } }
@name samsam.equal @param Object obj1 @param Object obj2 Returns ``true`` if two objects are strictly equal. Compared to ``===`` there are two exceptions: - NaN is considered equal to NaN - -0 and +0 are not considered equal
identical
javascript
rowanmanning/joblint
build/test.js
https://github.com/rowanmanning/joblint/blob/master/build/test.js
MIT
function deepEqualCyclic(obj1, obj2) { // used for cyclic comparison // contain already visited objects var objects1 = [], objects2 = [], // contain pathes (position in the object structure) // of the already visited objects // indexes same as in objects arrays paths1 = [], paths2 = [], // contains combinations of already compared objects // in the manner: { "$1['ref']$2['ref']": true } compared = {}; /** * used to check, if the value of a property is an object * (cyclic logic is only needed for objects) * only needed for cyclic logic */ function isObject(value) { if (typeof value === 'object' && value !== null && !(value instanceof Boolean) && !(value instanceof Date) && !(value instanceof Number) && !(value instanceof RegExp) && !(value instanceof String)) { return true; } return false; } /** * returns the index of the given object in the * given objects array, -1 if not contained * only needed for cyclic logic */ function getIndex(objects, obj) { var i; for (i = 0; i < objects.length; i++) { if (objects[i] === obj) { return i; } } return -1; } // does the recursion for the deep equal check return (function deepEqual(obj1, obj2, path1, path2) { var type1 = typeof obj1; var type2 = typeof obj2; // == null also matches undefined if (obj1 === obj2 || isNaN(obj1) || isNaN(obj2) || obj1 == null || obj2 == null || type1 !== "object" || type2 !== "object") { return identical(obj1, obj2); } // Elements are only equal if identical(expected, actual) if (isElement(obj1) || isElement(obj2)) { return false; } var isDate1 = isDate(obj1), isDate2 = isDate(obj2); if (isDate1 || isDate2) { if (!isDate1 || !isDate2 || obj1.getTime() !== obj2.getTime()) { return false; } } if (obj1 instanceof RegExp && obj2 instanceof RegExp) { if (obj1.toString() !== obj2.toString()) { return false; } } var class1 = getClass(obj1); var class2 = getClass(obj2); var keys1 = keys(obj1); var keys2 = keys(obj2); if (isArguments(obj1) || isArguments(obj2)) { if (obj1.length !== obj2.length) { return false; } } else { if (type1 !== type2 || class1 !== class2 || keys1.length !== keys2.length) { return false; } } var key, i, l, // following vars are used for the cyclic logic value1, value2, isObject1, isObject2, index1, index2, newPath1, newPath2; for (i = 0, l = keys1.length; i < l; i++) { key = keys1[i]; if (!o.hasOwnProperty.call(obj2, key)) { return false; } // Start of the cyclic logic value1 = obj1[key]; value2 = obj2[key]; isObject1 = isObject(value1); isObject2 = isObject(value2); // determine, if the objects were already visited // (it's faster to check for isObject first, than to // get -1 from getIndex for non objects) index1 = isObject1 ? getIndex(objects1, value1) : -1; index2 = isObject2 ? getIndex(objects2, value2) : -1; // determine the new pathes of the objects // - for non cyclic objects the current path will be extended // by current property name // - for cyclic objects the stored path is taken newPath1 = index1 !== -1 ? paths1[index1] : path1 + '[' + JSON.stringify(key) + ']'; newPath2 = index2 !== -1 ? paths2[index2] : path2 + '[' + JSON.stringify(key) + ']'; // stop recursion if current objects are already compared if (compared[newPath1 + newPath2]) { return true; } // remember the current objects and their pathes if (index1 === -1 && isObject1) { objects1.push(value1); paths1.push(newPath1); } if (index2 === -1 && isObject2) { objects2.push(value2); paths2.push(newPath2); } // remember that the current objects are already compared if (isObject1 && isObject2) { compared[newPath1 + newPath2] = true; } // End of cyclic logic // neither value1 nor value2 is a cycle // continue with next level if (!deepEqual(value1, value2, newPath1, newPath2)) { return false; } } return true; }(obj1, obj2, '$1', '$2')); }
@name samsam.deepEqual @param Object obj1 @param Object obj2 Deep equal comparison. Two values are "deep equal" if: - They are equal, according to samsam.identical - They are both date objects representing the same time - They are both arrays containing elements that are all deepEqual - They are objects with the same set of properties, and each property in ``obj1`` is deepEqual to the corresponding property in ``obj2`` Supports cyclic objects.
deepEqualCyclic
javascript
rowanmanning/joblint
build/test.js
https://github.com/rowanmanning/joblint/blob/master/build/test.js
MIT
function isObject(value) { if (typeof value === 'object' && value !== null && !(value instanceof Boolean) && !(value instanceof Date) && !(value instanceof Number) && !(value instanceof RegExp) && !(value instanceof String)) { return true; } return false; }
used to check, if the value of a property is an object (cyclic logic is only needed for objects) only needed for cyclic logic
isObject
javascript
rowanmanning/joblint
build/test.js
https://github.com/rowanmanning/joblint/blob/master/build/test.js
MIT
function getIndex(objects, obj) { var i; for (i = 0; i < objects.length; i++) { if (objects[i] === obj) { return i; } } return -1; }
returns the index of the given object in the given objects array, -1 if not contained only needed for cyclic logic
getIndex
javascript
rowanmanning/joblint
build/test.js
https://github.com/rowanmanning/joblint/blob/master/build/test.js
MIT
function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); }
Echos the value of a value. Trys to print the value out in the best way possible given the different types. @param {Object} obj The object to print out. @param {Object} opts Optional options object that alters the output.
inspect
javascript
rowanmanning/joblint
build/test.js
https://github.com/rowanmanning/joblint/blob/master/build/test.js
MIT
function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
Inherit the prototype methods from one constructor into another. The Function.prototype.inherits from lang.js rewritten as a standalone function (not on Function.prototype). NOTE: If this file is to be loaded during bootstrapping this function needs to be rewritten using some native functions as prototype setup using normal JavaScript does not work as expected during bootstrapping (see mirror.js in r114903). @param {function} ctor Constructor function which needs to inherit the prototype. @param {function} superCtor Constructor function to inherit prototype from.
hasOwnProperty
javascript
rowanmanning/joblint
build/test.js
https://github.com/rowanmanning/joblint/blob/master/build/test.js
MIT
getElementToNavigate(linkOnly = false) { const focusedElement = document.activeElement; // StartPage seems to still focus and change it to body when the page loads. if (focusedElement == null || focusedElement.localName === 'body') { if ( this.focusedIndex < 0 || this.focusedIndex >= this.searchResults.length ) { return null; } return this.searchResults[this.focusedIndex].anchor; } const isLink = focusedElement.localName === 'a' && focusedElement.hasAttribute('href'); if (!linkOnly || isLink) { return focusedElement; } }
Returns the element to click on upon navigation. The focused element in the document is preferred (if there is one) over the highlighted result. Note that the focused element does not have to be an anchor <a> element. @param {boolean} linkOnly If true the focused element is preferred only when it is a link with "href" attribute. @return {Element}
getElementToNavigate
javascript
infokiller/web-search-navigator
src/main.js
https://github.com/infokiller/web-search-navigator/blob/master/src/main.js
MIT
constructor(storage, defaultValues) { this.storage = storage; this.values = {}; this.defaultValues = defaultValues; }
@param {StorageArea} storage The storage area to which this section will write. @param {Object} defaultValues The default options. @constructor
constructor
javascript
infokiller/web-search-navigator
src/options.js
https://github.com/infokiller/web-search-navigator/blob/master/src/options.js
MIT
setSearchEnginePermission_ = async (checkbox) => { const urls = OPTIONAL_PERMISSIONS_URLS[checkbox.id]; if (checkbox.checked) { checkbox.checked = false; const granted = await browser.permissions.request({origins: urls}); checkbox.checked = granted; } else { browser.permissions.remove({origins: urls}); } }
Add other search engines domain on user input @param {Element} checkbox
setSearchEnginePermission_
javascript
infokiller/web-search-navigator
src/options_page.js
https://github.com/infokiller/web-search-navigator/blob/master/src/options_page.js
MIT
constructor( element, anchorSelector, highlightClass, highlightedElementSelector, containerSelector, ) { this.#element = element; this.#anchorSelector = anchorSelector; this.highlightClass = highlightClass; this.#highlightedElementSelector = highlightedElementSelector; this.#containerSelector = containerSelector; }
@param {Element} element @param {function|null} anchorSelector @param {string} highlightClass @param {function|null} highlightedElementSelector @param {function|null} containerSelector
constructor
javascript
infokiller/web-search-navigator
src/search_engines.js
https://github.com/infokiller/web-search-navigator/blob/master/src/search_engines.js
MIT
getSortedSearchResults = ( includedSearchResults, excludedNodeList = [], ) => { const excludedResultsSet = new Set(); for (const node of excludedNodeList) { excludedResultsSet.add(node); } const searchResults = []; for (const results of includedSearchResults) { for (const node of results.nodes) { const searchResult = new SearchResult( node, results.anchorSelector, results.highlightClass, results.highlightedElementSelector, results.containerSelector, ); const anchor = searchResult.anchor; // Use offsetParent to exclude hidden elements, see: // https://stackoverflow.com/a/21696585/1014208 if ( anchor != null && !excludedResultsSet.has(anchor) && anchor.offsetParent !== null ) { // Prevent adding the same node multiple times. excludedResultsSet.add(anchor); searchResults.push(searchResult); } } } // Sort searchResults by their document position. searchResults.sort((a, b) => { const position = a.anchor.compareDocumentPosition(b.anchor); if (position & Node.DOCUMENT_POSITION_FOLLOWING) { return -1; } else if (position & Node.DOCUMENT_POSITION_PRECEDING) { return 1; } else { return 0; } }); return searchResults; }
@param {Array} includedSearchResults An array of tuples. Each tuple contains collection of the search results optionally accompanied with their container selector. @constructor
getSortedSearchResults
javascript
infokiller/web-search-navigator
src/search_engines.js
https://github.com/infokiller/web-search-navigator/blob/master/src/search_engines.js
MIT
changeTools(period) { const searchParams = new URLSearchParams(window.location.search); // Use the last value of the tbs param in case there are multiple ones, // since the last one overrides the previous ones. const allTbsValues = searchParams.getAll('tbs'); const lastTbsValue = allTbsValues[allTbsValues.length - 1] || ''; const match = /(qdr:.|li:1)(,sbd:.)?/.exec(lastTbsValue); const currentPeriod = (match && match[1]) || ''; const currentSort = (match && match[2]) || ''; if (period === 'a') { searchParams.delete('tbs'); } else if (period) { let newTbs = ''; if (period === 'v') { if (currentPeriod === 'li:1') { newTbs = ''; } else { newTbs = 'li:1'; } } else { newTbs = `qdr:${period}`; } searchParams.set('tbs', `${newTbs}${currentSort}`); // Can't apply sort when not using period. } else if (currentPeriod) { searchParams.set( 'tbs', `${currentPeriod}` + (currentSort ? '' : ',sbd:1'), ); } const newSearchString = '?' + searchParams.toString(); if (newSearchString !== window.location.search) { window.location.search = newSearchString; } return false; }
Filter the results based on special properties @param {*} period, filter identifier. Accepted filter are : 'a' : all results 'h' : last hour 'd' : last day 'w' : last week 'm' : last month 'y' : last year 'v' : verbatim search null : toggle sort
changeTools
javascript
infokiller/web-search-navigator
src/search_engines.js
https://github.com/infokiller/web-search-navigator/blob/master/src/search_engines.js
MIT
invoke(id, args) { if (id === undefined) { return } const obj = this.callbacks[id] if (obj && isFunction(obj.callback)) { obj.callback(args) if (!obj.keep) { delete this.callbacks[id] } } }
[Container] triggerCallback -> [Service] invoke @param {*} id @param {*} args
invoke
javascript
didi/dimina
fe/packages/common/src/core/callback.js
https://github.com/didi/dimina/blob/master/fe/packages/common/src/core/callback.js
Apache-2.0
function invokeAPI(apiName, { params, bridgeId }) { window.__message.invoke({ type: 'invokeAPI', target: 'container', body: { name: apiName, bridgeId, params, }, }) }
https://developers.weixin.qq.com/miniprogram/dev/framework/view/wxml/event.html @param {*} methodName @param {*} param
invokeAPI
javascript
didi/dimina
fe/packages/components/src/common/events.js
https://github.com/didi/dimina/blob/master/fe/packages/components/src/common/events.js
Apache-2.0
function generateColorFromName(name) { // If name is empty, return a default color (Material Blue) if (!name || name.length === 0) { return '#2196F3' } // Use the hash code of the name as a seed for color generation let hash = 0 for (let i = 0; i < name.length; i++) { hash = ((hash << 5) - hash) + name.charCodeAt(i) hash |= 0 // Convert to 32bit integer } // Generate HSV color with consistent hue based on name // Use a limited range of saturation and value for visually pleasing colors const hue = Math.abs(hash % 360) const saturation = 0.7 + (Math.abs(hash % 3000) / 10000) // Range: 0.7-1.0 const value = 0.8 + (Math.abs(hash % 2000) / 10000) // Range: 0.8-1.0 // Convert HSV to RGB const rgbColor = hsvToRgb(hue, saturation, value) // Convert RGB to hex return rgbToHex(rgbColor[0], rgbColor[1], rgbColor[2]) }
Generates a consistent color based on the name's hash code @param {string} name - The name to generate a color from @returns {string} - A hex color code
generateColorFromName
javascript
didi/dimina
fe/packages/container/src/services/index.js
https://github.com/didi/dimina/blob/master/fe/packages/container/src/services/index.js
Apache-2.0
function hsvToRgb(h, s, v) { let r, g, b const i = Math.floor(h / 60) const f = h / 60 - i const p = v * (1 - s) const q = v * (1 - f * s) const t = v * (1 - (1 - f) * s) /* eslint-disable style/max-statements-per-line */ switch (i % 6) { case 0: r = v; g = t; b = p; break case 1: r = q; g = v; b = p; break case 2: r = p; g = v; b = t; break case 3: r = p; g = q; b = v; break case 4: r = t; g = p; b = v; break case 5: r = v; g = p; b = q; break } /* eslint-enable style/max-statements-per-line */ return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)] }
Converts HSV color values to RGB @param {number} h - Hue (0-360) @param {number} s - Saturation (0-1) @param {number} v - Value (0-1) @returns {number[]} - Array of [r, g, b] values (0-255)
hsvToRgb
javascript
didi/dimina
fe/packages/container/src/services/index.js
https://github.com/didi/dimina/blob/master/fe/packages/container/src/services/index.js
Apache-2.0
function rgbToHex(r, g, b) { return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}` }
Converts RGB values to a hex color string @param {number} r - Red (0-255) @param {number} g - Green (0-255) @param {number} b - Blue (0-255) @returns {string} - Hex color code
rgbToHex
javascript
didi/dimina
fe/packages/container/src/services/index.js
https://github.com/didi/dimina/blob/master/fe/packages/container/src/services/index.js
Apache-2.0
setInitialData(initialData) { for (const [path, data] of Object.entries(initialData)) { if (!data) { continue } const module = this.staticModules[path] if (!module) { continue } module.setInitialData(data) } }
serviceResourceLoaded && renderResourceLoaded -> [Container]resourceLoaded -> [Service]resourceLoaded -> [Service]initialDataReady -> [Container]initialDataReady -> [Render]setInitialData @param {*} initialData
setInitialData
javascript
didi/dimina
fe/packages/render/src/core/loader.js
https://github.com/didi/dimina/blob/master/fe/packages/render/src/core/loader.js
Apache-2.0
isElementReady(element) { if (!element) { return false } const rect = element.getBoundingClientRect() return rect.height > 0 || rect.width > 0 }
https://developers.weixin.qq.com/miniprogram/dev/api/wxml/NodesRef.fields.html
isElementReady
javascript
didi/dimina
fe/packages/render/src/core/runtime.js
https://github.com/didi/dimina/blob/master/fe/packages/render/src/core/runtime.js
Apache-2.0
function getSystemInfo(opts) { return new Promise((resolve) => { resolve(invokeAPI('getSystemInfo', opts)) }) }
https://developers.weixin.qq.com/miniprogram/dev/api/base/system/wx.getSystemInfo.html
getSystemInfo
javascript
didi/dimina
fe/packages/service/src/api/core/base/system/index.js
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/base/system/index.js
Apache-2.0
function getSystemInfoSync() { return invokeAPI('getSystemInfoSync') }
https://developers.weixin.qq.com/miniprogram/dev/api/base/system/wx.getSystemInfoSync.html
getSystemInfoSync
javascript
didi/dimina
fe/packages/service/src/api/core/base/system/index.js
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/base/system/index.js
Apache-2.0
function getSystemInfoAsync(opts) { invokeAPI('getSystemInfoAsync', opts) }
https://developers.weixin.qq.com/miniprogram/dev/api/base/system/wx.getSystemInfoAsync.html
getSystemInfoAsync
javascript
didi/dimina
fe/packages/service/src/api/core/base/system/index.js
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/base/system/index.js
Apache-2.0
function makePhoneCall(opts) { invokeAPI('makePhoneCall', opts) }
https://developers.weixin.qq.com/miniprogram/dev/api/device/phone/wx.makePhoneCall.html
makePhoneCall
javascript
didi/dimina
fe/packages/service/src/api/core/device/phone/index.js
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/device/phone/index.js
Apache-2.0
function scanCode(opts) { invokeAPI('scanCode', opts) }
https://developers.weixin.qq.com/miniprogram/dev/api/device/scan/wx.scanCode.html
scanCode
javascript
didi/dimina
fe/packages/service/src/api/core/device/scan/index.js
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/device/scan/index.js
Apache-2.0
function login(opts) { invokeAPI('login', opts) }
https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
login
javascript
didi/dimina
fe/packages/service/src/api/core/open-api/index.js
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/open-api/index.js
Apache-2.0
function setStorageSync(...opts) { invokeAPI('setStorageSync', opts) }
https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.setStorageSync.html
setStorageSync
javascript
didi/dimina
fe/packages/service/src/api/core/storage/index.js
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/storage/index.js
Apache-2.0
function removeStorageSync(...opts) { return invokeAPI('removeStorageSync', opts) }
https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.removeStorageSync.html
removeStorageSync
javascript
didi/dimina
fe/packages/service/src/api/core/storage/index.js
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/storage/index.js
Apache-2.0
function setStorage(opts) { invokeAPI('setStorage', opts) }
https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.setStorage.html
setStorage
javascript
didi/dimina
fe/packages/service/src/api/core/storage/index.js
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/storage/index.js
Apache-2.0
function getStorage(opts) { invokeAPI('getStorage', opts) }
https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.getStorage.html
getStorage
javascript
didi/dimina
fe/packages/service/src/api/core/storage/index.js
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/storage/index.js
Apache-2.0
function removeStorage(opts) { invokeAPI('removeStorage', opts) }
https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.removeStorage.html
removeStorage
javascript
didi/dimina
fe/packages/service/src/api/core/storage/index.js
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/storage/index.js
Apache-2.0
function getStorageInfoSync(...opts) { return invokeAPI('getStorageInfoSync', opts) }
https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.getStorageInfoSync.html
getStorageInfoSync
javascript
didi/dimina
fe/packages/service/src/api/core/storage/index.js
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/storage/index.js
Apache-2.0
function getStorageInfo(opts) { invokeAPI('getStorageInfo', opts) }
https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.getStorageInfo.html
getStorageInfo
javascript
didi/dimina
fe/packages/service/src/api/core/storage/index.js
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/storage/index.js
Apache-2.0
selectViewport() { return new NodesRef(this, router.getPageInfo().id, '', true) }
@param {*} selector @param {*} moduleId @param {*} single @param {*} fields @param {*} callback
selectViewport
javascript
didi/dimina
fe/packages/service/src/api/core/wxml/selector-query/index.js
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/wxml/selector-query/index.js
Apache-2.0
constructor(moduleInfo, extraInfo) { this.moduleInfo = moduleInfo this.extraInfo = extraInfo this.type = ComponentModule.type this.isComponent = this.extraInfo.component this.behaviors = this.moduleInfo.behaviors this.usingComponents = this.extraInfo.usingComponents this.noReferenceData = filterData(this.moduleInfo.data || {}) mergeBehaviors(this.moduleInfo, this.behaviors) }
@param {{data: object, lifetimes: object, pageLifetimes: object, methods: object, options: object, properties: object}} moduleInfo
constructor
javascript
didi/dimina
fe/packages/service/src/instance/component/component-module.js
https://github.com/didi/dimina/blob/master/fe/packages/service/src/instance/component/component-module.js
Apache-2.0
constructor(module, opts) { this.initd = false this.opts = opts if (opts.targetInfo) { this.id = opts.targetInfo.id this.dataset = opts.targetInfo.dataset this.__targetInfo__ = opts.targetInfo } this.is = opts.path this.renderer = 'webview' this.bridgeId = opts.bridgeId this.behaviors = module.behaviors this.data = cloneDeep(module.noReferenceData) this.__isComponent__ = module.isComponent this.__type__ = module.type this.__id__ = this.opts.moduleId this.__info__ = module.moduleInfo this.__eventAttr__ = opts.eventAttr this.__pageId__ = opts.pageId this.__parentId__ = opts.parentId this.#init() }
https://developers.weixin.qq.com/miniprogram/dev/reference/api/Component.html
constructor
javascript
didi/dimina
fe/packages/service/src/instance/component/component.js
https://github.com/didi/dimina/blob/master/fe/packages/service/src/instance/component/component.js
Apache-2.0
setData(data) { const fData = filterData(data) for (const key in fData) { set(this.data, key, fData[key]) } if (!this.initd) { return } message.send({ type: 'u', target: 'render', body: { bridgeId: this.bridgeId, moduleId: this.__id__, data: fData, }, }) }
https://developers.weixin.qq.com/miniprogram/dev/framework/performance/tips/runtime_setData.html @param {*} data
setData
javascript
didi/dimina
fe/packages/service/src/instance/component/component.js
https://github.com/didi/dimina/blob/master/fe/packages/service/src/instance/component/component.js
Apache-2.0
setOption(option, value) { this._setOption(option, value); this._checkOptionTypes(); }
Set a configuration option. @param {string} option @param {*} value
setOption
javascript
DoctorMcKay/node-steam-user
index.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/index.js
MIT
setOptions(options) { for (let i in options) { this._setOption(i, options[i]); } this._checkOptionTypes(); }
Set one or more configuration options @param {OptionsObject} options
setOptions
javascript
DoctorMcKay/node-steam-user
index.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/index.js
MIT
_checkOptionTypes() { // We'll infer types from DefaultOptions, but stuff that's null (for example) needs to be defined explicitly let types = { socksProxy: 'string', httpProxy: 'string', localAddress: 'string', localPort: 'number', machineIdFormat: 'array' }; for (let opt in DefaultOptions) { if (types[opt]) { // already specified continue; } types[opt] = typeof DefaultOptions[opt]; } for (let opt in this.options) { if (!types[opt]) { // no type specified for this option, so bail continue; } let requiredType = types[opt]; let providedType = typeof this.options[opt]; if (providedType == 'object' && Array.isArray(this.options[opt])) { providedType = 'array'; } else if (requiredType == 'number' && providedType == 'string' && !isNaN(this.options[opt])) { providedType = 'number'; this.options[opt] = parseFloat(this.options[opt]); } if (this.options[opt] !== null && requiredType != providedType) { this._warn(`Incorrect type '${providedType}' provided for option ${opt}, '${requiredType}' expected. Resetting to default value ${DefaultOptions[opt]}`); this._setOption(opt, DefaultOptions[opt]); } } }
Make sure that the types of all options are valid. @private
_checkOptionTypes
javascript
DoctorMcKay/node-steam-user
index.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/index.js
MIT
_resetExponentialBackoff(backoffName, dontClearBackoffTime) { if (this._exponentialBackoffs[backoffName]) { this.emit('debug-verbose', `[EBO] ${dontClearBackoffTime ? 'Soft-resetting' : 'Resetting'} exponential backoff "${backoffName}"`); clearTimeout(this._exponentialBackoffs[backoffName].timeout); if (!dontClearBackoffTime) { delete this._exponentialBackoffs[backoffName]; } } }
@param {string} backoffName @param {boolean} [dontClearBackoffTime=false] @protected
_resetExponentialBackoff
javascript
DoctorMcKay/node-steam-user
components/00-base.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/00-base.js
MIT
_exponentialBackoff(backoffName, minimumTimeout, maximumTimeout) { return new Promise((resolve) => { let timeout = this._exponentialBackoffs[backoffName]?.lastTimeout ?? 0; this._resetExponentialBackoff(backoffName); // cancel any outstanding backoffs of this name timeout *= 2; timeout = Math.max(timeout, minimumTimeout); timeout = Math.min(timeout, maximumTimeout); let isImportant = IMPORTANT_BACKOFFS.includes(backoffName); this.emit(isImportant ? 'debug' : 'debug-verbose', `[EBO] Queueing exponential backoff "${backoffName}" with timeout ${timeout}`); this._exponentialBackoffs[backoffName] = { lastTimeout: timeout, timeout: setTimeout(resolve, timeout) }; }); }
@param {string} backoffName @param {number} minimumTimeout @param {number} maximumTimeout @return Promise<void> @protected
_exponentialBackoff
javascript
DoctorMcKay/node-steam-user
components/00-base.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/00-base.js
MIT
_handleConnectionClose(conn) { let connPrefix = conn.connectionType[0] + conn.connectionId; // If the message queue is currently enabled, we need to enqueue processing of the connection close. // Otherwise we might handle the closed connection too early, e.g. before processing ClientLogOnResponse if (this._useMessageQueue) { this.emit('debug', `[${connPrefix}] Connection closed, but message queue is active. Enqueueing __CLOSE__`); this._incomingMessageQueue.push(['__CLOSE__', conn]); return; } this.emit('debug', `[${connPrefix}] Handling connection close`); if (this._loggingOff) { // We want to bail, so call _handleLogOff now (normally it's called at the end) this._handleLogOff(EResult.NoConnection, 'Logged off'); return; } this._cleanupClosedConnection(); if (!this.steamID) { // connection closed while connecting; reconnect if (this._lastChosenCM) { // Blacklist this CM from subsequent connection attempts this._ttlCache.add(`CM_DQ_${this._lastChosenCM.type}_${this._lastChosenCM.endpoint}`, 1, 1000 * 60 * 2); } // We save this timeout reference because it's possible that we handle connection close before we fully handle // a logon response. In that case, we'll cancel this timeout when we handle the logon response. // This isn't an issue in the reverse case, since a handled logon response will tear down the connection and // remove all listeners. this._reconnectForCloseDuringAuthTimeout = setTimeout(() => this._doConnection(), 1000); } else { // connection closed while we were connected; fire logoff this._handleLogOff(EResult.NoConnection, 'NoConnection'); } }
Handle the closure of our underlying connection. @param {BaseConnection} conn @protected
_handleConnectionClose
javascript
DoctorMcKay/node-steam-user
components/02-connection.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/02-connection.js
MIT
static _encodeProto(proto, data) { return proto.encode(data).finish(); }
Encode a protobuf. @param {object} proto - The protobuf class @param {object} data - The data to serialize @returns {Buffer} @protected
_encodeProto
javascript
DoctorMcKay/node-steam-user
components/03-messages.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/03-messages.js
MIT
static _decodeProto(proto, encoded) { if (ByteBuffer.isByteBuffer(encoded)) { encoded = encoded.toBuffer(); } let decoded = proto.decode(encoded); let objNoDefaults = proto.toObject(decoded, {longs: String}); let objWithDefaults = proto.toObject(decoded, {defaults: true, longs: String}); return replaceDefaults(objNoDefaults, objWithDefaults); function replaceDefaults(noDefaults, withDefaults) { if (Array.isArray(withDefaults)) { return withDefaults.map((val, idx) => replaceDefaults(noDefaults[idx], val)); } for (let i in withDefaults) { if (!Object.hasOwnProperty.call(withDefaults, i)) { continue; } if (withDefaults[i] && typeof withDefaults[i] === 'object' && !Buffer.isBuffer(withDefaults[i])) { // Covers both object and array cases, both of which will work // Won't replace empty arrays, but that's desired behavior withDefaults[i] = replaceDefaults(noDefaults[i], withDefaults[i]); } else if (typeof noDefaults[i] === 'undefined' && isReplaceableDefaultValue(withDefaults[i])) { withDefaults[i] = null; } } return withDefaults; } function isReplaceableDefaultValue(val) { if (Buffer.isBuffer(val) && val.length == 0) { // empty buffer is replaceable return true; } if (Array.isArray(val)) { // empty array is not replaceable (empty repeated fields) return false; } if (val === '0') { // Zero as a string is replaceable (64-bit integer) return true; } // Anything falsy is true return !val; } }
Decode a protobuf. @param {object} proto - The protobuf class @param {Buffer|ByteBuffer} encoded - The data to decode @returns {object} @protected
_decodeProto
javascript
DoctorMcKay/node-steam-user
components/03-messages.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/03-messages.js
MIT
_send(emsgOrHeader, body, callback) { // header fields: msg, proto, sourceJobID, targetJobID let header = typeof emsgOrHeader === 'object' ? emsgOrHeader : {msg: emsgOrHeader}; let emsg = header.msg; let canWeSend = this.steamID || ( this._tempSteamID && [EMsg.ChannelEncryptResponse, EMsg.ClientLogon, EMsg.ClientHello, EMsg.ServiceMethodCallFromClientNonAuthed].includes(emsg) ); if (!canWeSend) { // We're disconnected, drop it this.emit('debug', 'Dropping outgoing message ' + emsg + ' because we\'re not logged on.'); return; } const Proto = protobufs[emsg]; if (Proto) { header.proto = header.proto || {}; body = SteamUserMessages._encodeProto(Proto, body); } else if (ByteBuffer.isByteBuffer(body)) { body = body.toBuffer(); } let jobIdSource = null; if (callback) { jobIdSource = ++this._currentJobID; this._jobs.add(jobIdSource.toString(), callback); } let emsgName = EMsg[emsg] || emsg; if ([EMsg.ServiceMethodCallFromClient, EMsg.ServiceMethodCallFromClientNonAuthed].includes(emsg) && header.proto && header.proto.target_job_name) { emsgName = header.proto.target_job_name; } this.emit(VERBOSE_EMSG_LIST.includes(emsg) ? 'debug-verbose' : 'debug', 'Sending message: ' + emsgName); // Make the header let hdrBuf; if (header.msg == EMsg.ChannelEncryptResponse) { // since we're setting up the encrypted channel, we use this very minimal header hdrBuf = ByteBuffer.allocate(4 + 8 + 8, ByteBuffer.LITTLE_ENDIAN); hdrBuf.writeUint32(header.msg); hdrBuf.writeUint64(header.targetJobID || JOBID_NONE); hdrBuf.writeUint64(jobIdSource || header.sourceJobID || JOBID_NONE); } else if (header.proto) { // if we have a protobuf header, use that let shouldIncludeSessionId = ![EMsg.ClientHello, EMsg.ServiceMethodCallFromClientNonAuthed].includes(header.msg); header.proto.client_sessionid = shouldIncludeSessionId ? (this._sessionID || 0) : 0; header.proto.steamid = shouldIncludeSessionId ? (this.steamID || this._tempSteamID).getSteamID64() : '0'; header.proto.jobid_source = jobIdSource || header.proto.jobid_source || header.sourceJobID || JOBID_NONE; header.proto.jobid_target = header.proto.jobid_target || header.targetJobID || JOBID_NONE; let hdrProtoBuf = SteamUserMessages._encodeProto(Schema.CMsgProtoBufHeader, header.proto); hdrBuf = ByteBuffer.allocate(4 + 4 + hdrProtoBuf.length, ByteBuffer.LITTLE_ENDIAN); hdrBuf.writeUint32(header.msg | PROTO_MASK); hdrBuf.writeUint32(hdrProtoBuf.length); hdrBuf.append(hdrProtoBuf); } else { // this is the standard non-protobuf extended header hdrBuf = ByteBuffer.allocate(4 + 1 + 2 + 8 + 8 + 1 + 8 + 4, ByteBuffer.LITTLE_ENDIAN); hdrBuf.writeUint32(header.msg); hdrBuf.writeByte(36); hdrBuf.writeUint16(2); hdrBuf.writeUint64(header.targetJobID || JOBID_NONE); hdrBuf.writeUint64(jobIdSource || header.sourceJobID || JOBID_NONE); hdrBuf.writeByte(239); hdrBuf.writeUint64((this.steamID || this._tempSteamID).getSteamID64()); hdrBuf.writeUint32(this._sessionID || 0); } let outputBuffer = Buffer.concat([hdrBuf.flip().toBuffer(), body]); this.emit('debug-traffic-outgoing', outputBuffer, header.msg); this._connection.send(outputBuffer); }
@param {int|object} emsgOrHeader @param {object|Buffer|ByteBuffer} body @param {function} [callback] @protected
_send
javascript
DoctorMcKay/node-steam-user
components/03-messages.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/03-messages.js
MIT
_handleNetMessage(buffer, conn, multiId) { if (conn && conn != this._connection) { let ghostConnId = conn.connectionType[0] + conn.connectionId; let expectedConnId = this._connection ? (this._connection.connectionType[0] + this._connection.connectionId) : 'NO CONNECTION'; this.emit('debug', `Received net message from ghost connection ${ghostConnId} (expected ${expectedConnId})`); return; } if (this._useMessageQueue && !multiId) { // Multi sub-messages skip the queue because we need messages contained in a decoded multi to be processed first this._incomingMessageQueue.push(arguments); this.emit('debug', `Enqueued incoming message; queue size is now ${this._incomingMessageQueue.length}`); return; } if (buffer === '__CLOSE__') { // This is an enqueued connection closure this._handleConnectionClose(conn); return; } let buf = ByteBuffer.wrap(buffer, ByteBuffer.LITTLE_ENDIAN); let rawEMsg = buf.readUint32(); let eMsg = rawEMsg & ~PROTO_MASK; let isProtobuf = !!(rawEMsg & PROTO_MASK); this.emit('debug-traffic-incoming', buffer, eMsg); let header = {msg: eMsg}; if ([EMsg.ChannelEncryptRequest, EMsg.ChannelEncryptResult].includes(eMsg)) { // for encryption setup, we just have a very small header with two fields header.targetJobID = buf.readUint64().toString(); header.sourceJobID = buf.readUint64().toString(); } else if (isProtobuf) { // decode the protobuf header let headerLength = buf.readUint32(); header.proto = SteamUserMessages._decodeProto(Schema.CMsgProtoBufHeader, buf.slice(buf.offset, buf.offset + headerLength)); buf.skip(headerLength); header.targetJobID = header.proto.jobid_target && header.proto.jobid_target.toString(); header.sourceJobID = header.proto.jobid_source && header.proto.jobid_source.toString(); header.steamID = header.proto.steamid && header.proto.steamid.toString(); header.sessionID = header.proto.client_sessionid; } else { // decode the extended header buf.skip(3); // 1 byte for header size (fixed at 36), 2 bytes for header version (fixed at 2) header.targetJobID = buf.readUint64().toString(); header.sourceJobID = buf.readUint64().toString(); buf.skip(1); // 1 byte for header canary (fixed at 239) header.steamID = buf.readUint64().toString(); header.sessionID = buf.readUint32(); } let sessionID = (header.proto && header.proto.client_sessionid) || header.sessionID; let steamID = (header.proto && header.proto.steamid) || header.steamID; let ourCurrentSteamID = this.steamID ? this.steamID.toString() : null; if (steamID && sessionID && (sessionID != this._sessionID || steamID.toString() != ourCurrentSteamID) && steamID != 0) { // TODO if we get a new sessionid, should we check if it matches a previously-closed session? probably not necessary... this._sessionID = sessionID; this.steamID = new SteamID(steamID.toString()); delete this._tempSteamID; } this._handleMessage(header, buf.slice(), conn, multiId); }
Handles a raw binary netmessage by parsing the header and routing it appropriately @param {Buffer|string} buffer @param {BaseConnection} [conn] @param {string} [multiId] @protected
_handleNetMessage
javascript
DoctorMcKay/node-steam-user
components/03-messages.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/03-messages.js
MIT
_handleMessage(header, bodyBuf, conn, multiId) { // Is this a multi? If yes, short-circuit and just process it now. if (header.msg == EMsg.Multi) { this._processMulti(header, SteamUserMessages._decodeProto(protobufs[EMsg.Multi], bodyBuf), conn); return; } let msgName = EMsg[header.msg] || header.msg; let handlerName = header.msg; let debugPrefix = multiId ? `[${multiId}] ` : (conn ? `[${conn.connectionType[0]}${conn.connectionId}] ` : ''); let isServiceMethodMsg = [EMsg.ServiceMethod, EMsg.ServiceMethodResponse].includes(header.msg); if (isServiceMethodMsg) { if (header.proto && header.proto.target_job_name) { handlerName = msgName = header.proto.target_job_name; if (header.msg == EMsg.ServiceMethodResponse) { handlerName += '_Response'; msgName += '_Response'; } } else { this.emit('debug', debugPrefix + 'Got ' + (header.msg == EMsg.ServiceMethod ? 'ServiceMethod' : 'ServiceMethodResponse') + ' without target_job_name'); return; } } if (!isServiceMethodMsg && header.proto && header.proto.target_job_name) { this.emit('debug', debugPrefix + 'Got unknown target_job_name ' + header.proto.target_job_name + ' for msg ' + msgName); } if (!this._handlerManager.hasHandler(handlerName) && this._jobs.get(header.targetJobID.toString()) === null) { this.emit(VERBOSE_EMSG_LIST.includes(header.msg) ? 'debug-verbose' : 'debug', debugPrefix + 'Unhandled message: ' + msgName); return; } let body = bodyBuf; if (protobufs[handlerName]) { body = SteamUserMessages._decodeProto(protobufs[handlerName], bodyBuf); } let handledMessageDebugMsg = debugPrefix + 'Handled message: ' + msgName; if (header.msg == EMsg.ClientLogOnResponse) { handledMessageDebugMsg += ` (${EResult[body.eresult] || body.eresult})`; } this.emit(VERBOSE_EMSG_LIST.includes(header.msg) ? 'debug-verbose' : 'debug', handledMessageDebugMsg); let cb = null; if (header.sourceJobID != JOBID_NONE) { // this message expects a response. make a callback we can pass to the end-user. cb = (emsgOrHeader, body) => { // once invoked the callback should set the jobid_target let responseHeader = typeof emsgOrHeader === 'object' ? emsgOrHeader : {msg: emsgOrHeader}; let emsg = responseHeader.msg; if (protobufs[emsg]) { responseHeader.proto = {jobid_target: header.sourceJobID}; } else { responseHeader.targetJobID = header.sourceJobID; } this._send(responseHeader, body); }; } let jobCallback = this._jobs.get(header.targetJobID.toString()); if (jobCallback) { // this is a response to something, so invoke the appropriate callback jobCallback.call(this, body, header, cb); } else { this._handlerManager.emit(this, handlerName, body, header, cb); } }
Handles and routes a parsed message @param {object} header @param {ByteBuffer} bodyBuf @param {BaseConnection} [conn] @param {string} [multiId] @protected
_handleMessage
javascript
DoctorMcKay/node-steam-user
components/03-messages.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/03-messages.js
MIT
async _processMulti(header, body, conn) { let multiId = conn.connectionType[0] + conn.connectionId + '#' + (++this._multiCount); this.emit('debug-verbose', `=== Processing ${body.size_unzipped ? 'gzipped multi msg' : 'multi msg'} ${multiId} (${body.message_body.length} bytes) ===`); let payload = body.message_body; // Enable the message queue while we're unzipping the message (or waiting until the next event loop cycle). // This prevents any messages from getting processed out of order. this._useMessageQueue = true; if (body.size_unzipped) { try { payload = await new Promise((resolve, reject) => { Zlib.gunzip(payload, (err, unzipped) => { if (err) { return reject(err); } resolve(unzipped); }); }); } catch (ex) { this.emit('error', ex); this._disconnect(true); return; } } else { // Await a setImmediate promise to guarantee that multi msg processing always takes at least one iteration of the event loop. // This avoids message queue processing shenanigans. Waiting until the next iteration of the event loop enables // _handleNetMessage at the end of this method to return immediately, which will thus exit the clear-queue loop // because the queue got re-enabled. Prevents the queue from being cleared in multiple places at once. await new Promise(resolve => setImmediate(resolve)); } if (!this._connection || this._connection != conn) { this.emit('debug', `=== Bailing out on processing multi msg ${multiId} because our connection is ${!this._connection ? 'lost' : 'different'}! ===`); return; } while (payload.length && (this.steamID || this._tempSteamID)) { let subSize = payload.readUInt32LE(0); this._handleNetMessage(payload.slice(4, 4 + subSize), conn, multiId); payload = payload.slice(4 + subSize); } this.emit('debug-verbose', `=== Finished processing multi msg ${multiId}; now clearing queue of size ${this._incomingMessageQueue.length} ===`); // Go ahead and process anything in the queue now. First disable the message queue. We don't need to worry about // newly-received messages sneaking in ahead of the queue being cleared, since message processing is synchronous. // If we encounter another multi msg, the message queue will get re-enabled. this._useMessageQueue = false; // Continue to pop items from the message queue until it's empty, or it gets re-enabled. If the message queue gets // re-enabled, immediately stop popping items from it to avoid stuff getting out of order. while (this._incomingMessageQueue.length > 0 && !this._useMessageQueue) { this._handleNetMessage.apply(this, this._incomingMessageQueue.shift()); } if (this._incomingMessageQueue.length > 0) { this.emit('debug-verbose', `[${multiId}] Message queue processing ended early with ${this._incomingMessageQueue.length} elements remaining`); } }
@param {object} header @param {object} body @param {object} conn @returns {Promise<void>} @protected
_processMulti
javascript
DoctorMcKay/node-steam-user
components/03-messages.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/03-messages.js
MIT
_sendUnified(methodName, methodData, callback) { let Proto = protobufs[methodName + (callback ? '_Request' : '')]; let header = { msg: EMsg.ServiceMethodCallFromClient, proto: { target_job_name: methodName } }; this._send(header, SteamUserMessages._encodeProto(Proto, methodData), callback); }
Send a unified message. @param {string} methodName - In format Interface.Method#Version, e.g. Foo.DoThing#1 @param {object} methodData @param {function} [callback] @protected
_sendUnified
javascript
DoctorMcKay/node-steam-user
components/03-messages.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/03-messages.js
MIT
static formatCurrency(amount, currency) { let amountString = amount.toFixed(2); if (!CurrencyData[currency]) { return amountString; } let data = CurrencyData[currency]; if (data.whole) { amountString = amountString.replace('.00', ''); } if (data.commas) { amountString = amountString.replace('.', ','); } return (data.prepend || '') + amountString + (data.append || ''); }
@param {number} amount @param {ECurrencyCode} currency @returns {string}
formatCurrency
javascript
DoctorMcKay/node-steam-user
components/04-utility.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/04-utility.js
MIT
async _saveFile(filename, content) { try { if (this.storage) { await this.storage.saveFile(filename, content); } } catch (ex) { this.emit('debug', `Error saving file ${filename}: ${ex.message}`); } }
@param {string} filename @param {Buffer|*} content @return {Promise} @protected
_saveFile
javascript
DoctorMcKay/node-steam-user
components/05-filestorage.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/05-filestorage.js
MIT
async _readFile(filename) { let content = null; try { if (this.storage) { content = await this.storage.readFile(filename); } } catch (ex) { this.emit('debug', `Error reading file ${filename}: ${ex.message}`); } return content; }
@param {string} filename @returns {Promise<Buffer|null>} @protected
_readFile
javascript
DoctorMcKay/node-steam-user
components/05-filestorage.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/05-filestorage.js
MIT
async _readFiles(filenames) { if (!this.storage) { return filenames.map(filename => ({filename, error: new Error('Storage system disabled')})); } // No need for a try/catch because readFiles can't reject return await this.storage.readFiles(filenames); }
@param {string[]} filenames @returns {Promise<{filename: string, error?: Error, contents?: Buffer}[]>} @protected
_readFiles
javascript
DoctorMcKay/node-steam-user
components/05-filestorage.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/05-filestorage.js
MIT
async _apiRequest(httpMethod, iface, method, version, data, cacheSeconds) { data = data || {}; httpMethod = httpMethod.toUpperCase(); // just in case // Pad the version with zeroes to make it 4 digits long, because Valve version = version.toString(); while (version.length < 4) { version = '0' + version; } data.format = 'vdf'; // for parity with the Steam client let client = this._httpClient || new HttpClient({ userAgent: USER_AGENT, httpsAgent: this._getProxyAgent(), localAddress: this.options.localAddress, defaultHeaders: Object.assign(getDefaultHeaders(), this.options.additionalHeaders), defaultTimeout: 5000, gzip: true }); this._httpClient = client; let url = `https://${HOSTNAME}/${iface}/${method}/v${version}/`; let cacheKey = `API_${httpMethod}_${url}`; let cacheValue; if (cacheSeconds && (cacheValue = this._ttlCache.get(cacheKey))) { this.emit('debug', `[WebAPI] Using cached value for ${cacheKey}`); return cacheValue; } let headers = {}; let body = null; if (httpMethod == 'GET') { url += `?${buildQueryString(data)}`; } else { headers['Content-Type'] = 'application/x-www-form-urlencoded'; body = buildQueryString(data); } let res = await client.request({ method: httpMethod, url, body }); this.emit('debug', `API ${httpMethod} request to ${url}: ${res.statusCode}`); if (res.statusCode != 200) { throw new Error(`HTTP error ${res.statusCode}`); } let responseData = VDF.parse(res.textBody); if (cacheSeconds) { this._ttlCache.add(cacheKey, responseData, 1000 * cacheSeconds); } return responseData; }
@param {string} httpMethod @param {string} iface @param {string} method @param {number} version @param {object} [data] @param {number} [cacheSeconds] @returns {Promise} @protected
_apiRequest
javascript
DoctorMcKay/node-steam-user
components/06-webapi.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/06-webapi.js
MIT
async _sendLogOn() { if (this._logOnDetails.account_name && this._logOnDetails.password) { this.emit('debug', 'Logging on with account name and password; fetching a new refresh token'); let startTime = Date.now(); let authSuccess = await this._performPasswordAuth(); if (!authSuccess) { // We would have already emitted 'error' so let's just bail now return; } else { this.emit('debug', `Password auth succeeded in ${Date.now() - startTime} ms`); } } // Realistically, this should never need to elapse since at this point we have already established a successful connection // with the CM. But sometimes, Steam appears to never respond to the logon message. Valve. this._logonMsgTimeout = setTimeout(() => { this.emit('debug', 'Logon message timeout elapsed. Attempting relog.'); this._disconnect(true); this._enqueueLogonAttempt(); }, 5000); this._send(this._logOnDetails.game_server_token ? EMsg.ClientLogonGameServer : EMsg.ClientLogon, this._logOnDetails); }
Send the actual ClientLogOn message. @private
_sendLogOn
javascript
DoctorMcKay/node-steam-user
components/09-logon.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/09-logon.js
MIT
_enqueueLogonAttempt() { this._exponentialBackoff('logOn', 1000, 60000).then(() => { if (this.steamID || this._connecting) { // Not sure why this happened, but we're already connected let whyFail = this.steamID ? 'already connected' : 'already attempting to connect'; this.emit('debug', `!! Attempted to fire queued login attempt, but we're ${whyFail}`); return; } this.emit('debug', 'Firing queued login attempt'); this.logOn(true); }); }
Enqueue another logon attempt. Used after we get ServiceUnavailable, TryAnotherCM, or a timeout waiting for ClientLogOnResponse. @private
_enqueueLogonAttempt
javascript
DoctorMcKay/node-steam-user
components/09-logon.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/09-logon.js
MIT
_disconnect(suppressLogoff) { this._clearChangelistUpdateTimer(); this._incomingMessageQueue = []; // clear the incoming message queue. If we're disconnecting, we don't care about anything else in the queue. this.emit('debug', 'Disconnecting' + (suppressLogoff ? ' without sending logoff' : '')); if (this.steamID && !suppressLogoff) { this._loggingOff = true; this._send(EMsg.ClientLogOff, {}); let timeout = setTimeout(() => { this.emit('disconnected', 0, 'Logged off'); this._loggingOff = false; this._connection && this._connection.end(true); this.steamID = null; this._cleanupClosedConnection(); }, 4000); this.once('disconnected', (eresult) => { clearTimeout(timeout); this.steamID = null; this._cleanupClosedConnection(); }); } else { this._connection && this._connection.end(true); this.steamID = null; this._cleanupClosedConnection(); } }
Disconnect from Steam @param {boolean} suppressLogoff - If true, just disconnect immediately without sending a logoff message. @private
_disconnect
javascript
DoctorMcKay/node-steam-user
components/09-logon.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/09-logon.js
MIT
_getMachineID(localFile) { if ( ( !this._logOnDetails.account_name && !this._logOnDetails._steamid ) || this.options.machineIdType == EMachineIDType.None ) { // No machine IDs for anonymous logons return null; } // The user wants to use a random machine ID that's saved to dataDirectory if (this.options.machineIdType == EMachineIDType.PersistentRandom) { if (localFile) { return localFile; } let file = getRandomID(); this._saveFile('machineid.bin', file); return file; } // The user wants to use a machine ID that's generated off the account name if (this.options.machineIdType == EMachineIDType.AccountNameGenerated) { return createMachineID( this.options.machineIdFormat[0].replace(/\{account_name\}/g, this._getAccountIdentifier()), this.options.machineIdFormat[1].replace(/\{account_name\}/g, this._getAccountIdentifier()), this.options.machineIdFormat[2].replace(/\{account_name\}/g, this._getAccountIdentifier()) ); } // Default to random return getRandomID(); function getRandomID() { return createMachineID(Math.random().toString(), Math.random().toString(), Math.random().toString()); } }
@param {Buffer} [localFile] @returns {null|Buffer} @private
_getMachineID
javascript
DoctorMcKay/node-steam-user
components/09-logon.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/09-logon.js
MIT
_handleLogOff(result, msg) { let fatal = true; let nonFatalLogOffResults = [ 0, EResult.Fail, EResult.NoConnection, EResult.ServiceUnavailable, EResult.TryAnotherCM ]; if (this.options.autoRelogin && nonFatalLogOffResults.includes(result)) { fatal = false; } delete this.publicIP; delete this.cellID; this.contentServersReady = false; this._initProperties(); this._clearChangelistUpdateTimer(); clearInterval(this._heartbeatInterval); if (!this._relogging && fatal && !this._loggingOff) { let e = new Error(msg); e.eresult = result; let steamID = this.steamID; this._disconnect(true); this.steamID = steamID; this.emit('error', e); this.steamID = null; } else { // Only emit "disconnected" if we were previously logged on let wasLoggingOff = this._loggingOff; // remember this since our 'disconnected' event handler might reset it if (this.steamID) { this.emit('disconnected', result, msg); } this._disconnect(true); // if we're manually relogging, or we got disconnected because steam went down, enqueue a reconnect if (!wasLoggingOff || this._relogging) { this._resetExponentialBackoff('logOn'); this._exponentialBackoff('logOn', 1000, 1000).then(() => { this.logOn(true); }); } this._loggingOff = false; this._relogging = false; this.steamID = null; } }
@param {number} result @param {string} msg @private
_handleLogOff
javascript
DoctorMcKay/node-steam-user
components/09-logon.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/09-logon.js
MIT
_steamGuardPrompt(domain, lastCodeWrong, callback) { if (this.listenerCount('steamGuard') == 0) { // No steamGuard listeners, so prompt for one from stdin let rl = require('readline').createInterface({ input: process.stdin, output: process.stdout }); rl.question('Steam Guard' + (!domain ? ' App' : '') + ' Code: ', function(code) { rl.close(); callback(code); }); } else { this.emit('steamGuard', domain, callback, lastCodeWrong); } }
@param {string} domain @param {boolean} lastCodeWrong @param {function} callback @private
_steamGuardPrompt
javascript
DoctorMcKay/node-steam-user
components/09-logon.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/09-logon.js
MIT
getPrivacySettings(callback) { return StdLib.Promises.timeoutCallbackPromise(10000, null, callback, (resolve, reject) => { this._sendUnified('Player.GetPrivacySettings#1', {}, (body, hdr) => { let err = Helpers.eresultError(hdr.proto); if (err) { return reject(err); } resolve(body.privacy_settings); }); }); }
Get your account's profile privacy settings. @param {function} [callback] @returns {Promise<{privacy_state: int, privacy_state_inventory: int, privacy_state_gifts: int, privacy_state_ownedgames: int, privacy_state_playtime: int, privacy_state_friendslist: int}>}
getPrivacySettings
javascript
DoctorMcKay/node-steam-user
components/account.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/account.js
MIT