code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
function shouldInvalidateReactRefreshBoundary(prevSignature, nextSignature) { if (prevSignature.length !== nextSignature.length) { return true; } for (var i = 0; i < nextSignature.length; i += 1) { if (prevSignature[i] !== nextSignature[i]) { return true; } } return false; }
Compares previous and next module objects to check for mutated boundaries. This implementation is based on the one in [Metro](https://github.com/facebook/metro/blob/907d6af22ac6ebe58572be418e9253a90665ecbd/packages/metro/src/lib/polyfills/require.js#L776-L792). @param {*} prevSignature The signature of the current Webpack module exports object. @param {*} nextSignature The signature of the next Webpack module exports object. @returns {boolean} Whether the React refresh boundary should be invalidated.
shouldInvalidateReactRefreshBoundary ( prevSignature , nextSignature )
javascript
pmmmwh/react-refresh-webpack-plugin
lib/runtime/RefreshUtils.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/runtime/RefreshUtils.js
MIT
function hotDisposeCallback(data) { // We have to mutate the data object to get data registered and cached data.prevData = getWebpackHotData(moduleExports); }
A callback to performs a full refresh if React has unrecoverable errors, and also caches the to-be-disposed module. @param {*} data A hot module data object from Webpack HMR. @returns {void}
hotDisposeCallback ( data )
javascript
pmmmwh/react-refresh-webpack-plugin
lib/runtime/RefreshUtils.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/runtime/RefreshUtils.js
MIT
function hotErrorHandler(error) { if (typeof refreshOverlay !== 'undefined' && refreshOverlay) { refreshOverlay.handleRuntimeError(error); } if (typeof isTest !== 'undefined' && isTest) { if (window.onHotAcceptError) { window.onHotAcceptError(error.message); } } __webpack_require__.c[moduleId].hot.accept(hotErrorHandler); }
An error handler to allow self-recovering behaviours. @param {Error} error An error occurred during evaluation of a module. @returns {void}
hotErrorHandler ( error )
javascript
pmmmwh/react-refresh-webpack-plugin
lib/runtime/RefreshUtils.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/runtime/RefreshUtils.js
MIT
function updateCallback() { if (typeof refreshOverlay !== 'undefined' && refreshOverlay) { refreshOverlay.clearRuntimeErrors(); } }
A function to dismiss the error overlay after performing React refresh. @returns {void}
updateCallback ( )
javascript
pmmmwh/react-refresh-webpack-plugin
lib/runtime/RefreshUtils.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/lib/runtime/RefreshUtils.js
MIT
const d = (object, property, defaultValue) => { if (typeof object[property] === 'undefined' && typeof defaultValue !== 'undefined') { object[property] = defaultValue; } return object[property]; };
Sets a constant default value for the property when it is undefined. @template T @template {keyof T} Property @param {T} object An object. @param {Property} property A property of the provided object. @param {T[Property]} [defaultValue] The default value to set for the property. @returns {T[Property]} The defaulted property value.
d
javascript
pmmmwh/react-refresh-webpack-plugin
options/index.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/options/index.js
MIT
const n = (object, property, fn) => { object[property] = fn(object[property]); return object[property]; };
Resolves the value for a nested object option. @template T @template {keyof T} Property @template Result @param {T} object An object. @param {Property} property A property of the provided object. @param {function(T | undefined): Result} fn The handler to resolve the property's value. @returns {Result} The resolved option value.
n
javascript
pmmmwh/react-refresh-webpack-plugin
options/index.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/options/index.js
MIT
function resolver(request, options) { // This acts as a mock for `require.resolve('react-refresh')`, // since the current mocking behaviour of Jest is not symmetrical, // i.e. only `require` is mocked but not `require.resolve`. if (request === 'react-refresh') { return 'react-refresh'; } return options.defaultResolver(request, options); }
@param {string} request @param {*} options @return {string}
resolver ( request , options )
javascript
pmmmwh/react-refresh-webpack-plugin
test/jest-resolver.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/test/jest-resolver.js
MIT
describe.skipIf = (condition, blockName, blockFn) => { if (condition) { return describe.skip(blockName, blockFn); } return describe(blockName, blockFn); };
Skips a test block conditionally. @param {boolean} condition The condition to skip the test block. @param {string} blockName The name of the test block. @param {import('@jest/types').Global.BlockFn} blockFn The test block function. @returns {void}
describe.skipIf
javascript
pmmmwh/react-refresh-webpack-plugin
test/jest-test-setup.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/test/jest-test-setup.js
MIT
test.skipIf = (condition, testName, fn, timeout) => { if (condition) { return test.skip(testName, fn); } return test(testName, fn, timeout); };
Skips a test conditionally. @param {boolean} condition The condition to skip the test. @param {string} testName The name of the test. @param {import('@jest/types').Global.TestFn} fn The test function. @param {number} [timeout] The time to wait before aborting. @returns {void}
test.skipIf
javascript
pmmmwh/react-refresh-webpack-plugin
test/jest-test-setup.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/test/jest-test-setup.js
MIT
function getIndexHTML(port) { return ` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Sandbox React App</title> </head> <body> <div id="app"></div> <script src="http://localhost:${port}/${BUNDLE_FILENAME}.js"></script> </body> </html> `; }
@param {number} port @returns {string}
getIndexHTML ( port )
javascript
pmmmwh/react-refresh-webpack-plugin
test/helpers/sandbox/configs.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/test/helpers/sandbox/configs.js
MIT
function getPackageJson(esModule = false) { return ` { "type": "${esModule ? 'module' : 'commonjs'}" } `; }
@param {boolean} esModule @returns {string}
getPackageJson ( esModule = false )
javascript
pmmmwh/react-refresh-webpack-plugin
test/helpers/sandbox/configs.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/test/helpers/sandbox/configs.js
MIT
function getWDSConfig(srcDir) { return ` const { DefinePlugin, ProgressPlugin } = require('webpack'); const ReactRefreshPlugin = require('@pmmmwh/react-refresh-webpack-plugin'); module.exports = { mode: 'development', context: '${srcDir}', devtool: false, entry: { '${BUNDLE_FILENAME}': [ '${path.join(__dirname, 'fixtures/hmr-notifier.js')}', './index.js', ], }, module: { rules: [ { test: /\\.jsx?$/, include: '${srcDir}', use: [ { loader: '${require.resolve('babel-loader')}', options: { babelrc: false, plugins: ['${require.resolve('react-refresh/babel')}'], } } ], }, ], }, output: { hashFunction: ${WEBPACK_VERSION === 4 ? "'sha1'" : "'xxhash64'"}, }, plugins: [ new DefinePlugin({ __react_refresh_test__: true }), new ProgressPlugin((percentage) => { if (percentage === 1) { console.log("Webpack compilation complete."); } }), new ReactRefreshPlugin(), ], resolve: { alias: ${JSON.stringify( { ...(WEBPACK_VERSION === 4 && { webpack: 'webpack-v4' }), ...(WDS_VERSION === 3 && { 'webpack-dev-server': 'webpack-dev-server-v3' }), ...(WDS_VERSION === 4 && { 'webpack-dev-server': 'webpack-dev-server-v4' }), }, null, 2 )}, extensions: ['.js', '.jsx'], }, }; `; }
@param {string} srcDir @returns {string}
getWDSConfig ( srcDir )
javascript
pmmmwh/react-refresh-webpack-plugin
test/helpers/sandbox/configs.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/test/helpers/sandbox/configs.js
MIT
function getPackageExecutable(packageName, binName) { let { bin: binPath } = require(`${packageName}/package.json`); // "bin": { "package": "bin.js" } if (typeof binPath === 'object') { binPath = binPath[binName || packageName]; } if (!binPath) { throw new Error(`Package ${packageName} does not have an executable!`); } return require.resolve(path.join(packageName, binPath)); }
@param {string} packageName @returns {string}
getPackageExecutable ( packageName , binName )
javascript
pmmmwh/react-refresh-webpack-plugin
test/helpers/sandbox/spawn.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/test/helpers/sandbox/spawn.js
MIT
function killTestProcess(instance) { if (!instance) { return; } try { process.kill(instance.pid); } catch (error) { if ( process.platform === 'win32' && typeof error.message === 'string' && (error.message.includes(`no running instance of the task`) || error.message.includes(`not found`)) ) { // Windows throws an error if the process is already dead return; } throw error; } }
@param {import('child_process').ChildProcess | void} instance @returns {void}
killTestProcess ( instance )
javascript
pmmmwh/react-refresh-webpack-plugin
test/helpers/sandbox/spawn.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/test/helpers/sandbox/spawn.js
MIT
function handleStdout(data) { const message = data.toString(); if (successRegex.test(message)) { if (!didResolve) { didResolve = true; resolve(instance); } } if (__DEBUG__) { process.stdout.write(message); } }
@param {Buffer} data @returns {void}
handleStdout ( data )
javascript
pmmmwh/react-refresh-webpack-plugin
test/helpers/sandbox/spawn.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/test/helpers/sandbox/spawn.js
MIT
function spawnTestProcess(processPath, argv, options = {}) { const cwd = options.cwd || path.resolve(__dirname, '../../..'); const env = { ...process.env, NODE_ENV: 'development', ...options.env, }; const successRegex = new RegExp(options.successMessage || 'webpack compilation complete.', 'i'); return new Promise((resolve, reject) => { const instance = spawn(processPath, argv, { cwd, env }); let didResolve = false; /** * @param {Buffer} data * @returns {void} */ function handleStdout(data) { const message = data.toString(); if (successRegex.test(message)) { if (!didResolve) { didResolve = true; resolve(instance); } } if (__DEBUG__) { process.stdout.write(message); } } /** * @param {Buffer} data * @returns {void} */ function handleStderr(data) { const message = data.toString(); if (__DEBUG__) { process.stderr.write(message); } } instance.stdout.on('data', handleStdout); instance.stderr.on('data', handleStderr); instance.on('close', () => { instance.stdout.removeListener('data', handleStdout); instance.stderr.removeListener('data', handleStderr); if (!didResolve) { didResolve = true; resolve(); } }); instance.on('error', (error) => { reject(error); }); }); }
@param {string} processPath @param {*[]} argv @param {SpawnOptions} [options] @returns {Promise<import('child_process').ChildProcess | void>}
spawnTestProcess ( processPath , argv , options = { } )
javascript
pmmmwh/react-refresh-webpack-plugin
test/helpers/sandbox/spawn.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/test/helpers/sandbox/spawn.js
MIT
const log = (...args) => { if (__DEBUG__) { console.log(...args); } };
Logs output to the console (only in debug mode). @param {...*} args @returns {void}
log
javascript
pmmmwh/react-refresh-webpack-plugin
test/helpers/sandbox/index.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/test/helpers/sandbox/index.js
MIT
const sleep = (ms) => { return new Promise((resolve) => { setTimeout(resolve, ms); }); };
Pause current asynchronous execution for provided milliseconds. @param {number} ms @returns {Promise<void>}
sleep
javascript
pmmmwh/react-refresh-webpack-plugin
test/helpers/sandbox/index.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/test/helpers/sandbox/index.js
MIT
async write(fileName, content) { // Update the file on filesystem const fullFileName = path.join(srcDir, fileName); const directory = path.dirname(fullFileName); await fse.mkdirp(directory); await fse.writeFile(fullFileName, content); },
@param {string} fileName @param {string} content @returns {Promise<void>}
write ( fileName , content )
javascript
pmmmwh/react-refresh-webpack-plugin
test/helpers/sandbox/index.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/test/helpers/sandbox/index.js
MIT
const onFrameNavigate = (frame) => { if (frame === page.mainFrame()) { page.off('hotSuccess', onHotSuccess); clearTimeout(hmrTimeout); hmrStatus = 'reloaded'; resolve(); } };
@param {import('puppeteer').Frame} frame @returns {void}
onFrameNavigate
javascript
pmmmwh/react-refresh-webpack-plugin
test/helpers/sandbox/index.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/test/helpers/sandbox/index.js
MIT
async remove(fileName) { const fullFileName = path.join(srcDir, fileName); await fse.remove(fullFileName); },
@param {string} fileName @returns {Promise<void>}
remove ( fileName )
javascript
pmmmwh/react-refresh-webpack-plugin
test/helpers/sandbox/index.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/test/helpers/sandbox/index.js
MIT
async evaluate(fn, ...restArgs) { if (typeof fn === 'function') { return await page.evaluate(fn, ...restArgs); } else { throw new Error('You must pass a function to be evaluated in the browser!'); } },
@param {*} fn @param {...*} restArgs @returns {Promise<*>}
evaluate ( fn , ... restArgs )
javascript
pmmmwh/react-refresh-webpack-plugin
test/helpers/sandbox/index.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/test/helpers/sandbox/index.js
MIT
function removeCwd(str) { let cwd = process.cwd(); let result = str; const isWin = process.platform === 'win32'; if (isWin) { cwd = cwd.replace(/\\/g, '/'); result = result.replace(/\\/g, '/'); } return result.replace(new RegExp(cwd, 'g'), ''); }
@param {string} str @return {string}
removeCwd ( str )
javascript
pmmmwh/react-refresh-webpack-plugin
test/helpers/compilation/normalizeErrors.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/test/helpers/compilation/normalizeErrors.js
MIT
function normalizeErrors(errors) { return errors.map((error) => { // Output nested error messages in full - // this is useful for checking loader validation errors, for example. if ('error' in error) { return removeCwd(error.error.message); } return removeCwd(error.message.split('\n').slice(0, 2).join('\n')); }); }
@param {Error[]} errors @return {string[]}
normalizeErrors ( errors )
javascript
pmmmwh/react-refresh-webpack-plugin
test/helpers/compilation/normalizeErrors.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/test/helpers/compilation/normalizeErrors.js
MIT
function getRefreshModuleRuntime(Template, options) { const constDeclaration = options.const ? 'const' : 'var'; const letDeclaration = options.const ? 'let' : 'var'; const webpackHot = options.moduleSystem === 'esm' ? 'import.meta.webpackHot' : 'module.hot'; return Template.asString([ `${constDeclaration} $ReactRefreshModuleId$ = __webpack_require__.$Refresh$.moduleId;`, `${constDeclaration} $ReactRefreshCurrentExports$ = __react_refresh_utils__.getModuleExports(`, Template.indent('$ReactRefreshModuleId$'), ');', '', 'function $ReactRefreshModuleRuntime$(exports) {', Template.indent([ `if (${webpackHot}) {`, Template.indent([ `${letDeclaration} errorOverlay;`, "if (typeof __react_refresh_error_overlay__ !== 'undefined') {", Template.indent('errorOverlay = __react_refresh_error_overlay__;'), '}', `${letDeclaration} testMode;`, "if (typeof __react_refresh_test__ !== 'undefined') {", Template.indent('testMode = __react_refresh_test__;'), '}', 'return __react_refresh_utils__.executeRuntime(', Template.indent([ 'exports,', '$ReactRefreshModuleId$,', `${webpackHot},`, 'errorOverlay,', 'testMode', ]), ');', ]), '}', ]), '}', '', "if (typeof Promise !== 'undefined' && $ReactRefreshCurrentExports$ instanceof Promise) {", Template.indent('$ReactRefreshCurrentExports$.then($ReactRefreshModuleRuntime$);'), '} else {', Template.indent('$ReactRefreshModuleRuntime$($ReactRefreshCurrentExports$);'), '}', ]); }
Generates code appended to each JS-like module for react-refresh capabilities. `__react_refresh_utils__` will be replaced with actual utils during source parsing by `webpack.ProvidePlugin`. [Reference for Runtime Injection](https://github.com/webpack/webpack/blob/b07d3b67d2252f08e4bb65d354a11c9b69f8b434/lib/HotModuleReplacementPlugin.js#L419) [Reference for HMR Error Recovery](https://github.com/webpack/webpack/issues/418#issuecomment-490296365) @param {import('webpack').Template} Webpack's templating helpers. @param {ModuleRuntimeOptions} options The refresh module runtime options. @returns {string} The refresh module runtime template.
getRefreshModuleRuntime ( Template , options )
javascript
pmmmwh/react-refresh-webpack-plugin
loader/utils/getRefreshModuleRuntime.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/loader/utils/getRefreshModuleRuntime.js
MIT
async function getModuleSystem(ModuleFilenameHelpers, options) { // Check loader options - // if `esModule` is set we don't have to do extra guess work. switch (typeof options.esModule) { case 'boolean': { return options.esModule ? 'esm' : 'cjs'; } case 'object': { if ( options.esModule.include && ModuleFilenameHelpers.matchPart(this.resourcePath, options.esModule.include) ) { return 'esm'; } if ( options.esModule.exclude && ModuleFilenameHelpers.matchPart(this.resourcePath, options.esModule.exclude) ) { return 'cjs'; } break; } default: // Do nothing } // Check current resource's extension if (/\.mjs$/.test(this.resourcePath)) return 'esm'; if (/\.cjs$/.test(this.resourcePath)) return 'cjs'; if (typeof this.addMissingDependency !== 'function') { // This is Webpack 4 which does not support `import.meta`. // We assume `.js` files are CommonJS because the output cannot be ESM anyway. return 'cjs'; } // We will assume CommonJS if we cannot determine otherwise let packageJsonType = ''; // We begin our search for relevant `package.json` files, // at the directory of the resource being loaded. // These paths should already be resolved, // but we resolve them again to ensure we are dealing with an aboslute path. const resourceContext = path.dirname(this.resourcePath); let searchPath = resourceContext; let previousSearchPath = ''; // We start our search just above the root context of the webpack compilation const stopPath = path.dirname(this.rootContext); // If the module context is a resolved symlink outside the `rootContext` path, // then we will never find the `stopPath` - so we also halt when we hit the root. // Note that there is a potential that the wrong `package.json` is found in some pathalogical cases, // such as a folder that is conceptually a package + does not have an ancestor `package.json`, // but there exists a `package.json` higher up. // This might happen if you have a folder of utility JS files that you symlink but did not organize as a package. // We consider this an unsupported edge case for now. while (searchPath !== stopPath && searchPath !== previousSearchPath) { // If we have already determined the `package.json` type for this path we can stop searching. // We do however still need to cache the found value, // from the `resourcePath` folder up to the matching `searchPath`, // to avoid retracing these steps when processing sibling resources. if (packageJsonTypeMap.has(searchPath)) { packageJsonType = packageJsonTypeMap.get(searchPath); let currentPath = resourceContext; while (currentPath !== searchPath) { // We set the found type at least level from `resourcePath` folder up to the matching `searchPath` packageJsonTypeMap.set(currentPath, packageJsonType); currentPath = path.dirname(currentPath); } break; } let packageJsonPath = path.join(searchPath, 'package.json'); try { const packageSource = await fsPromises.readFile(packageJsonPath, 'utf-8'); try { const packageObject = JSON.parse(packageSource); // Any package.json is sufficient as long as it can be parsed. // If it does not explicitly have a `type: "module"` it will be assumed to be CommonJS. packageJsonType = typeof packageObject.type === 'string' ? packageObject.type : ''; packageJsonTypeMap.set(searchPath, packageJsonType); // We set the type in the cache for all paths from the `resourcePath` folder, // up to the matching `searchPath` to avoid retracing these steps when processing sibling resources. let currentPath = resourceContext; while (currentPath !== searchPath) { packageJsonTypeMap.set(currentPath, packageJsonType); currentPath = path.dirname(currentPath); } } catch (e) { // `package.json` exists but could not be parsed. // We track it as a dependency so we can reload if this file changes. } this.addDependency(packageJsonPath); break; } catch (e) { // `package.json` does not exist. // We track it as a missing dependency so we can reload if this file is added. this.addMissingDependency(packageJsonPath); } // Try again at the next level up previousSearchPath = searchPath; searchPath = path.dirname(searchPath); } // Check `package.json` for the `type` field - // fallback to use `cjs` for anything ambiguous. return packageJsonType === 'module' ? 'esm' : 'cjs'; } module.exports = getModuleSystem;
Infers the current active module system from loader context and options. @this {import('webpack').loader.LoaderContext} @param {import('webpack').ModuleFilenameHelpers} ModuleFilenameHelpers Webpack's module filename helpers. @param {import('../types').NormalizedLoaderOptions} options The normalized loader options. @return {Promise<'esm' | 'cjs'>} The inferred module system.
getModuleSystem ( ModuleFilenameHelpers , options )
javascript
pmmmwh/react-refresh-webpack-plugin
loader/utils/getModuleSystem.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/loader/utils/getModuleSystem.js
MIT
const normalizeOptions = (options) => { d(options, 'const', false); n(options, 'esModule', (esModule) => { if (typeof esModule === 'boolean' || typeof esModule === 'undefined') { return esModule; } d(esModule, 'include'); d(esModule, 'exclude'); return esModule; }); return options; };
Normalizes the options for the loader. @param {import('../types').ReactRefreshLoaderOptions} options Non-normalized loader options. @returns {import('../types').NormalizedLoaderOptions} Normalized loader options.
normalizeOptions
javascript
pmmmwh/react-refresh-webpack-plugin
loader/utils/normalizeOptions.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/loader/utils/normalizeOptions.js
MIT
function getIdentitySourceMap(source, resourcePath) { const sourceMap = new SourceMapGenerator(); sourceMap.setSourceContent(resourcePath, source); source.split('\n').forEach((line, index) => { sourceMap.addMapping({ source: resourcePath, original: { line: index + 1, column: 0, }, generated: { line: index + 1, column: 0, }, }); }); return sourceMap.toJSON(); }
Generates an identity source map from a source file. @param {string} source The content of the source file. @param {string} resourcePath The name of the source file. @returns {import('source-map').RawSourceMap} The identity source map.
getIdentitySourceMap ( source , resourcePath )
javascript
pmmmwh/react-refresh-webpack-plugin
loader/utils/getIdentitySourceMap.js
https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/master/loader/utils/getIdentitySourceMap.js
MIT
toFixed: function(value, maxDecimals, roundingFunction, optionals) { var splitValue = value.toString().split('.'), minDecimals = maxDecimals - (optionals || 0), boundedPrecision, optionalsRegExp, power, output; // Use the smallest precision value possible to avoid errors from floating point representation if (splitValue.length === 2) { boundedPrecision = Math.min(Math.max(splitValue[1].length, minDecimals), maxDecimals); } else { boundedPrecision = minDecimals; } power = Math.pow(10, boundedPrecision); // Multiply up by precision, round accurately, then divide and use native toFixed(): output = (roundingFunction(value + 'e+' + boundedPrecision) / power).toFixed(boundedPrecision); if (optionals > maxDecimals - boundedPrecision) { optionalsRegExp = new RegExp('\\.?0{1,' + (optionals - (maxDecimals - boundedPrecision)) + '}$'); output = output.replace(optionalsRegExp, ''); } return output; }
Implementation of toFixed() that treats floats more like decimals Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present problems for accounting- and finance-related software.
toFixed ( value , maxDecimals , roundingFunction , optionals )
javascript
adamwdraper/Numeral-js
numeral.js
https://github.com/adamwdraper/Numeral-js/blob/master/numeral.js
MIT
app.post('/interactions', verifyKeyMiddleware(process.env.PUBLIC_KEY), async function (req, res) { // Interaction id, type and data const { id, type, data } = req.body; /** * Handle verification requests */ if (type === InteractionType.PING) { return res.send({ type: InteractionResponseType.PONG }); } /** * Handle slash command requests * See https://discord.com/developers/docs/interactions/application-commands#slash-commands */ if (type === InteractionType.APPLICATION_COMMAND) { const { name } = data; // "test" command if (name === 'test') { // Send a message into the channel where command was triggered from return res.send({ type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE, data: { // Fetches a random emoji to send from a helper function content: `hello world ${getRandomEmoji()}`, }, }); } console.error(`unknown command: ${name}`); return res.status(400).json({ error: 'unknown command' }); } console.error('unknown interaction type', type); return res.status(400).json({ error: 'unknown interaction type' }); });
Interactions endpoint URL where Discord will send HTTP requests Parse request body and verifies incoming requests using discord-interactions package
(anonymous) ( req , res )
javascript
discord/discord-example-app
app.js
https://github.com/discord/discord-example-app/blob/master/app.js
MIT
function interfaceName (component) { // Root doesn't have splits if (component.splits.length === 0) { return 'ApiRoot' } // // Replace '.'s with '_'s and CamelCase. // return component.splits .map(split => split.replace(/\./g, '_').replace(/./, first => first.toUpperCase())) .join('') }
Get the typescript interface name for a swagger-fluent component. @param {object} component - swagger-fluent Component. @returns {string} TypeScript interface name
interfaceName ( component )
javascript
godaddy/kubernetes-client
scripts/typings.js
https://github.com/godaddy/kubernetes-client/blob/master/scripts/typings.js
MIT
function setup (client) { const kinds = {} _walk(client, kinds) const kindsToGroups = Object.keys(kinds).reduce((acc, kindKey) => { acc[kindKey] = kinds[kindKey].reduce((kind, operation) => { const operationGroup = getOperationGroup(operation) kind[operationGroup] = kind[operationGroup] || [] let hasQueryParameters = false let hasPathParameters = false let hasBodyParameters = false const parameters = operation.parameters || [] parameters.forEach(parameter => { if (parameter.in === 'query') { parameter.isQueryParameter = true hasQueryParameters = true } else if (parameter.in === 'path') { parameter.isPathParameter = true hasPathParameters = true } else if (parameter.in === 'body') { parameter.isBodyParameter = true hasBodyParameters = true } }) operation.hasQueryParameters = hasQueryParameters operation.hasPathParameters = hasPathParameters operation.hasBodyParameters = hasBodyParameters kind[operationGroup].push(operation) return kind }, {}) return acc }, {}) return kindsToGroups }
Setup data for mustache rendering/viewing. @param {object} client - kubernetes-client object. @returns {object} Object mapping kind (e.g., Deployment) to groups (e.g., read or write) of OpenAPI operations.
setup ( client )
javascript
godaddy/kubernetes-client
scripts/docs.js
https://github.com/godaddy/kubernetes-client/blob/master/scripts/docs.js
MIT
function refreshAuth (type, config) { return new Promise((resolve, reject) => { const provider = require(`./auth-providers/${type}.js`) provider.refresh(config) .then(result => { const auth = { bearer: result } return resolve(auth) }) .catch(err => reject(err)) }) }
Refresh whatever authentication {type} is. @param {String} type - type of authentication @param {Object} config - auth provider config @returns {Promise} with request friendly auth object
refreshAuth ( type , config )
javascript
godaddy/kubernetes-client
backends/request/client.js
https://github.com/godaddy/kubernetes-client/blob/master/backends/request/client.js
MIT
function isUpgradeRequired (body) { return body.status === 'Failure' && body.code === 400 && body.message === 'Upgrade request required' }
Determine whether a failed Kubernetes API response is asking for an upgrade @param {object} body - response body object from Kubernetes @property {string} status - request status @property {number} code - previous request's response code @property {message} message - previous request response message @returns {boolean} Upgrade the request
isUpgradeRequired ( body )
javascript
godaddy/kubernetes-client
backends/request/client.js
https://github.com/godaddy/kubernetes-client/blob/master/backends/request/client.js
MIT
constructor (options) { this.requestOptions = options.request || {} let convertedOptions if (!options.kubeconfig) { deprecate('Request() without a .kubeconfig option, see ' + 'https://github.com/godaddy/kubernetes-client/blob/master/merging-with-kubernetes.md') convertedOptions = options } else { convertedOptions = convertKubeconfig(options.kubeconfig) } this.requestOptions.qsStringifyOptions = { indices: false } this.requestOptions.baseUrl = convertedOptions.url this.requestOptions.ca = convertedOptions.ca this.requestOptions.cert = convertedOptions.cert this.requestOptions.key = convertedOptions.key if ('insecureSkipTlsVerify' in convertedOptions) { this.requestOptions.strictSSL = !convertedOptions.insecureSkipTlsVerify } if ('timeout' in convertedOptions) { this.requestOptions.timeout = convertedOptions.timeout } this.authProvider = { type: null } if (convertedOptions.auth) { this.requestOptions.auth = convertedOptions.auth if (convertedOptions.auth.provider) { this.requestOptions.auth = convertedOptions.auth.request this.authProvider = convertedOptions.auth.provider } } }
Internal representation of HTTP request object. @param {object} options - Options object @param {string} options.url - Kubernetes API URL @param {object} options.auth - request library auth object @param {string} options.ca - Certificate authority @param {string} options.cert - Client certificate @param {string} options.key - Client key @param {boolean} options.insecureSkipTlsVerify - Skip the validity check on the server's certificate.
constructor ( options )
javascript
godaddy/kubernetes-client
backends/request/client.js
https://github.com/godaddy/kubernetes-client/blob/master/backends/request/client.js
MIT
async getWebSocket (options) { throw new Error('Request.getWebSocket not implemented') }
@param {object} options - Options object @param {Stream} options.stdin - optional stdin Readable stream @param {Stream} options.stdout - optional stdout Writeable stream @param {Stream} options.stderr - optional stdout Writeable stream @returns {Promise} Promise resolving to a Kubernetes V1 Status object and a WebSocket
getWebSocket ( options )
javascript
godaddy/kubernetes-client
backends/request/client.js
https://github.com/godaddy/kubernetes-client/blob/master/backends/request/client.js
MIT
function getInCluster () { const host = process.env.KUBERNETES_SERVICE_HOST const port = process.env.KUBERNETES_SERVICE_PORT if (!host || !port) { throw new TypeError( 'Unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST' + ' and KUBERNETES_SERVICE_PORT must be defined') } const ca = fs.readFileSync(caPath, 'utf8') const bearer = fs.readFileSync(tokenPath, 'utf8') const namespace = fs.readFileSync(namespacePath, 'utf8') return { url: `https://${host}:${port}`, ca, auth: { bearer }, namespace } }
Returns with in cluster config Based on: https://github.com/kubernetes/client-go/blob/124670e99da15091e13916f0ad4b2b2df2a39cd5/rest/config.go#L274 and http://kubernetes.io/docs/user-guide/accessing-the-cluster/#accessing-the-api-from-a-pod @function getInCluster @returns {Object} { url, cert, auth, namespace }
getInCluster ( )
javascript
godaddy/kubernetes-client
backends/request/config.js
https://github.com/godaddy/kubernetes-client/blob/master/backends/request/config.js
MIT
loadSpec () { return this._getSpec('/openapi/v2') .catch(() => { return this._getSpec('/swagger.json') }) .then(res => { this._addSpec(res) return this }) .catch(err => { throw new Error(`Failed to get /openapi/v2 and /swagger.json: ${err.message}`) }) }
Load swagger.json from kube-apiserver. @returns {Promise} Promise
loadSpec ( )
javascript
godaddy/kubernetes-client
lib/swagger-client.js
https://github.com/godaddy/kubernetes-client/blob/master/lib/swagger-client.js
MIT
const triggerSimulatedOnChange = (element, newValue, prototype) => { const lastValue = element.value; element.value = newValue; const nativeInputValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set; nativeInputValueSetter.call(element, newValue); const event = new Event('input', { bubbles: true }); // React 15 event.simulated = true; // React >= 16 let tracker = element._valueTracker; if (tracker) { tracker.setValue(lastValue); } element.dispatchEvent(event); };
Hacky function to trigger react, angular & vue.js onChange on input
triggerSimulatedOnChange
javascript
marmelab/gremlins.js
src/species/formFiller.js
https://github.com/marmelab/gremlins.js/blob/master/src/species/formFiller.js
MIT
[Actions.shortIncrementStart]: (state, amount) => { console.log('short start'); return loop(state .setIn(['short', 'loading'], true) .setIn(['short', 'failed'], false), Cmd.run(Api.shortIncrement, { successActionCreator: Actions.shortIncrementSucceed, failActionCreator: Actions.shortIncrementFail, args: [amount] }) ) },
The following three reducers start through the process of updating the counter on the short timer. The process starts here and can either fail or succeed randomly, and we've covered both cases.
]
javascript
redux-loop/redux-loop
example/src/index.js
https://github.com/redux-loop/redux-loop/blob/master/example/src/index.js
MIT
[Actions.longIncrementStart]: (state, amount) => { console.log('long start'); return loop(state .setIn(['long', 'loading'], true) .setIn(['long', 'failed'], false), Cmd.run(Api.longIncrement, { successActionCreator: Actions.longIncrementSucceed, failActionCreator: Actions.longIncrementFail, args: [amount] })) },
The following three reducers perform the same such behavior for the counter on the long timer.
]
javascript
redux-loop/redux-loop
example/src/index.js
https://github.com/redux-loop/redux-loop/blob/master/example/src/index.js
MIT
[Actions.incrementBothStart]: (state, amount) => { console.log('both start'); return loop(state, Cmd.list([ Cmd.action(Actions.shortIncrementStart(amount)), Cmd.action(Actions.longIncrementStart(amount)), ]) )},
This final action groups the two increment start actions with a list.
]
javascript
redux-loop/redux-loop
example/src/index.js
https://github.com/redux-loop/redux-loop/blob/master/example/src/index.js
MIT
const Counter = ({ loading, count, failed, onClick, name }) => { const failureMessage = failed ? <div>Failed to complete increment for {name}</div> : null; return ( <div style={{ opacity: loading ? 0.5 : 1, padding: 10 }}> <div> <button disabled={loading} onClick={onClick}> {loading ? 'Loading...' : `Add 1 to ${name} counter`} </button> </div> <div> {name} counter: {count} </div> {failureMessage} </div> ); }
Here we set up a simple, reusable "dumb" component in the redux nomenclature which we can reuse to render each counter since they have a repeatable structure.
Counter
javascript
redux-loop/redux-loop
example/src/index.js
https://github.com/redux-loop/redux-loop/blob/master/example/src/index.js
MIT
const connector = connect((state) => ({ model: state.toJS() }));
Careful here! Our top level state is a an Immutable Map, and `connect()` in react-redux attempts to spread our state object over our components, so we need to make sure the state is contained in a single property within our component's `props`. We'll call it `model` here, to be a little more like Elm 😄, and we'll also deserialize it to a plain object for convenience.
state.toJS ( )
javascript
redux-loop/redux-loop
example/src/index.js
https://github.com/redux-loop/redux-loop/blob/master/example/src/index.js
MIT
function initMobileMenu () { var mobileBar = document.getElementById('mobile-bar') var sidebar = document.querySelector('.sidebar') var menuButton = mobileBar.querySelector('.menu-button') menuButton.addEventListener('click', function () { sidebar.classList.toggle('open') }) document.body.addEventListener('click', function (e) { if (e.target !== menuButton && !sidebar.contains(e.target)) { sidebar.classList.remove('open') } }) // Toggle sidebar on swipe var start = {}, end = {} document.body.addEventListener('touchstart', function (e) { start.x = e.changedTouches[0].clientX start.y = e.changedTouches[0].clientY }) document.body.addEventListener('touchend', function (e) { end.y = e.changedTouches[0].clientY end.x = e.changedTouches[0].clientX var xDiff = end.x - start.x var yDiff = end.y - start.y if (Math.abs(xDiff) > Math.abs(yDiff)) { if (xDiff > 0 && start.x <= 80) sidebar.classList.add('open') else sidebar.classList.remove('open') } }) }
Mobile burger menu button and gesture for toggling sidebar
initMobileMenu ( )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/common.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/common.js
MIT
function isObject(obj) { return obj !== null && typeof obj === 'object'; }
Quick object check - this is primarily used to tell objects from primitive values when we know the value is a JSON-compliant type.
isObject ( obj )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
function toNumber(val) { var n = parseFloat(val); return isNaN(n) ? val : n; }
Convert an input value to a number for persistence. If the conversion fails, return original string.
toNumber ( val )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
function makeMap(str, expectsLowerCase) { var map = Object.create(null); var list = str.split(','); for (var i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? function (val) { return map[val.toLowerCase()]; } : function (val) { return map[val]; }; }
Make a map and return a function for checking if a key is in that map.
makeMap ( str , expectsLowerCase )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
function polyfillBind(fn, ctx) { function boundFn(a) { var l = arguments.length; return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx); } boundFn._length = fn.length; return boundFn; }
Simple bind polyfill for environments that do not support it, e.g., PhantomJS 1.x. Technically, we don't need this anymore since native bind is now performant enough in most browsers. But removing it would mean breaking code that was able to run in PhantomJS 1.x, so this must be kept for backward compatibility. /* istanbul ignore next
polyfillBind ( fn , ctx )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
function getCurrentInstance() { return currentInstance && { proxy: currentInstance }; }
This is exposed for compatibility with v3 (e.g. some functions in VueUse relies on it). Do not use this internally, just use `currentInstance`. @internal this function needs manual type declaration because it relies on previously manually authored types from Vue 2
getCurrentInstance ( )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
var Dep = /** @class */ (function () { function Dep() { // pending subs cleanup this._pending = false; this.id = uid$2++; this.subs = []; } Dep.prototype.addSub = function (sub) { this.subs.push(sub); }; Dep.prototype.removeSub = function (sub) { // #12696 deps with massive amount of subscribers are extremely slow to // clean up in Chromium // to workaround this, we unset the sub for now, and clear them on // next scheduler flush. this.subs[this.subs.indexOf(sub)] = null; if (!this._pending) { this._pending = true; pendingCleanupDeps.push(this); } }; Dep.prototype.depend = function (info) { if (Dep.target) { Dep.target.addDep(this); if (info && Dep.target.onTrack) { Dep.target.onTrack(__assign({ effect: Dep.target }, info)); } } }; Dep.prototype.notify = function (info) { // stabilize the subscriber list first var subs = this.subs.filter(function (s) { return s; }); if (!config.async) { // subs aren't sorted in scheduler if not running async // we need to sort them now to make sure they fire in correct // order subs.sort(function (a, b) { return a.id - b.id; }); } for (var i = 0, l = subs.length; i < l; i++) { var sub = subs[i]; if (info) { sub.onTrigger && sub.onTrigger(__assign({ effect: subs[i] }, info)); } sub.update(); } }; return Dep; }());
A dep is an observable that can have multiple directives subscribing to it. @internal
(anonymous) ( )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
function useSlots() { return getContext().slots; }
@internal use manual type def because public setup context type relies on legacy VNode types
useSlots ( )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
function useListeners() { return getContext().listeners; }
Vue 2 only @internal use manual type def because public setup context type relies on legacy VNode types
useListeners ( )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
function mergeDefaults(raw, defaults) { var props = isArray(raw) ? raw.reduce(function (normalized, p) { return ((normalized[p] = {}), normalized); }, {}) : raw; for (var key in defaults) { var opt = props[key]; if (opt) { if (isArray(opt) || isFunction(opt)) { props[key] = { type: opt, default: defaults[key] }; } else { opt.default = defaults[key]; } } else if (opt === null) { props[key] = { default: defaults[key] }; } else { warn$2("props default key \"".concat(key, "\" has no corresponding declaration.")); } } return props; }
Runtime helper for merging default declarations. Imported by compiled code only. @internal
mergeDefaults ( raw , defaults )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
function queueActivatedComponent(vm) { // setting _inactive to false here so that a render function can // rely on checking whether it's in an inactive tree (e.g. router-view) vm._inactive = false; activatedChildren.push(vm); }
Queue a kept-alive component that was activated during patch. The queue will be processed after the entire tree has been patched.
queueActivatedComponent ( vm )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
function queueWatcher(watcher) { var id = watcher.id; if (has[id] != null) { return; } if (watcher === Dep.target && watcher.noRecurse) { return; } has[id] = true; if (!flushing) { queue.push(watcher); } else { // if already flushing, splice the watcher based on its id // if already past its id, it will be run next immediately. var i = queue.length - 1; while (i > index$1 && queue[i].id > watcher.id) { i--; } queue.splice(i + 1, 0, watcher); } // queue the flush if (!waiting) { waiting = true; if (!config.async) { flushSchedulerQueue(); return; } nextTick(flushSchedulerQueue); } }
Push a watcher into the watcher queue. Jobs with duplicate IDs will be skipped unless it's pushed when the queue is being flushed.
queueWatcher ( watcher )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
function h(type, props, children) { if (!currentInstance) { warn$2("globally imported h() can only be invoked when there is an active " + "component instance, e.g. synchronously in a component's render or setup function."); } return createElement$1(currentInstance, type, props, children, 2, true); }
@internal this function needs manual public type declaration because it relies on previously manually authored types from Vue 2
h ( type , props , children )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
function useCssVars(getter) { if (!inBrowser && !false) return; var instance = currentInstance; if (!instance) { warn$2("useCssVars is called without current active component instance."); return; } watchPostEffect(function () { var el = instance.$el; var vars = getter(instance, instance._setupProxy); if (el && el.nodeType === 1) { var style = el.style; for (var key in vars) { style.setProperty("--".concat(key), vars[key]); } } }); }
Runtime helper for SFC's CSS variable injection feature. @private
useCssVars ( getter )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
function defineAsyncComponent(source) { if (isFunction(source)) { source = { loader: source }; } var loader = source.loader, loadingComponent = source.loadingComponent, errorComponent = source.errorComponent, _a = source.delay, delay = _a === void 0 ? 200 : _a, timeout = source.timeout, // undefined = never times out _b = source.suspensible, // undefined = never times out suspensible = _b === void 0 ? false : _b, // in Vue 3 default is true userOnError = source.onError; if (suspensible) { warn$2("The suspensiblbe option for async components is not supported in Vue2. It is ignored."); } var pendingRequest = null; var retries = 0; var retry = function () { retries++; pendingRequest = null; return load(); }; var load = function () { var thisRequest; return (pendingRequest || (thisRequest = pendingRequest = loader() .catch(function (err) { err = err instanceof Error ? err : new Error(String(err)); if (userOnError) { return new Promise(function (resolve, reject) { var userRetry = function () { return resolve(retry()); }; var userFail = function () { return reject(err); }; userOnError(err, userRetry, userFail, retries + 1); }); } else { throw err; } }) .then(function (comp) { if (thisRequest !== pendingRequest && pendingRequest) { return pendingRequest; } if (!comp) { warn$2("Async component loader resolved to undefined. " + "If you are using retry(), make sure to return its return value."); } // interop module default if (comp && (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) { comp = comp.default; } if (comp && !isObject(comp) && !isFunction(comp)) { throw new Error("Invalid async component load result: ".concat(comp)); } return comp; }))); }; return function () { var component = load(); return { component: component, delay: delay, timeout: timeout, error: errorComponent, loading: loadingComponent }; }; }
v3-compatible async component API. @internal the type is manually declared in <root>/types/v3-define-async-component.d.ts because it relies on existing manual types
defineAsyncComponent ( source )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
function defineComponent(options) { return options; }
@internal type is manually declared in <root>/types/v3-define-component.d.ts
defineComponent ( options )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
Watcher.prototype.update = function () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true; } else if (this.sync) { this.run(); } else { queueWatcher(this); } };
Subscriber interface. Will be called when a dependency changes.
Watcher.prototype.update ( )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
Watcher.prototype.run = function () { if (this.active) { var value = this.get(); if (value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated. isObject(value) || this.deep) { // set new value var oldValue = this.value; this.value = value; if (this.user) { var info = "callback for watcher \"".concat(this.expression, "\""); invokeWithErrorHandling(this.cb, this.vm, [value, oldValue], this.vm, info); } else { this.cb.call(this.vm, value, oldValue); } } } };
Scheduler job interface. Will be called by the scheduler.
Watcher.prototype.run ( )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
Watcher.prototype.evaluate = function () { this.value = this.get(); this.dirty = false; };
Evaluate the value of the watcher. This only gets called for lazy watchers.
Watcher.prototype.evaluate ( )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
Watcher.prototype.depend = function () { var i = this.deps.length; while (i--) { this.deps[i].depend(); } };
Depend on all deps collected by this watcher.
Watcher.prototype.depend ( )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
Watcher.prototype.teardown = function () { if (this.vm && !this.vm._isBeingDestroyed) { remove$2(this.vm._scope.effects, this); } if (this.active) { var i = this.deps.length; while (i--) { this.deps[i].removeSub(this); } this.active = false; if (this.onStop) { this.onStop(); } } };
Remove self from all dependencies' subscriber list.
Watcher.prototype.teardown ( )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
Watcher.prototype.get = function () { pushTarget(this); var value; var vm = this.vm; try { value = this.getter.call(vm, vm); } catch (e) { if (this.user) { handleError(e, vm, "getter for watcher \"".concat(this.expression, "\"")); } else { throw e; } } finally { // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value); } popTarget(); this.cleanupDeps(); } return value; }; /** * Add a dependency to this directive. */ Watcher.prototype.addDep = function (dep) { var id = dep.id; if (!this.newDepIds.has(id)) { this.newDepIds.add(id); this.newDeps.push(dep); if (!this.depIds.has(id)) { dep.addSub(this); } } }; /** * Clean up for dependency collection. */ Watcher.prototype.cleanupDeps = function () { var i = this.deps.length; while (i--) { var dep = this.deps[i]; if (!this.newDepIds.has(dep.id)) { dep.removeSub(this); } } var tmp = this.depIds; this.depIds = this.newDepIds; this.newDepIds = tmp; this.newDepIds.clear(); tmp = this.deps; this.deps = this.newDeps; this.newDeps = tmp; this.newDeps.length = 0; }; /** * Subscriber interface. * Will be called when a dependency changes. */ Watcher.prototype.update = function () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true; } else if (this.sync) { this.run(); } else { queueWatcher(this); } }; /** * Scheduler job interface. * Will be called by the scheduler. */ Watcher.prototype.run = function () { if (this.active) { var value = this.get(); if (value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated. isObject(value) || this.deep) { // set new value var oldValue = this.value; this.value = value; if (this.user) { var info = "callback for watcher \"".concat(this.expression, "\""); invokeWithErrorHandling(this.cb, this.vm, [value, oldValue], this.vm, info); } else { this.cb.call(this.vm, value, oldValue); } } } }; /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */ Watcher.prototype.evaluate = function () { this.value = this.get(); this.dirty = false; }; /** * Depend on all deps collected by this watcher. */ Watcher.prototype.depend = function () { var i = this.deps.length; while (i--) { this.deps[i].depend(); } }; /** * Remove self from all dependencies' subscriber list. */ Watcher.prototype.teardown = function () { if (this.vm && !this.vm._isBeingDestroyed) { remove$2(this.vm._scope.effects, this); } if (this.active) { var i = this.deps.length; while (i--) { this.deps[i].removeSub(this); } this.active = false; if (this.onStop) { this.onStop(); } } }; return Watcher; }());
Evaluate the getter, and re-collect dependencies.
Watcher.prototype.get ( )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
function mergeLifecycleHook(parentVal, childVal) { var res = childVal ? parentVal ? parentVal.concat(childVal) : isArray(childVal) ? childVal : [childVal] : parentVal; return res ? dedupeHooks(res) : res; }
Hooks and props are merged as arrays.
mergeLifecycleHook ( parentVal , childVal )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
function getType(fn) { var match = fn && fn.toString().match(functionTypeCheckRE); return match ? match[1] : ''; }
Use function string name to check built-in types, because a simple equality check will fail when running across different vms / iframes.
getType ( fn )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
function query(el) { if (typeof el === 'string') { var selected = document.querySelector(el); if (!selected) { warn$2('Cannot find element: ' + el); return document.createElement('div'); } return selected; } else { return el; } }
Query an element selector if it's not an element already.
query ( el )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
function genAssignmentCode(value, assignment) { var res = parseModel(value); if (res.key === null) { return "".concat(value, "=").concat(assignment); } else { return "$set(".concat(res.exp, ", ").concat(res.key, ", ").concat(assignment, ")"); } }
Cross-platform codegen helper for generating v-model value assignment code.
genAssignmentCode ( value , assignment )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
function getStyle(vnode, checkChild) { var res = {}; var styleData; if (checkChild) { var childNode = vnode; while (childNode.componentInstance) { childNode = childNode.componentInstance._vnode; if (childNode && childNode.data && (styleData = normalizeStyleData(childNode.data))) { extend(res, styleData); } } } if ((styleData = normalizeStyleData(vnode.data))) { extend(res, styleData); } var parentNode = vnode; // @ts-expect-error parentNode.parent not VNodeWithData while ((parentNode = parentNode.parent)) { if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) { extend(res, styleData); } } return res; }
parent component style should be after child's so that parent component's style could override it
getStyle ( vnode , checkChild )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
function addClass(el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return; } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(whitespaceRE$1).forEach(function (c) { return el.classList.add(c); }); } else { el.classList.add(cls); } } else { var cur = " ".concat(el.getAttribute('class') || '', " "); if (cur.indexOf(' ' + cls + ' ') < 0) { el.setAttribute('class', (cur + cls).trim()); } } }
Add class with compatibility for SVG since classList is not supported on SVG elements in IE
addClass ( el , cls )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
function removeClass(el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return; } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(whitespaceRE$1).forEach(function (c) { return el.classList.remove(c); }); } else { el.classList.remove(cls); } if (!el.classList.length) { el.removeAttribute('class'); } } else { var cur = " ".concat(el.getAttribute('class') || '', " "); var tar = ' ' + cls + ' '; while (cur.indexOf(tar) >= 0) { cur = cur.replace(tar, ' '); } cur = cur.trim(); if (cur) { el.setAttribute('class', cur); } else { el.removeAttribute('class'); } } }
Remove class with compatibility for SVG since classList is not supported on SVG elements in IE
removeClass ( el , cls )
javascript
vuejs/v2.cn.vuejs.org
themes/vue/source/js/vue.js
https://github.com/vuejs/v2.cn.vuejs.org/blob/master/themes/vue/source/js/vue.js
MIT
AppRegistry.registerComponent('snowflake', () => Snowflake)
registerComponent to the AppRegistery and off we go....
(anonymous)
javascript
bartonhammond/snowflake
src/snowflake.js
https://github.com/bartonhammond/snowflake/blob/master/src/snowflake.js
MIT
getInitialState () { return { text: '', isDisabled: true } },
## Header.class set the initial state of having the button be disabled.
getInitialState ( )
javascript
bartonhammond/snowflake
src/components/Header.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/Header.js
MIT
_onPressMark () { this.props.onGetState(!this.props.showState) },
### _onPressMark Call the onGetState action passing the state prop
_onPressMark ( )
javascript
bartonhammond/snowflake
src/components/Header.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/Header.js
MIT
_onChangeText (text) { this.setState({ text, isDisabled: false }) },
### _onChangeText when the textinput value changes, set the state for that component
_onChangeText ( text )
javascript
bartonhammond/snowflake
src/components/Header.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/Header.js
MIT
_updateStateButtonPress () { this.props.onSetState(this.state.text) },
### _updateStateButtonPress When the button for the state is pressed, call ```onSetState```
_updateStateButtonPress ( )
javascript
bartonhammond/snowflake
src/components/Header.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/Header.js
MIT
checkError (obj) { let errorMessage = '' if (!_.isNull(obj)) { if (!_.isUndefined(obj.error)) { if (!_.isUndefined(obj.error.error)) { errorMessage = obj.error.error } else { errorMessage = obj.error } } else { errorMessage = obj } if (errorMessage !== '') { if (!_.isUndefined(errorMessage.message)) { SimpleAlert.alert('Error', errorMessage.message) } else { SimpleAlert.alert('Error', errorMessage) } } }// isNull }
### checkErro determine if there is an error and how deep it is. Take the deepest level as the message and display it
checkError ( obj )
javascript
bartonhammond/snowflake
src/components/ErrorAlert.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/ErrorAlert.js
MIT
componentWillReceiveProps (nextprops) { this.setState({ value: { username: nextprops.auth.form.fields.username, email: nextprops.auth.form.fields.email, password: nextprops.auth.form.fields.password, passwordAgain: nextprops.auth.form.fields.passwordAgain } }) }
### componentWillReceiveProps As the properties are validated they will be set here.
componentWillReceiveProps ( nextprops )
javascript
bartonhammond/snowflake
src/components/LoginRender.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/LoginRender.js
MIT
onChange (value) { if (value.username !== '') { this.props.actions.onAuthFormFieldChange('username', value.username) } if (value.email !== '') { this.props.actions.onAuthFormFieldChange('email', value.email) } if (value.password !== '') { this.props.actions.onAuthFormFieldChange('password', value.password) } if (value.passwordAgain !== '') { this.props.actions.onAuthFormFieldChange('passwordAgain', value.passwordAgain) } this.setState( {value} ) }
### onChange As the user enters keys, this is called for each key stroke. Rather then publish the rules for each of the fields, I find it better to display the rules required as long as the field doesn't meet the requirements. *Note* that the fields are validated by the authReducer
onChange ( value )
javascript
bartonhammond/snowflake
src/components/LoginRender.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/LoginRender.js
MIT
return ( <View style={styles.container}> <ScrollView horizontal={false} width={width} height={height}> <View> <Header isFetching={this.props.auth.form.isFetching} showState={this.props.global.showState} currentState={this.props.global.currentState} onGetState={this.props.actions.getState} onSetState={this.props.actions.setState} /> <View style={styles.inputs}> <LoginForm formType={formType} form={this.props.auth.form} value={this.state.value} onChange={self.onChange.bind(self)} /> {passwordCheckbox} </View> <FormButton isDisabled={!this.props.auth.form.isValid || this.props.auth.form.isFetching} onPress={onButtonPress} buttonText={loginButtonText} /> <View > <View style={styles.forgotContainer}> {leftMessage} {rightMessage} </View> </View> </View> </ScrollView> </View> ) }
The LoginForm is now defined with the required fields. Just surround it with the Header and the navigation messages Note how the button too is disabled if we're fetching. The header props are mostly for support of Hot reloading. See the docs for Header for more info.
return ( < View style = { styles . container } > < ScrollView horizontal = { false } width = { width } height = { height } > < View > < Header isFetching = { this . props . auth . form . isFetching } showState = { this . props . global . showState } currentState = { this . props . global . currentState } onGetState = { this . props . actions . getState } onSetState = { this . props . actions . setState } / > < View style = { styles . inputs } > < LoginForm formType = { formType } form = { this . props . auth . form } value = { this . state . value } onChange = { self . onChange . bind ( self )
javascript
bartonhammond/snowflake
src/components/LoginRender.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/LoginRender.js
MIT
getDefaultProps: function () { return { onCheck: null, onUncheck: null, icon_check: 'check-square', icon_open: 'square-o', size: 30, backgroundColor: 'white', color: 'grey', iconSize: 'normal', checked: false, text: 'MISSING TEXT', disabled: false } },
### getDefaultProps set the default values
getDefaultProps ( )
javascript
bartonhammond/snowflake
src/components/ItemCheckbox.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/ItemCheckbox.js
MIT
getInitialState: function () { return { checked: this.props.checked, bg_color: this.props.backgroundColor } },
### getInitialState Set the box to be checked or not
getInitialState ( )
javascript
bartonhammond/snowflake
src/components/ItemCheckbox.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/ItemCheckbox.js
MIT
_getCircleCheckStyle: function () { return { width: this.props.size, height: this.props.size, backgroundColor: this.state.bg_color, borderColor: this.props.color, borderWidth: 2, borderRadius: this.props.size / 2, justifyContent: 'center', alignItems: 'center', padding: 2 } },
### _getCircleCheckSytel merge the props styles w/ some defaults
_getCircleCheckStyle ( )
javascript
bartonhammond/snowflake
src/components/ItemCheckbox.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/ItemCheckbox.js
MIT
_completeProgress: function () { if (this.state.checked) { this.setState({ checked: false, bg_color: this.props.backgroundColor }) if (this.props.onUncheck) { this.props.onUncheck() } } else { this.setState({ checked: true, bg_color: this.props.color }) if (this.props.onCheck) { this.props.onCheck() } } },
### _completeProgress If the checkbox is pressable, figure out what state it's in and what the display should look like
_completeProgress ( )
javascript
bartonhammond/snowflake
src/components/ItemCheckbox.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/ItemCheckbox.js
MIT
componentDidMount: function () { if (this.props.checked) { this._completeProgress() } },
### componentDidMount If there is a ```checked``` property, set the UI appropriately
componentDidMount ( )
javascript
bartonhammond/snowflake
src/components/ItemCheckbox.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/ItemCheckbox.js
MIT
render: function () { var iconName = this.props.icon_open if (this.state.checked) { iconName = this.props.icon_check } if (this.props.disabled) { iconName = this.props.checked ? this.props.icon_check : this.props.icon_open return ( <View style={this.props.style}> <TouchableWithoutFeedback> <View style={{ flexDirection: 'row', flex: 1 }}> <Icon name={iconName} size={20} /> <Text> {this.props.text}</Text> </View> </TouchableWithoutFeedback> </View> ) } else { return ( <View style={this.props.style}> <TouchableHighlight onPress={this._completeProgress} > <View style={{ flexDirection: 'row', flex: 1 }}> <Icon name={iconName} size={20} /> <Text> {this.props.text}</Text> </View> </TouchableHighlight> </View> ) } }
### render Use Touchable with or without Feedback depending on ```disabled```. Set the ```iconName``` depending on if checked
render ( )
javascript
bartonhammond/snowflake
src/components/ItemCheckbox.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/ItemCheckbox.js
MIT
it('if not disabled and checked, it should display check-square and text', () => { const props = { checked: true, text: 'TextShouldDisplay', disabled: false } renderer.render(<ItemCheckbox {...props} />) const tree = renderer.getRenderOutput() expect(tree).toMatchSnapshot() })
### if not disabled and checked, it should display check-square and text change the props and call ```testItemCheckbox``` to validate
(anonymous)
javascript
bartonhammond/snowflake
src/components/__tests__/ItemCheckbox-test.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/__tests__/ItemCheckbox-test.js
MIT
it('if not disabled and not checked, it should display square-o and text', () => { const props = { checked: false, text: 'TextShouldDisplay', disabled: false } renderer.render(<ItemCheckbox {...props} />) const tree = renderer.getRenderOutput() expect(tree).toMatchSnapshot() })
### if not disabled and not checked, it should display square-o and text change the props and call ```testItemCheckbox``` to validate
(anonymous)
javascript
bartonhammond/snowflake
src/components/__tests__/ItemCheckbox-test.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/__tests__/ItemCheckbox-test.js
MIT
it('if disabled and checked, it should display check-square and text', () => { const props = { checked: true, text: 'TextShouldDisplay', disabled: true } renderer.render(<ItemCheckbox {...props} />) const tree = renderer.getRenderOutput() expect(tree).toMatchSnapshot() })
### if disabled and checked, it should display check-square and text change the props and call ```testItemCheckbox``` to validate
(anonymous)
javascript
bartonhammond/snowflake
src/components/__tests__/ItemCheckbox-test.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/__tests__/ItemCheckbox-test.js
MIT
it('if disabled and not checked, it should display square-o and text', () => { const props = { checked: false, text: 'TextShouldDisplay', disabled: true } renderer.render(<ItemCheckbox {...props} />) const tree = renderer.getRenderOutput() expect(tree).toMatchSnapshot() })
### if disabled and not checked, it should display square-o and text change the props and call ```testItemCheckbox``` to validate
(anonymous)
javascript
bartonhammond/snowflake
src/components/__tests__/ItemCheckbox-test.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/__tests__/ItemCheckbox-test.js
MIT
function snapshotForm (props) { renderer.render(<LoginForm {...props} />) const tree = renderer.getRenderOutput() expect(tree).toMatchSnapshot() }
### snapshotForm Depending on the state, this function validates that the rendered component has the correct data
snapshotForm ( props )
javascript
bartonhammond/snowflake
src/components/__tests__/LoginForm-test.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/__tests__/LoginForm-test.js
MIT
it('password fields are not secured if shown', () => { let form = { isFetching: false, fields: { emailHasError: false, showPassword: true } } let value = { email: 'email' } let props = { form: form, formType: FORGOT_PASSWORD, value: value, onChange: () => {} } snapshotForm(props) }) }) })// describe LoginFormTest
### password fields are not secured if shown change the props and call ```snapshotForm``` to validate
(anonymous)
javascript
bartonhammond/snowflake
src/components/__tests__/LoginForm-test.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/__tests__/LoginForm-test.js
MIT
it('should be display empty text when not fetching', () => { const props = { isFetching: false } renderer.render(<Header {...props} />) const tree = renderer.getRenderOutput() expect(tree).toMatchSnapshot() })
### it should be display empty text when not fetching render the header when not fetching
(anonymous)
javascript
bartonhammond/snowflake
src/components/__tests__/Header-test.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/__tests__/Header-test.js
MIT
it('should be display spinner when fetching', () => { const props = { isFetching: true } renderer.render(<Header {...props} />) const tree = renderer.getRenderOutput() expect(tree).toMatchSnapshot() })
### it should be display spinner when fetching When fetching, the GiftedSpinner should display
(anonymous)
javascript
bartonhammond/snowflake
src/components/__tests__/Header-test.js
https://github.com/bartonhammond/snowflake/blob/master/src/components/__tests__/Header-test.js
MIT
async login (data) { var formBody = [] for (var property in data) { var encodedKey = encodeURIComponent(property) var encodedValue = encodeURIComponent(data[property]) formBody.push(encodedKey + '=' + encodedValue) } formBody = formBody.join('&') return await this._fetch({ method: 'GET', url: '/login?' + formBody }) .then((res) => { return res.json().then(function (json) { if (res.status === 200 || res.status === 201) { return json } else { throw (json) } }) }) .catch((error) => { throw (error) }) }
### login encode the data and and call _fetch @param data {username: "barton", password: "Passw0rd!"} @returns createdAt: "2015-12-30T15:29:36.611Z" updatedAt: "2015-12-30T16:08:50.419Z" objectId: "Z4yvP19OeL" email: "[email protected]" sessionToken: "r:Kt9wXIBWD0dNijNIq2u5rRllW" username: "barton"
login ( data )
javascript
bartonhammond/snowflake
src/lib/Parse.js
https://github.com/bartonhammond/snowflake/blob/master/src/lib/Parse.js
MIT
async logout () { return await this._fetch({ method: 'POST', url: '/logout', body: {} }) .then((res) => { if ((res.status === 200 || res.status === 201 || res.status === 400) || (res.code === 209)) { return {} } else { throw new Error({code: 404, error: 'unknown error from Parse.com'}) } }) .catch((error) => { throw (error) }) }
### logout prepare the request and call _fetch
logout ( )
javascript
bartonhammond/snowflake
src/lib/Parse.js
https://github.com/bartonhammond/snowflake/blob/master/src/lib/Parse.js
MIT
async resetPassword (data) { return await this._fetch({ method: 'POST', url: '/requestPasswordReset', body: data }) .then((res) => { return res.json().then(function (json) { if ((res.status === 200 || res.status === 201)) { return {} } else { throw (json) } }) }) .catch((error) => { throw (error) }) }
### resetPassword the data is already in a JSON format, so call _fetch @param data {email: "[email protected]"} @returns empty object if error: {code: xxx, error: 'message'}
resetPassword ( data )
javascript
bartonhammond/snowflake
src/lib/Parse.js
https://github.com/bartonhammond/snowflake/blob/master/src/lib/Parse.js
MIT
async getProfile () { return await this._fetch({ method: 'GET', url: '/users/me' }) .then((response) => { return response.json().then(function (res) { if ((response.status === 200 || response.status === 201)) { return res } else { throw (res) } }) }) .catch((error) => { throw (error) }) }
### getProfile Using the sessionToken, we'll get everything about the current user. @returns if good: {createdAt: "2015-12-30T15:29:36.611Z" email: "[email protected]" objectId: "Z4yvP19OeL" sessionToken: "r:uFeYONgIsZMPyxOWVJ6VqJGqv" updatedAt: "2015-12-30T15:29:36.611Z" username: "barton"} if error, {code: xxx, error: 'message'}
getProfile ( )
javascript
bartonhammond/snowflake
src/lib/Parse.js
https://github.com/bartonhammond/snowflake/blob/master/src/lib/Parse.js
MIT