text
stringlengths 2
1.05M
|
|---|
define('ghost-admin/helpers/ember-power-select-is-selected', ['exports', 'ember-power-select/helpers/ember-power-select-is-selected'], function (exports, _emberPowerSelectIsSelected) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, 'default', {
enumerable: true,
get: function () {
return _emberPowerSelectIsSelected.default;
}
});
Object.defineProperty(exports, 'emberPowerSelectIsSelected', {
enumerable: true,
get: function () {
return _emberPowerSelectIsSelected.emberPowerSelectIsSelected;
}
});
});
|
/** CONTENTS
* 1. Toggle "Track Points Checkbox"
* 2. Add Tracking Points
* 3. Remove Tracking Points
*/
// "Show Track Points" CHECKBOX toggle function
$('#show-points').change(function() {
if(this.checked) {
console.log("checked");
showTrackingPoints = true;
addTrackingPoints();
} else {
console.log("unchecked");
showTrackingPoints = false;
removeTrackingPoints();
}
});
var flightTrackingPoints = {};
var newFlightList = [];
// Filter out all the trackingPoints that are to be added
function addTrackingPoints() {
if(showTrackingPoints && selectedFlightID != null) {
newFlightList = flightsData.filter(function(singleFlight) {
return singleFlight.ACID == selectedFlightID;
});
atp();
} else {
alert("please select a flight first");
$('#show-points').prop('checked', false);
}
}
// ADD the tracking Points
function atp() {
for(var i= 0; i < newFlightList.length; i=i+4) {
// Create a circle.
var name = newFlightList[i].ACID+i.toString();
flightTrackingPoints[name] = viewer.entities.add({
name : name,
description: '<div style="height: 500px; width: 500px; background color: white; color: black">helllllo</div>',
position: Cesium.Cartesian3.fromDegrees(newFlightList[i].LON, newFlightList[i].LAT, newFlightList[i].ALTITUDE),
ellipsoid : {
radii : new Cesium.Cartesian3(100.0, 100.0, 100.0),
material : new Cesium.Color(0.19,0.22,0.23,0.7),
outline : false,
minimumRadius: 100.0,
}
});
}
}
// REMOVE the tracking points
function removeTrackingPoints() {
// if(!showTrackingPoints && selectedFlightID != null) {
for(var i=0; i<newFlightList.length; i++) {
if(newFlightList[i].ACID == selectedFlightID) {
var name = newFlightList[i].ACID+i.toString();
if(flightTrackingPoints[name]) {
viewer.entities.remove(flightTrackingPoints[name]);
delete flightTrackingPoints[name];
}
}
}
// }
}
|
const yo = require('yo-yo')
const minixhr = require('minixhr')
const helper = require('../../../lib/helper')
const addTooltip = require('../../ui/tooltip')
const semver = require('semver')
const modalDialogCustom = require('../../ui/modal-dialog-custom')
const css = require('../styles/compile-tab-styles')
import { canUseWorker } from '../../compiler/compiler-utils'
const crossVersions = ['v1.0.0-crossVersion-0.6.0', 'v1.0.1-crossVersion-0.6.0']
class CompilerContainer {
constructor (compileTabLogic, editor, config, queryParams) {
this._view = {}
this.compileTabLogic = compileTabLogic
this.editor = editor
this.config = config
this.queryParams = queryParams
this.data = {
hideWarnings: config.get('hideWarnings') || false,
autoCompile: config.get('autoCompile'),
compileTimeout: null,
timeout: 300,
allversions: null,
selectedVersion: null,
defaultVersion: 'soljson-v0.6.6+commit.6c089d02.js', // this default version is defined: in makeMockCompiler (for browser test) and in package.json (downloadsolc_root) for the builtin compiler
baseurl: 'https://solc-bin.ethereum.org/bin'
}
}
/**
* Update the compilation button with the name of the current file
*/
set currentFile (name = '') {
if (name && name !== '') {
this._setCompilerVersionFromPragma(name)
}
if (!this._view.compilationButton) return
const button = this.compilationButton(name.split('/').pop())
this._disableCompileBtn(!name || (name && !this.isSolFileSelected(name)))
yo.update(this._view.compilationButton, button)
}
isSolFileSelected (currentFile = '') {
if (!currentFile) currentFile = this.config.get('currentFile')
if (!currentFile) return false
const extention = currentFile.substr(currentFile.length - 3, currentFile.length)
return extention.toLowerCase() === 'sol' || extention.toLowerCase() === 'yul'
}
deactivate () {
// deactivate editor listeners
this.editor.event.unregister('contentChanged')
this.editor.event.unregister('sessionSwitched')
}
activate () {
this.currentFile = this.config.get('currentFile')
this.listenToEvents()
}
listenToEvents () {
this.editor.event.register('sessionSwitched', () => {
if (!this._view.compileIcon) return
this.scheduleCompilation()
})
this.compileTabLogic.event.on('startingCompilation', () => {
if (!this._view.compileIcon) return
this._view.compileIcon.setAttribute('title', 'compiling...')
this._view.compileIcon.classList.remove(`${css.bouncingIcon}`)
this._view.compileIcon.classList.add(`${css.spinningIcon}`)
})
this.compileTabLogic.compiler.event.register('compilationDuration', (speed) => {
if (!this._view.warnCompilationSlow) return
if (speed > 1000) {
const msg = `Last compilation took ${speed}ms. We suggest to turn off autocompilation.`
this._view.warnCompilationSlow.setAttribute('title', msg)
this._view.warnCompilationSlow.style.visibility = 'visible'
} else {
this._view.warnCompilationSlow.style.visibility = 'hidden'
}
})
this.editor.event.register('contentChanged', () => {
if (!this._view.compileIcon) return
this.scheduleCompilation()
this._view.compileIcon.classList.add(`${css.bouncingIcon}`) // @TODO: compileView tab
})
this.compileTabLogic.compiler.event.register('loadingCompiler', () => {
if (!this._view.compileIcon) return
this._disableCompileBtn(true)
this._view.compileIcon.setAttribute('title', 'compiler is loading, please wait a few moments.')
this._view.compileIcon.classList.add(`${css.spinningIcon}`)
this._view.warnCompilationSlow.style.visibility = 'hidden'
this._updateLanguageSelector()
})
this.compileTabLogic.compiler.event.register('compilerLoaded', () => {
if (!this._view.compileIcon) return
this._disableCompileBtn(false)
this._view.compileIcon.setAttribute('title', '')
this._view.compileIcon.classList.remove(`${css.spinningIcon}`)
if (this.data.autoCompile) this.compileIfAutoCompileOn()
})
this.compileTabLogic.compiler.event.register('compilationFinished', (success, data, source) => {
if (!this._view.compileIcon) return
this._view.compileIcon.setAttribute('title', 'idle')
this._view.compileIcon.classList.remove(`${css.spinningIcon}`)
this._view.compileIcon.classList.remove(`${css.bouncingIcon}`)
})
}
/**************
* SUBCOMPONENT
*/
compilationButton (name = '') {
const displayed = name || '<no file selected>'
const disabled = name && this.isSolFileSelected() ? '' : 'disabled'
return yo`
<button id="compileBtn" data-id="compilerContainerCompileBtn" class="btn btn-primary btn-block ${disabled} mt-3" title="Compile" onclick="${this.compile.bind(this)}">
<span>${this._view.compileIcon} Compile ${displayed}</span>
</button>
`
}
_disableCompileBtn (shouldDisable) {
let btn = document.getElementById('compileBtn')
if (!btn) return
if (shouldDisable) {
btn.classList.add('disabled')
} else if (this.isSolFileSelected()) {
btn.classList.remove('disabled')
}
}
// Load solc compiler version according to pragma in contract file
_setCompilerVersionFromPragma (filename) {
if (!this.data.allversions) return
this.compileTabLogic.fileManager.getFile(filename).then(data => {
const pragmaArr = data.match(/(pragma solidity (.+?);)/g)
if (pragmaArr && pragmaArr.length === 1) {
const pragmaStr = pragmaArr[0].replace('pragma solidity', '').trim()
const pragma = pragmaStr.substring(0, pragmaStr.length - 1)
const releasedVersions = this.data.allversions.filter(obj => !obj.prerelease).map(obj => obj.version)
const allVersions = this.data.allversions.map(obj => this._retrieveVersion(obj.version))
const currentCompilerName = this._retrieveVersion(this._view.versionSelector.selectedOptions[0].label)
// contains only numbers part, for example '0.4.22'
const pureVersion = this._retrieveVersion()
// is nightly build newer than the last release
const isNewestNightly = currentCompilerName.includes('nightly') && semver.gt(pureVersion, releasedVersions[0])
// checking if the selected version is in the pragma range
const isInRange = semver.satisfies(pureVersion, pragma)
// checking if the selected version is from official compilers list(excluding custom versions) and in range or greater
const isOfficial = allVersions.includes(currentCompilerName)
if (isOfficial && (!isInRange && !isNewestNightly)) {
const compilerToLoad = semver.maxSatisfying(releasedVersions, pragma)
const compilerPath = this.data.allversions.filter(obj => !obj.prerelease && obj.version === compilerToLoad)[0].path
const isCrossVersion = crossVersions.includes(this.data.selectedVersion)
if (isCrossVersion) {
this._updateVersionSelector()
}
if (this.data.selectedVersion !== compilerPath && !isCrossVersion) {
this.data.selectedVersion = compilerPath
this._updateVersionSelector()
}
}
}
})
}
_retrieveVersion (version) {
if (!version) version = this._view.versionSelector.value
return semver.coerce(version) ? semver.coerce(version).version : ''
}
render () {
this.compileTabLogic.compiler.event.register('compilerLoaded', (version) => this.setVersionText(version))
this.fetchAllVersion((allversions, selectedVersion) => {
this.data.allversions = allversions
this.data.selectedVersion = selectedVersion
if (this._view.versionSelector) this._updateVersionSelector()
})
this._view.warnCompilationSlow = yo`<i title="Compilation Slow" style="visibility:hidden" class="${css.warnCompilationSlow} fas fa-exclamation-triangle" aria-hidden="true"></i>`
this._view.compileIcon = yo`<i class="fas fa-sync ${css.icon}" aria-hidden="true"></i>`
this._view.autoCompile = yo`<input class="${css.autocompile} custom-control-input" onchange=${this.updateAutoCompile.bind(this)} data-id="compilerContainerAutoCompile" id="autoCompile" type="checkbox" title="Auto compile">`
this._view.hideWarningsBox = yo`<input class="${css.autocompile} custom-control-input" onchange=${this.hideWarnings.bind(this)} id="hideWarningsBox" type="checkbox" title="Hide warnings">`
if (this.data.autoCompile) this._view.autoCompile.setAttribute('checked', '')
if (this.data.hideWarnings) this._view.hideWarningsBox.setAttribute('checked', '')
this._view.optimize = yo`<input onchange=${this.onchangeOptimize.bind(this)} class="custom-control-input" id="optimize" type="checkbox">`
if (this.compileTabLogic.optimize) this._view.optimize.setAttribute('checked', '')
this._view.versionSelector = yo`
<select onchange="${this.onchangeLoadVersion.bind(this)}" class="custom-select" id="versionSelector" disabled>
<option disabled selected>${this.data.defaultVersion}</option>
</select>`
this._view.languageSelector = yo`
<select onchange="${this.onchangeLanguage.bind(this)}" class="custom-select" id="compilierLanguageSelector" title="Available since v0.5.7">
<option>Solidity</option>
<option>Yul</option>
</select>`
this._view.version = yo`<span id="version"></span>`
this._view.evmVersionSelector = yo`
<select onchange="${this.onchangeEvmVersion.bind(this)}" class="custom-select" id="evmVersionSelector">
<option value="default">compiler default</option>
<option>istanbul</option>
<option>petersburg</option>
<option>constantinople</option>
<option>byzantium</option>
<option>spuriousDragon</option>
<option>tangerineWhistle</option>
<option>homestead</option>
</select>`
if (this.compileTabLogic.evmVersion) {
let s = this._view.evmVersionSelector
let i
for (i = 0; i < s.options.length; i++) {
if (s.options[i].value === this.compileTabLogic.evmVersion) {
break
}
}
if (i === s.options.length) { // invalid evmVersion from queryParams
s.selectedIndex = 0 // compiler default
this.onchangeEvmVersion()
} else {
s.selectedIndex = i
}
}
this._view.compilationButton = this.compilationButton()
this._view.includeNightlies = yo`
<input class="mr-2 custom-control-input" id="nightlies" type="checkbox" onchange=${() => this._updateVersionSelector()}>
`
this._view.compileContainer = yo`
<section>
<!-- Select Compiler Version -->
<article>
<header class="${css.compilerSection} border-bottom">
<div class="mb-2">
<label class="${css.compilerLabel} form-check-label" for="versionSelector">
Compiler
<button class="far fa-plus-square border-0 p-0 mx-2 btn-sm" onclick="${(e) => this.promtCompiler(e)}" title="Add a custom compiler with URL"></button>
</label>
${this._view.versionSelector}
</div>
<div class="mb-2 ${css.nightlyBuilds} custom-control custom-checkbox">
${this._view.includeNightlies}
<label for="nightlies" class="form-check-label custom-control-label">Include nightly builds</label>
</div>
<div class="mb-2">
<label class="${css.compilerLabel} form-check-label" for="compilierLanguageSelector">Language</label>
${this._view.languageSelector}
</div>
<div class="mb-2">
<label class="${css.compilerLabel} form-check-label" for="evmVersionSelector">EVM Version</label>
${this._view.evmVersionSelector}
</div>
<div class="mt-3">
<p class="mt-2 ${css.compilerLabel}">Compiler Configuration</p>
<div class="mt-2 ${css.compilerConfig} custom-control custom-checkbox">
${this._view.autoCompile}
<label class="form-check-label custom-control-label" for="autoCompile">Auto compile</label>
</div>
<div class="mt-2 ${css.compilerConfig} custom-control custom-checkbox">
${this._view.optimize}
<label class="form-check-label custom-control-label" for="optimize">Enable optimization</label>
</div>
<div class="mt-2 ${css.compilerConfig} custom-control custom-checkbox">
${this._view.hideWarningsBox}
<label class="form-check-label custom-control-label" for="hideWarningsBox">Hide warnings</label>
</div>
</div>
${this._view.compilationButton}
</header>
</article>
<!-- Config -->
</section>`
return this._view.compileContainer
}
promtCompiler () {
modalDialogCustom.prompt(
'Add a custom compiler',
'URL',
'',
(url) => this.addCustomCompiler(url)
)
}
addCustomCompiler (url) {
this.data.selectedVersion = this._view.versionSelector.value
this._updateVersionSelector(url)
}
updateAutoCompile (event) {
this.config.set('autoCompile', this._view.autoCompile.checked)
}
compile (event) {
const currentFile = this.config.get('currentFile')
if (!this.isSolFileSelected()) return
this._setCompilerVersionFromPragma(currentFile)
this.compileTabLogic.runCompiler()
}
compileIfAutoCompileOn () {
if (this.config.get('autoCompile')) {
this.compile()
}
}
hideWarnings (event) {
this.config.set('hideWarnings', this._view.hideWarningsBox.checked)
this.compileIfAutoCompileOn()
}
onchangeOptimize () {
this.compileTabLogic.setOptimize(!!this._view.optimize.checked)
this.compileIfAutoCompileOn()
}
onchangeLanguage (event) {
this.compileTabLogic.setLanguage(event.target.value)
this.compileIfAutoCompileOn()
}
onchangeEvmVersion (_) {
let s = this._view.evmVersionSelector
let v = s.value
if (v === 'default') {
v = null
}
this.compileTabLogic.setEvmVersion(v)
this.compileIfAutoCompileOn()
}
onchangeLoadVersion (event) {
this.data.selectedVersion = this._view.versionSelector.value
this._updateVersionSelector()
this._updateLanguageSelector()
}
_shouldBeAdded (version) {
return !version.includes('nightly') ||
(version.includes('nightly') && this._view.includeNightlies.checked)
}
_updateVersionSelector (customUrl = '') {
// update selectedversion of previous one got filtered out
if (!this.data.selectedVersion || !this._shouldBeAdded(this.data.selectedVersion)) {
this.data.selectedVersion = this.data.defaultVersion
}
this._view.versionSelector.innerHTML = ''
this.data.allversions.forEach(build => {
const option = build.path === this.data.selectedVersion
? yo`<option value="${build.path}" selected>${build.longVersion}</option>`
: yo`<option value="${build.path}">${build.longVersion}</option>`
if (this._shouldBeAdded(option.innerText)) {
this._view.versionSelector.appendChild(option)
}
})
this._view.versionSelector.removeAttribute('disabled')
this.queryParams.update({ version: this.data.selectedVersion })
let url
if (customUrl !== '') {
this.data.selectedVersion = customUrl
this._view.versionSelector.appendChild(yo`<option value="${customUrl}" selected>custom</option>`)
url = customUrl
} else if (this.data.selectedVersion === 'builtin') {
let location = window.document.location
location = `${location.protocol}//${location.host}/${location.pathname}`
if (location.endsWith('index.html')) location = location.substring(0, location.length - 10)
if (!location.endsWith('/')) location += '/'
url = location + 'soljson.js'
} else if (this._view.versionSelector.value === crossVersions[0]) {
url = `https://simplechain.oss-cn-hangzhou.aliyuncs.com/explorer/cross/${this._view.versionSelector.value}.js`
} else {
if (this.data.selectedVersion.indexOf('soljson') !== 0 || helper.checkSpecialChars(this.data.selectedVersion)) {
return console.log('loading ' + this.data.selectedVersion + ' not allowed')
}
url = `${this.data.baseurl}/${this.data.selectedVersion}`
}
// Workers cannot load js on "file:"-URLs and we get a
// "Uncaught RangeError: Maximum call stack size exceeded" error on Chromium,
// resort to non-worker version in that case.
if (canUseWorker(this.data.selectedVersion)) {
this.compileTabLogic.compiler.loadVersion(true, url)
this.setVersionText('(loading using worker)')
} else {
this.compileTabLogic.compiler.loadVersion(false, url)
this.setVersionText('(loading)')
}
}
_updateLanguageSelector () {
// This is the first version when Yul is available
if (!semver.valid(this._retrieveVersion()) || semver.lt(this._retrieveVersion(), 'v0.5.7+commit.6da8b019.js')) {
this._view.languageSelector.setAttribute('disabled', '')
this._view.languageSelector.value = 'Solidity'
this.compileTabLogic.setLanguage('Solidity')
} else {
this._view.languageSelector.removeAttribute('disabled')
}
}
setVersionText (text) {
if (this._view.version) this._view.version.innerText = text
}
fetchAllVersion (callback) {
minixhr(`${this.data.baseurl}/list.json`, (json, event) => {
// @TODO: optimise and cache results to improve app loading times #2461
var allversions, selectedVersion
if (event.type !== 'error') {
try {
const data = JSON.parse(json)
allversions = data.builds.slice().reverse()
selectedVersion = this.data.defaultVersion
// https://swarm-gateways.net/bzz:/7b0d2dc8dd66a191d1dd86d004ac1d5f6dc24ec955e9116e4cc2fff75063732a/123frnt.js
allversions.unshift({
longVersion: crossVersions[0],
path: crossVersions[0],
urls: ['bzzr://1a8e59736266c51abbfe8aed09573a6360653bd0ec33049be6dd132e91b25fab'],
version: crossVersions[0]
})
if (this.queryParams.get().version) selectedVersion = this.queryParams.get().version
} catch (e) {
addTooltip('Cannot load compiler version list. It might have been blocked by an advertisement blocker. Please try deactivating any of them from this page and reload.')
}
} else {
allversions = [{ path: 'builtin', longVersion: 'latest local version' }]
selectedVersion = 'builtin'
}
callback(allversions, selectedVersion)
})
}
scheduleCompilation () {
if (!this.config.get('autoCompile')) return
if (this.data.compileTimeout) window.clearTimeout(this.data.compileTimeout)
this.data.compileTimeout = window.setTimeout(() => this.compileIfAutoCompileOn(), this.data.timeout)
}
}
module.exports = CompilerContainer
|
/* @preserve
* @esri/arcgis-rest-auth - v2.14.1 - Apache-2.0
* Copyright (c) 2017-2020 Esri, Inc.
* Thu Jul 23 2020 13:27:15 GMT-0600 (Mountain Daylight Time)
*/
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@esri/arcgis-rest-request")):"function"==typeof define&&define.amd?define(["exports","@esri/arcgis-rest-request"],r):r((e=e||self).arcgisRest=e.arcgisRest||{},e.arcgisRest)}(this,function(e,d){"use strict";var k=function(){return(k=Object.assign||function(e){for(var r,t=1,n=arguments.length;t<n;t++)for(var s in r=arguments[t])Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s]);return e}).apply(this,arguments)};function a(e,r){var t=r;return t.rawResponse=!1,d.request(e,t).then(function(e){var r={token:e.access_token,username:e.username,expires:new Date(Date.now()+(1e3*e.expires_in-1e3)),ssl:!0===e.ssl};return e.refresh_token&&(r.refreshToken=e.refresh_token),r})}var r=(t.prototype.getToken=function(e,r){return this.token&&this.expires&&this.expires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequest||(this._pendingTokenRequest=this.refreshToken(r)),this._pendingTokenRequest)},t.prototype.refreshToken=function(e){var r=this,t=k({params:{client_id:this.clientId,client_secret:this.clientSecret,grant_type:"client_credentials",expiration:this.duration}},e);return a(this.portal+"/oauth2/token/",t).then(function(e){return r._pendingTokenRequest=null,r.token=e.token,r.expires=e.expires,e.token})},t.prototype.refreshSession=function(){var e=this;return this.refreshToken().then(function(){return e})},t);function t(e){this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.token=e.token,this.expires=e.expires,this.portal=e.portal||"https://www.arcgis.com/sharing/rest",this.duration=e.duration||7200}function o(e,r){var t=r;return"undefined"!=typeof window&&window.location&&window.location.host?t.params.referer=window.location.host:t.params.referer=d.NODEJS_DEFAULT_REFERER_HEADER,d.request(e,t)}var s=/^https?:\/\/(\S+)\.arcgis\.com.+/;function i(e){return s.test(e)}function h(e){if(!s.test(e))return null;var r=e.match(s)[1].split(".").pop();return r.includes("dev")?"dev":r.includes("qa")?"qa":"production"}function p(e,r){var t=d.cleanUrl(function(e){if(!s.test(e))return e;switch(h(e)){case"dev":return"https://devext.arcgis.com/sharing/rest";case"qa":return"https://qaext.arcgis.com/sharing/rest";default:return"https://www.arcgis.com/sharing/rest"}}(r)).replace(/https?:\/\//,""),n=d.cleanUrl(e).replace(/https?:\/\//,"");return new RegExp(n,"i").test(t)}var n=(T.beginOAuth2=function(e,r){void 0===r&&(r=window);var t,n=k({portal:"https://www.arcgis.com/sharing/rest",provider:"arcgis",duration:20160,popup:!0,state:e.clientId,locale:""},e),s=n.portal,o=n.provider,i=n.clientId,a=n.duration,h=n.redirectUri,p=n.popup,u=n.state,c=n.locale,l=n.params;if(t="arcgis"===o?s+"/oauth2/authorize?client_id="+i+"&response_type=token&expiration="+a+"&redirect_uri="+encodeURIComponent(h)+"&state="+u+"&locale="+c:s+"/oauth2/social/authorize?client_id="+i+"&socialLoginProviderName="+o+"&autoAccountCreateForSocial=true&response_type=token&expiration="+a+"&redirect_uri="+encodeURIComponent(h)+"&state="+u+"&locale="+c,l&&(t=t+"&"+d.encodeQueryString(l)),p){var f=function(){var t={promise:null,resolve:null,reject:null};return t.promise=new Promise(function(e,r){t.resolve=e,t.reject=r}),t}();return r["__ESRI_REST_AUTH_HANDLER_"+i]=function(e,r){if(e){var t=JSON.parse(e);f.reject(new d.ArcGISAuthError(t.errorMessage,t.error))}else if(r){var n=JSON.parse(r);f.resolve(new T({clientId:i,portal:s,ssl:n.ssl,token:n.token,tokenExpires:new Date(n.expires),username:n.username}))}},r.open(t,"oauth-window","height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes"),f.promise}r.location.href=t},T.completeOAuth2=function(e,s){void 0===s&&(s=window);var r=k({portal:"https://www.arcgis.com/sharing/rest",popup:!0},e),o=r.portal,i=r.clientId,a=r.popup;function t(e,r){try{var t=void 0,n="__ESRI_REST_AUTH_HANDLER_"+i;if(a&&(s.opener?s.opener.parent&&s.opener.parent[n]?t=s.opener.parent[n]:s.opener&&s.opener[n]&&(t=s.opener[n]):s!==s.parent&&s.parent&&s.parent[n]&&(t=s.parent[n]),t))return t(e?JSON.stringify(e):void 0,JSON.stringify(r)),void s.close()}catch(e){throw new d.ArcGISAuthError('Unable to complete authentication. It\'s possible you specified popup based oAuth2 but no handler from "beginOAuth2()" present. This generally happens because the "popup" option differs between "beginOAuth2()" and "completeOAuth2()".')}if(e)throw new d.ArcGISAuthError(e.errorMessage,e.error);return new T({clientId:i,portal:o,ssl:r.ssl,token:r.token,tokenExpires:r.expires,username:r.username})}var n=s.location.href.match(/access_token=(.+)&expires_in=(.+)&username=([^&]+)/);if(!n){var h=s.location.href.match(/error=(.+)&error_description=(.+)/);return t({error:h[1],errorMessage:decodeURIComponent(h[2])})}var p=n[1],u=new Date(Date.now()+1e3*parseInt(n[2],10)-6e4),c=decodeURIComponent(n[3]);return t(void 0,{token:p,expires:u,ssl:-1<s.location.href.indexOf("&ssl=true")||-1<s.location.href.indexOf("#ssl=true"),username:c})},T.authorize=function(e,r){var t=k({portal:"https://arcgis.com/sharing/rest",duration:20160},e),n=t.portal,s=t.clientId,o=t.duration,i=t.redirectUri;r.writeHead(301,{Location:n+"/oauth2/authorize?client_id="+s+"&duration="+o+"&response_type=code&redirect_uri="+encodeURIComponent(i)}),r.end()},T.exchangeAuthorizationCode=function(e,r){var t=k({portal:"https://www.arcgis.com/sharing/rest",refreshTokenTTL:1440},e),n=t.portal,s=t.clientId,o=t.redirectUri,i=t.refreshTokenTTL;return a(n+"/oauth2/token",{params:{grant_type:"authorization_code",client_id:s,redirect_uri:o,code:r}}).then(function(e){return new T({clientId:s,portal:n,ssl:e.ssl,redirectUri:o,refreshToken:e.refreshToken,refreshTokenTTL:i,refreshTokenExpires:new Date(Date.now()+1e3*(i-1)),token:e.token,tokenExpires:e.expires,username:e.username})})},T.deserialize=function(e){var r=JSON.parse(e);return new T({clientId:r.clientId,refreshToken:r.refreshToken,refreshTokenExpires:new Date(r.refreshTokenExpires),username:r.username,password:r.password,token:r.token,tokenExpires:new Date(r.tokenExpires),portal:r.portal,ssl:r.ssl,tokenDuration:r.tokenDuration,redirectUri:r.redirectUri,refreshTokenTTL:r.refreshTokenTTL})},T.fromCredential=function(e){return new T({portal:e.server.includes("sharing/rest")?e.server:e.server+"/sharing/rest",ssl:e.ssl,token:e.token,username:e.userId,tokenExpires:new Date(e.expires)})},Object.defineProperty(T.prototype,"token",{get:function(){return this._token},enumerable:!0,configurable:!0}),Object.defineProperty(T.prototype,"tokenExpires",{get:function(){return this._tokenExpires},enumerable:!0,configurable:!0}),Object.defineProperty(T.prototype,"refreshToken",{get:function(){return this._refreshToken},enumerable:!0,configurable:!0}),Object.defineProperty(T.prototype,"refreshTokenExpires",{get:function(){return this._refreshTokenExpires},enumerable:!0,configurable:!0}),T.prototype.toCredential=function(){return{expires:this.tokenExpires.getTime(),server:this.portal,ssl:this.ssl,token:this.token,userId:this.username}},T.prototype.getUser=function(e){var r=this;if(this._pendingUserRequest)return this._pendingUserRequest;if(this._user)return Promise.resolve(this._user);var t=this.portal+"/community/self",n=k({httpMethod:"GET",authentication:this},e,{rawResponse:!1});return this._pendingUserRequest=d.request(t,n).then(function(e){return r._user=e,r._pendingUserRequest=null,e}),this._pendingUserRequest},T.prototype.getUsername=function(){return this.username?Promise.resolve(this.username):this._user?Promise.resolve(this._user.username):this.getUser().then(function(e){return e.username})},T.prototype.getToken=function(e,r){return function(e,r){var t=i(e),n=i(r),s=h(e),o=h(r);return!(!t||!n||s!==o)}(this.portal,e)?this.getFreshToken(r):new RegExp(this.portal,"i").test(e)?this.getFreshToken(r):this.getTokenForServer(e,r)},T.prototype.toJSON=function(){return{clientId:this.clientId,refreshToken:this.refreshToken,refreshTokenExpires:this.refreshTokenExpires,username:this.username,password:this.password,token:this.token,tokenExpires:this.tokenExpires,portal:this.portal,ssl:this.ssl,tokenDuration:this.tokenDuration,redirectUri:this.redirectUri,refreshTokenTTL:this.refreshTokenTTL}},T.prototype.serialize=function(){return JSON.stringify(this)},T.prototype.refreshSession=function(e){return this._user=null,this.username&&this.password?this.refreshWithUsernameAndPassword(e):this.clientId&&this.refreshToken?this.refreshWithRefreshToken():Promise.reject(new d.ArcGISAuthError("Unable to refresh token."))},T.prototype.getServerRootUrl=function(e){var r=d.cleanUrl(e).split(/\/rest(\/admin)?\/services(?:\/|#|\?|$)/)[0].match(/(https?:\/\/)(.+)/),t=(r[0],r[1]),n=r[2].split("/"),s=n[0],o=n.slice(1);return""+t+s.toLowerCase()+"/"+o.join("/")},T.prototype.getTokenForServer=function(r,t){var n=this,s=this.getServerRootUrl(r),e=this.trustedServers[s];return e&&e.expires&&e.expires.getTime()>Date.now()?Promise.resolve(e.token):(this._pendingTokenRequests[s]||(this._pendingTokenRequests[s]=d.request(s+"/rest/info").then(function(e){if(e.owningSystemUrl){if(p(e.owningSystemUrl,n.portal))return d.request(e.owningSystemUrl+"/sharing/rest/info",t);throw new d.ArcGISAuthError(r+" is not federated with "+n.portal+".","NOT_FEDERATED")}if(e.authInfo&&void 0!==n.trustedServers[s])return Promise.resolve({authInfo:e.authInfo});throw new d.ArcGISAuthError(r+" is not federated with any portal and is not explicitly trusted.","NOT_FEDERATED")}).then(function(e){return e.authInfo.tokenServicesUrl}).then(function(e){return n.token&&n.tokenExpires.getTime()>Date.now()?o(e,{params:{token:n.token,serverUrl:r,expiration:n.tokenDuration,client:"referer"}}):o(e,{params:{username:n.username,password:n.password,expiration:n.tokenDuration,client:"referer"}}).then(function(e){return n._token=e.token,n._tokenExpires=new Date(e.expires),e})}).then(function(e){return n.trustedServers[s]={expires:new Date(e.expires),token:e.token},delete n._pendingTokenRequests[s],e.token})),this._pendingTokenRequests[s])},T.prototype.getFreshToken=function(e){var r=this;return this.token&&!this.tokenExpires?Promise.resolve(this.token):this.token&&this.tokenExpires&&this.tokenExpires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequests[this.portal]||(this._pendingTokenRequests[this.portal]=this.refreshSession(e).then(function(e){return r._pendingTokenRequests[r.portal]=null,e.token})),this._pendingTokenRequests[this.portal])},T.prototype.refreshWithUsernameAndPassword=function(e){var r=this,t=k({params:{username:this.username,password:this.password,expiration:this.tokenDuration}},e);return o(this.portal+"/generateToken",t).then(function(e){return r._token=e.token,r._tokenExpires=new Date(e.expires),r})},T.prototype.refreshWithRefreshToken=function(e){var r=this;if(this.refreshToken&&this.refreshTokenExpires&&this.refreshTokenExpires.getTime()<Date.now())return this.refreshRefreshToken(e);var t=k({params:{client_id:this.clientId,refresh_token:this.refreshToken,grant_type:"refresh_token"}},e);return a(this.portal+"/oauth2/token",t).then(function(e){return r._token=e.token,r._tokenExpires=e.expires,r})},T.prototype.refreshRefreshToken=function(e){var r=this,t=k({params:{client_id:this.clientId,refresh_token:this.refreshToken,redirect_uri:this.redirectUri,grant_type:"exchange_refresh_token"}},e);return a(this.portal+"/oauth2/token",t).then(function(e){return r._token=e.token,r._tokenExpires=e.expires,r._refreshToken=e.refreshToken,r._refreshTokenExpires=new Date(Date.now()+60*(r.refreshTokenTTL-1)*1e3),r})},T);function T(e){if(this.clientId=e.clientId,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this.username=e.username,this.password=e.password,this._token=e.token,this._tokenExpires=e.tokenExpires,this.portal=e.portal?d.cleanUrl(e.portal):"https://www.arcgis.com/sharing/rest",this.ssl=e.ssl,this.provider=e.provider||"arcgis",this.tokenDuration=e.tokenDuration||20160,this.redirectUri=e.redirectUri,this.refreshTokenTTL=e.refreshTokenTTL||1440,this.trustedServers={},e.server){var r=this.getServerRootUrl(e.server);this.trustedServers[r]={token:e.token,expires:e.tokenExpires}}this._pendingTokenRequests={}}e.ApplicationSession=r,e.UserSession=n,e.fetchToken=a,e.generateToken=o,Object.defineProperty(e,"__esModule",{value:!0})});
//# sourceMappingURL=auth.umd.min.js.map
|
/**
* Created by lijianxun on 16/9/13.
* @bluebird Promise.props
*/
var Promise = require("bluebird");
function async_fun1() {
return new Promise((resolve, reject)=>{
setTimeout(()=>{
resolve("success-1");
},200);
});
}
function async_fun2(num) {
return new Promise((resolve, reject)=>{
setTimeout(()=>{
if(num === 1){
return resolve("success-2");
}
return reject("fail-2");
},500);
});
}
// .props方法类似.all方法,不同的是.all接收的参数是数组,.props接收的是对象
var props = {
fun1: async_fun1(),
fun2: async_fun2(1)
};
//无异常的情况
Promise
.props(props)
.then((data)=>{
//data也是个对象 { fun1: 'success-1', fun2: 'success-2' }
console.log("data--1 ",data);
}).catch((error)=>{
console.log("error--1 ",error);
});
|
var express = require('express');
var multiparty = require('multiparty');
var fs = require('fs');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.post("/upload", function(req, res) {
var form = new multiparty.Form({
uploadDir: './public/images/'
});
form.parse(req, function(err, fields, files) {
var filesTmp = JSON.stringify(files, null, 2);
if (err) {
console.log('parse error: ' + err);
} else {
var inputFile = files.file[0];
var uploadedPath = inputFile.path;
var dstPath = './public/images/' + inputFile.originalFilename;
//重命名为真实文件名
fs.rename(uploadedPath, dstPath, function(err) {
if (err) {
console.log('rename error: ' + err);
} else {
res.send("ok")
}
});
}
});
});
router.post("/del", function(req, res) {
var filepath = "./public/images/" + req.body.name;
fs.unlink(filepath, function(err) {
if (err) {
throw err;
}
res.send({state: "ok"});
})
});
module.exports = router;
|
import React from 'react'
import { Router } from '@reach/router'
import App from '../App'
import Stake from '../Stake'
import Play from '../Play'
class Routes extends React.Component {
render() {
return (
<Router>
<App path="/" />
<Stake path="/stake" />
<Play path="/play" />
</Router>
)
}
}
export default Routes
|
import test from 'ava';
import AvaRuleTester from 'eslint-ava-rule-tester';
import rule from '../../rules/no-big-array';
import pnoexz from '../_pnoexz';
const ruleTester = new AvaRuleTester(test, {});
ruleTester.run('no-big-array', rule, {
valid: [
'array1[99] = "a";',
'temp = array1[101]',
'array1[99] = array2[101]'
].concat(pnoexz.scripts, pnoexz.functions, pnoexz.bodies),
invalid: [ {
code: 'array1[101] = "a"',
errors: [ {
messageId: "arraySize",
column: 8,
line: 1
} ]
} ]
});
|
/*
* Copyright 2019 is-land
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React, { useState } from 'react';
import { get, reject } from 'lodash';
import Button from '@material-ui/core/Button';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
import IconButton from '@material-ui/core/IconButton';
import AddIcon from '@material-ui/icons/Add';
import ClearIcon from '@material-ui/icons/Clear';
import EditIcon from '@material-ui/icons/Edit';
import FileCopyIcon from '@material-ui/icons/FileCopyOutlined';
import { useWorkspace, useWorkspaceActions } from 'context';
import { DeleteDialog } from 'components/common/Dialog';
import { Tooltip } from 'components/common/Tooltip';
import AutofillEditor, { MODE } from './AutofillEditor';
const AutofillList = () => {
const [editorMode, setEditorMode] = useState(MODE.ADD);
const [selectedData, setSelectedData] = useState(null);
const [isEditorOpen, setIsEditorOpen] = useState(false);
const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = useState(false);
const { updateWorkspace } = useWorkspaceActions();
const { currentWorkspace } = useWorkspace();
const settingFillings = get(currentWorkspace, 'settingFillings', []);
const handleAddButtonClick = () => {
setEditorMode(MODE.ADD);
setSelectedData(null);
setIsEditorOpen(true);
};
const handleEditButtonClick = data => {
setEditorMode(MODE.EDIT);
setSelectedData(data);
setIsEditorOpen(true);
};
const handleCopyButtonClick = data => {
setEditorMode(MODE.COPY);
setSelectedData(data);
setIsEditorOpen(true);
};
const handleDeleteButtonClick = data => {
setSelectedData(data);
setIsDeleteConfirmOpen(true);
};
const handleDelete = async () => {
const name = get(selectedData, 'name');
const workspaceName = get(currentWorkspace, 'name');
await updateWorkspace({
name: workspaceName,
settingFillings: reject(
settingFillings,
settingFilling => settingFilling.name === name,
),
});
setIsDeleteConfirmOpen(false);
};
const handleEditorClose = () => {
setEditorMode(MODE.ADD);
setSelectedData(null);
setIsEditorOpen(false);
};
return (
<>
<List>
{settingFillings.map(settingFilling => {
return (
<ListItem key={settingFilling.name} divider alignItems="flex-start">
<ListItemText primary={settingFilling.displayName} />
<ListItemSecondaryAction>
<Tooltip title="Edit the autofill">
<IconButton
onClick={() => handleEditButtonClick(settingFilling)}
>
<EditIcon />
</IconButton>
</Tooltip>
<Tooltip title="Copy the autofill">
<IconButton
onClick={() => handleCopyButtonClick(settingFilling)}
>
<FileCopyIcon />
</IconButton>
</Tooltip>
<Tooltip title="Delete the autofill">
<IconButton
onClick={() => handleDeleteButtonClick(settingFilling)}
>
<ClearIcon />
</IconButton>
</Tooltip>
</ListItemSecondaryAction>
</ListItem>
);
})}
</List>
<Tooltip title="Add an autofill" placement="right">
<Button
variant="outlined"
color="primary"
startIcon={<AddIcon />}
onClick={handleAddButtonClick}
>
Add Autofill
</Button>
</Tooltip>
<AutofillEditor
isOpen={isEditorOpen}
mode={editorMode}
onClose={handleEditorClose}
data={selectedData}
/>
<DeleteDialog
title="Delete Autofill?"
content={`Are you sure you want to delete the autofill: ${get(
selectedData,
'displayName',
)} ? This action cannot be undone!`}
open={isDeleteConfirmOpen}
handleClose={() => setIsDeleteConfirmOpen(false)}
handleConfirm={handleDelete}
/>
</>
);
};
export default AutofillList;
|
'use strict';
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _enzyme = require('enzyme');
var _sinon = require('sinon');
var _sinon2 = _interopRequireDefault(_sinon);
var _ = require('../');
var _2 = _interopRequireDefault(_);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
describe('Card test', function () {
it('render header', function () {
var w = (0, _enzyme.shallow)(_react2.default.createElement(_2.default, { header: 'HEADER' }));
expect(w.find('.el-card__header').at(0).text()).toBe('HEADER');
});
it('render body', function () {
var w = (0, _enzyme.shallow)(_react2.default.createElement(
_2.default,
null,
'BODY'
));
expect(w.find('.el-card__body').at(0).text()).toBe('BODY');
});
it('use bodyStyle', function () {
var bodyStyle = {
padding: '5px',
border: '1px solid blue'
};
var w = (0, _enzyme.shallow)(_react2.default.createElement(_2.default, { bodyStyle: bodyStyle }));
expect(w.find('.el-card__body').at(0).prop('style')).toEqual(bodyStyle);
});
});
|
'use strict';
var path = require('path');
var fs = require('fs');
var generators = require('yeoman-generator');
var ClassGenerator = generators.Base.extend({
constructor: function () {
generators.Base.apply(this, arguments);
this.option('configfilename',{
type: String
, required: true
});
this.configfilename=this.options.configfilename;
},
scriptbuilding: function () {
var data = path.join(process.cwd(), this.configfilename);
var words = fs.readFileSync(data);
var tst = JSON.parse(words);
var appPackage = tst.appname;
var appTypeName = tst.appname + 'Type';
var appName = tst.appname;
var noofservices = tst.numofservices;
var is_Windows = (process.platform == 'win32');
var is_Linux = (process.platform == 'linux');
var is_mac = (process.platform == 'darwin');
var sdkScriptExtension;
var buildScriptExtension;
var serviceManifestFile;
if (is_Windows) {
sdkScriptExtension = '.ps1';
buildScriptExtension = '.cmd';
serviceManifestFile = 'ServiceManifest.xml';
}
else {
sdkScriptExtension = '.sh';
buildScriptExtension = '.sh';
}
if (is_Linux) serviceManifestFile = 'ServiceManifest_Linux.xml';
if (is_mac) serviceManifestFile = 'ServiceManifest.xml';
fs.writeFile(path.join(process.cwd(), 'build' + buildScriptExtension), '', function () { });
if (noofservices) {
var i;
for (i = 0; i < noofservices; i++) {
var serviceProject = path.join(appPackage, tst.services[i].serviceProjName, tst.services[i].serviceProjName + '.csproj');
var serviceProjName = tst.services[i].serviceProjName;
if (tst.services[i].interfaceprojpath == undefined) {
var servicePackage = tst.services[i].servicePackage;
var nodeFs = require('fs');
var appendToSettings = null;
if (is_Linux || is_mac) {
var appendToSettings = '\n\
\ndotnet restore $DIR/../' + serviceProject + ' -s https://api.nuget.org/v3/index.json \
\ndotnet build $DIR/../'+ serviceProject + ' -v normal\
\ncd ' + '`' + 'dirname $DIR/../' + serviceProject + '`' +
'\ndotnet publish -o ../../../../' + appName + '/' + serviceProjName + '/' + 'PackageRoot' + '/Code\
\ncd -';
}
else if (is_Windows) {
var appendToSettings = '\n\
\ndotnet restore %~dp0\\..\\' + serviceProject + ' -s https://api.nuget.org/v3/index.json \
\ndotnet build %~dp0\\..\\'+ serviceProject + ' -v normal\
\nfor %%F in ("%~dp0\\..\\'+ serviceProject + '") do cd %%~dpF\
\ndotnet publish -o %~dp0\\..\\' + appName + '\\' + serviceProjName + '\\PackageRoot' + '\\Code\
\ncd ..';
}
fs.appendFileSync(path.join(process.cwd(), 'build' + buildScriptExtension), appendToSettings, function (err) {
if (err) {
return console.log(err);
}
});
if (i == 0) {
if (is_Windows) {
var txt4 = '\n' + 'mkdir' + ' ' + path.join(process.cwd(), appName, appName);
fs.appendFileSync(path.join(process.cwd(), 'build' + buildScriptExtension), txt4, function (err) {
if (err) {
return console.log(err);
}
});
}
}
var p1 = path.join(process.cwd(), tst.services[i].serviceProjName, 'PackageRoot', '*');
var p11 = path.join(process.cwd(), appName, appName, tst.services[i].servicePackage);
var txt1 = '\n' + 'xcopy' + ' ' + '/Y' + ' ' + p1 + ' ' + p11 + ' ' + '/s' + ' ' + '/i';
fs.appendFileSync(path.join(process.cwd(), 'build' + buildScriptExtension), txt1, function (err) {
if (err)
return console.log(err);
});
}
else {
var appendToSettings = null;
var interfaceProject = tst.services[i].interfaceprojpath;
var codePath = path.join(appName, serviceProjName, 'PackageRoot', 'Code');
if (is_Windows) {
var appendToSettings = '\ndotnet restore %~dp0\\..\\' + interfaceProject + '-s https://api.nuget.org/v3/index.json\
\ndotnet build %~dp0\\..\\' + interfaceProject + ' -v normal\
\ndotnet restore %~dp0\\..\\'+ serviceProject + ' -s https://api.nuget.org/v3/index.json\
\ndotnet build %~dp0\\..\\'+ serviceProject + ' -v normal\
\nfor %%F in ("%~dp0\\..\\'+ serviceProject + '") do cd %%~dpF\
\ndotnet publish -o %~dp0\\..\\'+ codePath + '\
\ncd %~dp0\..';
}
if (is_Linux || is_mac) {
var appendToSettings = '\n\
\ndotnet restore $DIR/../'+ interfaceProject + ' -s https://api.nuget.org/v3/index.json \
\ndotnet build $DIR/../'+ interfaceProject + ' -v normal\n \n \
\ndotnet restore $DIR/../'+ serviceProject + ' -s https://api.nuget.org/v3/index.json \
\ndotnet build $DIR/../'+ serviceProject + ' -v normal\
\ndotnet publish $DIR/../'+ serviceProject + ' -o ../../../../' + codePath + '\n\n\
\ndotnet restore $DIR/../'+ testProject + ' -s https://api.nuget.org/v3/index.json \
\ndotnet publish -o %~dp0\\..\\'+ codePath + '\
\ncd -';
}
fs.appendFileSync(path.join(process.cwd(), 'build' + buildScriptExtension), appendToSettings, function (err) {
if (err) {
return console.log(err);
}
});
if (is_Windows) {
if (i == 0) {
var txt4 = '\n' + 'mkdir' + ' ' + path.join(process.cwd(), appName, appName);
fs.appendFileSync(path.join(process.cwd(), 'build' + buildScriptExtension), txt4, function (err) {
if (err) {
return console.log(err);
}
});
}
var p1 = path.join(process.cwd(), tst.services[i].serviceProjName, 'PackageRoot', '*');
var p11 = path.join(process.cwd(), appName, appName, tst.services[i].servicePackage);
var txt1 = '\n' + 'xcopy' + ' ' + '/Y' + ' ' + p1 + ' ' + p11 + ' ' + '/s' + ' ' + '/i';
fs.appendFileSync(path.join(process.cwd(), 'build' + buildScriptExtension), txt1, function (err) {
if (err)
return console.log(err);
})
}
}
}
this.fs.copyTpl(
this.templatePath('../../utilityscripts/main/deploy/deploy' + sdkScriptExtension),
this.destinationPath(path.join(process.cwd(), 'install' + sdkScriptExtension)),
{
appPackage: appPackage,
appName: appName,
appTypeName: appTypeName,
VScodeConfig:"./"+this.configfilename
}
);
this.fs.copyTpl(
this.templatePath('../../utilityscripts/main/deploy/upgrade' + sdkScriptExtension),
this.destinationPath(path.join(process.cwd(), 'upgrade' + sdkScriptExtension)),
{
appPackage: appPackage,
appName: appName,
appTypeName: appTypeName
}
);
this.fs.copyTpl(
this.templatePath('../../utilityscripts/main/deploy/un-deploy' + sdkScriptExtension),
this.destinationPath(path.join(process.cwd(), 'uninstall' + sdkScriptExtension)),
{
appPackage: appPackage,
appName: appName,
appTypeName: appTypeName
}
);
}
}
});
module.exports = ClassGenerator;
|
(function(GoNorth) {
"use strict";
(function(Tale) {
(function(Actions) {
/// Action Type for transfering an item from the npc inventory to the player inventory
var actionTypeTransferItemToPlayerInventory = 5;
/**
* Transfer item from the npc inventory to the player inventory Action
* @class
*/
Actions.TransferItemToPlayerInventoryAction = function()
{
Actions.ChangeInventoryAction.apply(this);
};
Actions.TransferItemToPlayerInventoryAction.prototype = jQuery.extend({ }, Actions.ChangeInventoryAction.prototype);
/**
* Builds the action
*
* @returns {object} Action
*/
Actions.TransferItemToPlayerInventoryAction.prototype.buildAction = function() {
return new Actions.TransferItemToPlayerInventoryAction();
};
/**
* Returns the type of the action
*
* @returns {number} Type of the action
*/
Actions.TransferItemToPlayerInventoryAction.prototype.getType = function() {
return actionTypeTransferItemToPlayerInventory;
};
/**
* Returns the label of the action
*
* @returns {string} Label of the action
*/
Actions.TransferItemToPlayerInventoryAction.prototype.getLabel = function() {
return Tale.Localization.Actions.TransferItemToPlayerInventoryLabel;
};
GoNorth.DefaultNodeShapes.Shapes.addAvailableAction(new Actions.TransferItemToPlayerInventoryAction());
}(Tale.Actions = Tale.Actions || {}));
}(GoNorth.Tale = GoNorth.Tale || {}));
}(window.GoNorth = window.GoNorth || {}));
|
/* eslint-disable no-new */
import Vue from 'vue'
import VueRouter from 'vue-router'
import '@/main.css'
import Homepage from '@/pages/Homepage'
import Login from '@/pages/Login'
import Loader from '@/components/Loader'
import EventsStore from '@libs/vue-events-store'
if (process.env.DEBUG === true) window.localStorage.debug = 'nova:*'
Vue.use(EventsStore)
Vue.use(VueRouter)
Vue.config.productionTip = false
Vue.component('ui-loader', Loader)
const routes = [
{ path: '/admin', component: Homepage },
{ path: '/admin/login', component: Login }
]
const router = new VueRouter({
routes,
mode: 'history'
})
new Vue({
router,
components: {
Loader
}
}).$mount('#root')
|
module.exports = installSelenium
const merge = require('lodash').merge
const selenium = require('selenium-standalone')
function installSelenium (state, callback) {
if (state.seleniumAlreadyRunning) {
return callback()
}
state.debugSelenium('Installing selenium')
const options = merge(state.config.selenium.standalone, {
// https://github.com/vvo/selenium-standalone#seleniuminstallopts-cb
// progressCb: (totalLength, progressLength) => {
// console.log(progressLength, '/', totalLength)
// }
logger: (message) => {
// ignore empty messages or messages containing - only
if (/^[-]+$/.test(message.trim())) {
return
}
state.debugSelenium(message)
}
})
selenium.install(options, (error) => {
if (error) {
if (error.message.indexOf('getaddrinfo')) {
// most likely there is no internet connectivity, so we try to just run
// tests as it might have been installed before
state.debugSelenium('CONNECTION ERROR: could not install/update selenium. Will try to run tests either way')
return callback()
}
state.debugSelenium('Could not install selenium: ' + error.message)
return callback(error)
}
state.debugSelenium('Selenium installed')
callback()
})
}
|
module.exports={A:{A:{"1":"E A B","8":"O lB","129":"D","257":"G"},B:{"1":"C I F P J K L M KB N R YB T PB"},C:{"1":"0 1 2 3 4 5 6 7 8 9 vB OB H Y O D G E A B C I F P J K L Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB NB GB HB IB JB Q LB FB W V U QB RB SB TB UB VB WB M KB N sB R kB jB"},D:{"1":"0 1 2 3 4 5 6 7 8 9 H Y O D G E A B C I F P J K L Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB NB GB HB IB JB Q LB FB W V U QB RB SB TB UB VB WB M KB N R YB T PB eB cB 2B"},E:{"1":"H Y O D G E A B C I F dB aB fB gB hB iB ZB S X mB nB"},F:{"1":"0 1 2 3 4 5 6 7 8 9 E B C P J K L Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB EB GB HB IB JB Q LB FB W V U oB pB qB rB S XB tB X"},G:{"1":"G F aB uB MB wB xB yB zB 0B 1B bB 3B 4B 5B 6B 7B 8B 9B AC BC"},H:{"1":"CC"},I:{"1":"OB H N DC EC FC GC MB HC IC"},J:{"1":"D A"},K:{"1":"A B C DB S XB X"},L:{"1":"T"},M:{"1":"M"},N:{"1":"A B"},O:{"1":"JC"},P:{"1":"H KC LC MC NC OC ZB PC QC"},Q:{"1":"RC"},R:{"1":"SC"},S:{"1":"TC"}},B:2,C:"CSS min/max-width/height"};
|
/**
* SocketCluster JavaScript client v16.0.2
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.socketClusterClient = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
(function (global){
function AuthEngine() {
this._internalStorage = {};
this.isLocalStorageEnabled = this._checkLocalStorageEnabled();
}
AuthEngine.prototype._checkLocalStorageEnabled = function () {
let err;
try {
// Some browsers will throw an error here if localStorage is disabled.
global.localStorage;
// Safari, in Private Browsing Mode, looks like it supports localStorage but all calls to setItem
// throw QuotaExceededError. We're going to detect this and avoid hard to debug edge cases.
global.localStorage.setItem('__scLocalStorageTest', 1);
global.localStorage.removeItem('__scLocalStorageTest');
} catch (e) {
err = e;
}
return !err;
};
AuthEngine.prototype.saveToken = function (name, token, options) {
if (this.isLocalStorageEnabled && global.localStorage) {
global.localStorage.setItem(name, token);
} else {
this._internalStorage[name] = token;
}
return Promise.resolve(token);
};
AuthEngine.prototype.removeToken = function (name) {
let loadPromise = this.loadToken(name);
if (this.isLocalStorageEnabled && global.localStorage) {
global.localStorage.removeItem(name);
} else {
delete this._internalStorage[name];
}
return loadPromise;
};
AuthEngine.prototype.loadToken = function (name) {
let token;
if (this.isLocalStorageEnabled && global.localStorage) {
token = global.localStorage.getItem(name);
} else {
token = this._internalStorage[name] || null;
}
return Promise.resolve(token);
};
module.exports = AuthEngine;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],2:[function(require,module,exports){
(function (global){
const StreamDemux = require('stream-demux');
const AsyncStreamEmitter = require('async-stream-emitter');
const AGChannel = require('ag-channel');
const AuthEngine = require('./auth');
const formatter = require('sc-formatter');
const AGTransport = require('./transport');
const querystring = require('querystring');
const LinkedList = require('linked-list');
const cloneDeep = require('clone-deep');
const Buffer = require('buffer/').Buffer;
const wait = require('./wait');
const scErrors = require('sc-errors');
const InvalidArgumentsError = scErrors.InvalidArgumentsError;
const InvalidMessageError = scErrors.InvalidMessageError;
const InvalidActionError = scErrors.InvalidActionError;
const SocketProtocolError = scErrors.SocketProtocolError;
const TimeoutError = scErrors.TimeoutError;
const BadConnectionError = scErrors.BadConnectionError;
const isBrowser = typeof window !== 'undefined';
function AGClientSocket(socketOptions) {
AsyncStreamEmitter.call(this);
let defaultOptions = {
path: '/socketcluster/',
secure: false,
protocolScheme: null,
socketPath: null,
autoConnect: true,
autoReconnect: true,
autoSubscribeOnConnect: true,
connectTimeout: 20000,
ackTimeout: 10000,
timestampRequests: false,
timestampParam: 't',
authTokenName: 'socketcluster.authToken',
binaryType: 'arraybuffer',
batchOnHandshake: false,
batchOnHandshakeDuration: 100,
batchInterval: 50,
protocolVersion: 2,
wsOptions: {},
cloneData: false
};
let opts = Object.assign(defaultOptions, socketOptions);
this.id = null;
this.version = opts.version || null;
this.protocolVersion = opts.protocolVersion;
this.state = this.CLOSED;
this.authState = this.UNAUTHENTICATED;
this.signedAuthToken = null;
this.authToken = null;
this.pendingReconnect = false;
this.pendingReconnectTimeout = null;
this.preparingPendingSubscriptions = false;
this.clientId = opts.clientId;
this.wsOptions = opts.wsOptions;
this.connectTimeout = opts.connectTimeout;
this.ackTimeout = opts.ackTimeout;
this.channelPrefix = opts.channelPrefix || null;
this.disconnectOnUnload = opts.disconnectOnUnload == null ? true : opts.disconnectOnUnload;
this.authTokenName = opts.authTokenName;
// pingTimeout will be connectTimeout at the start, but it will
// be updated with values provided by the 'connect' event
opts.pingTimeout = opts.connectTimeout;
this.pingTimeout = opts.pingTimeout;
this.pingTimeoutDisabled = !!opts.pingTimeoutDisabled;
let maxTimeout = Math.pow(2, 31) - 1;
let verifyDuration = (propertyName) => {
if (this[propertyName] > maxTimeout) {
throw new InvalidArgumentsError(
`The ${propertyName} value provided exceeded the maximum amount allowed`
);
}
};
verifyDuration('connectTimeout');
verifyDuration('ackTimeout');
verifyDuration('pingTimeout');
this.connectAttempts = 0;
this.isBatching = false;
this.batchOnHandshake = opts.batchOnHandshake;
this.batchOnHandshakeDuration = opts.batchOnHandshakeDuration;
this._batchingIntervalId = null;
this._outboundBuffer = new LinkedList();
this._channelMap = {};
this._channelEventDemux = new StreamDemux();
this._channelDataDemux = new StreamDemux();
this._receiverDemux = new StreamDemux();
this._procedureDemux = new StreamDemux();
this.options = opts;
this._cid = 1;
this.options.callIdGenerator = () => {
return this._cid++;
};
if (this.options.autoReconnect) {
if (this.options.autoReconnectOptions == null) {
this.options.autoReconnectOptions = {};
}
// Add properties to the this.options.autoReconnectOptions object.
// We assign the reference to a reconnectOptions variable to avoid repetition.
let reconnectOptions = this.options.autoReconnectOptions;
if (reconnectOptions.initialDelay == null) {
reconnectOptions.initialDelay = 10000;
}
if (reconnectOptions.randomness == null) {
reconnectOptions.randomness = 10000;
}
if (reconnectOptions.multiplier == null) {
reconnectOptions.multiplier = 1.5;
}
if (reconnectOptions.maxDelay == null) {
reconnectOptions.maxDelay = 60000;
}
}
if (this.options.subscriptionRetryOptions == null) {
this.options.subscriptionRetryOptions = {};
}
if (this.options.authEngine) {
this.auth = this.options.authEngine;
} else {
this.auth = new AuthEngine();
}
if (this.options.codecEngine) {
this.codec = this.options.codecEngine;
} else {
// Default codec engine
this.codec = formatter;
}
if (this.options.protocol) {
let protocolOptionError = new InvalidArgumentsError(
'The "protocol" option does not affect socketcluster-client - ' +
'If you want to utilize SSL/TLS, use "secure" option instead'
);
this._onError(protocolOptionError);
}
this.options.query = opts.query || {};
if (typeof this.options.query === 'string') {
this.options.query = querystring.parse(this.options.query);
}
if (isBrowser && this.disconnectOnUnload && global.addEventListener && global.removeEventListener) {
this._handleBrowserUnload();
}
if (this.options.autoConnect) {
this.connect();
}
}
AGClientSocket.prototype = Object.create(AsyncStreamEmitter.prototype);
AGClientSocket.CONNECTING = AGClientSocket.prototype.CONNECTING = AGTransport.prototype.CONNECTING;
AGClientSocket.OPEN = AGClientSocket.prototype.OPEN = AGTransport.prototype.OPEN;
AGClientSocket.CLOSED = AGClientSocket.prototype.CLOSED = AGTransport.prototype.CLOSED;
AGClientSocket.AUTHENTICATED = AGClientSocket.prototype.AUTHENTICATED = 'authenticated';
AGClientSocket.UNAUTHENTICATED = AGClientSocket.prototype.UNAUTHENTICATED = 'unauthenticated';
AGClientSocket.SUBSCRIBED = AGClientSocket.prototype.SUBSCRIBED = AGChannel.SUBSCRIBED;
AGClientSocket.PENDING = AGClientSocket.prototype.PENDING = AGChannel.PENDING;
AGClientSocket.UNSUBSCRIBED = AGClientSocket.prototype.UNSUBSCRIBED = AGChannel.UNSUBSCRIBED;
AGClientSocket.ignoreStatuses = scErrors.socketProtocolIgnoreStatuses;
AGClientSocket.errorStatuses = scErrors.socketProtocolErrorStatuses;
Object.defineProperty(AGClientSocket.prototype, 'isBufferingBatch', {
get: function () {
return this.transport.isBufferingBatch;
}
});
AGClientSocket.prototype.getBackpressure = function () {
return Math.max(
this.getAllListenersBackpressure(),
this.getAllReceiversBackpressure(),
this.getAllProceduresBackpressure(),
this.getAllChannelsBackpressure()
);
};
AGClientSocket.prototype._handleBrowserUnload = async function () {
let unloadHandler = () => {
this.disconnect();
};
let isUnloadHandlerAttached = false;
let attachUnloadHandler = () => {
if (!isUnloadHandlerAttached) {
isUnloadHandlerAttached = true;
global.addEventListener('beforeunload', unloadHandler, false);
}
};
let detachUnloadHandler = () => {
if (isUnloadHandlerAttached) {
isUnloadHandlerAttached = false;
global.removeEventListener('beforeunload', unloadHandler, false);
}
};
(async () => {
let consumer = this.listener('connecting').createConsumer();
while (true) {
let packet = await consumer.next();
if (packet.done) break;
attachUnloadHandler();
}
})();
(async () => {
let consumer = this.listener('close').createConsumer();
while (true) {
let packet = await consumer.next();
if (packet.done) break;
detachUnloadHandler();
}
})();
};
AGClientSocket.prototype._setAuthToken = function (data) {
this._changeToAuthenticatedState(data.token);
(async () => {
try {
await this.auth.saveToken(this.authTokenName, data.token, {});
} catch (err) {
this._onError(err);
}
})();
};
AGClientSocket.prototype._removeAuthToken = function (data) {
(async () => {
let oldAuthToken;
try {
oldAuthToken = await this.auth.removeToken(this.authTokenName);
} catch (err) {
// Non-fatal error - Do not close the connection
this._onError(err);
return;
}
this.emit('removeAuthToken', {oldAuthToken});
})();
this._changeToUnauthenticatedStateAndClearTokens();
};
AGClientSocket.prototype._privateDataHandlerMap = {
'#publish': function (data) {
let undecoratedChannelName = this._undecorateChannelName(data.channel);
let isSubscribed = this.isSubscribed(undecoratedChannelName, true);
if (isSubscribed) {
this._channelDataDemux.write(undecoratedChannelName, data.data);
}
},
'#kickOut': function (data) {
let undecoratedChannelName = this._undecorateChannelName(data.channel);
let channel = this._channelMap[undecoratedChannelName];
if (channel) {
this.emit('kickOut', {
channel: undecoratedChannelName,
message: data.message
});
this._channelEventDemux.write(`${undecoratedChannelName}/kickOut`, {message: data.message});
this._triggerChannelUnsubscribe(channel);
}
},
'#setAuthToken': function (data) {
if (data) {
this._setAuthToken(data);
}
},
'#removeAuthToken': function (data) {
this._removeAuthToken(data);
}
};
AGClientSocket.prototype._privateRPCHandlerMap = {
'#setAuthToken': function (data, request) {
if (data) {
this._setAuthToken(data);
request.end();
} else {
request.error(new InvalidMessageError('No token data provided by #setAuthToken event'));
}
},
'#removeAuthToken': function (data, request) {
this._removeAuthToken(data);
request.end();
}
};
AGClientSocket.prototype.getState = function () {
return this.state;
};
AGClientSocket.prototype.getBytesReceived = function () {
return this.transport.getBytesReceived();
};
AGClientSocket.prototype.deauthenticate = async function () {
(async () => {
let oldAuthToken;
try {
oldAuthToken = await this.auth.removeToken(this.authTokenName);
} catch (err) {
this._onError(err);
return;
}
this.emit('removeAuthToken', {oldAuthToken});
})();
if (this.state !== this.CLOSED) {
this.transmit('#removeAuthToken');
}
this._changeToUnauthenticatedStateAndClearTokens();
await wait(0);
};
AGClientSocket.prototype.connect = function () {
if (this.state === this.CLOSED) {
this.pendingReconnect = false;
this.pendingReconnectTimeout = null;
clearTimeout(this._reconnectTimeoutRef);
this.state = this.CONNECTING;
this.emit('connecting', {});
if (this.transport) {
this.transport.clearAllListeners();
}
let transportHandlers = {
onOpen: (value) => {
this.state = this.OPEN;
this._onOpen(value);
},
onOpenAbort: (value) => {
if (this.state !== this.CLOSED) {
this.state = this.CLOSED;
this._destroy(value.code, value.reason, true);
}
},
onClose: (value) => {
if (this.state !== this.CLOSED) {
this.state = this.CLOSED;
this._destroy(value.code, value.reason);
}
},
onEvent: (value) => {
this.emit(value.event, value.data);
},
onError: (value) => {
this._onError(value.error);
},
onInboundInvoke: (value) => {
this._onInboundInvoke(value);
},
onInboundTransmit: (value) => {
this._onInboundTransmit(value.event, value.data);
}
};
this.transport = new AGTransport(this.auth, this.codec, this.options, this.wsOptions, transportHandlers);
}
};
AGClientSocket.prototype.reconnect = function (code, reason) {
this.disconnect(code, reason);
this.connect();
};
AGClientSocket.prototype.disconnect = function (code, reason) {
code = code || 1000;
if (typeof code !== 'number') {
throw new InvalidArgumentsError('If specified, the code argument must be a number');
}
let isConnecting = this.state === this.CONNECTING;
if (isConnecting || this.state === this.OPEN) {
this.state = this.CLOSED;
this._destroy(code, reason, isConnecting);
this.transport.close(code, reason);
} else {
this.pendingReconnect = false;
this.pendingReconnectTimeout = null;
clearTimeout(this._reconnectTimeoutRef);
}
};
AGClientSocket.prototype._changeToUnauthenticatedStateAndClearTokens = function () {
if (this.authState !== this.UNAUTHENTICATED) {
let oldAuthState = this.authState;
let oldAuthToken = this.authToken;
let oldSignedAuthToken = this.signedAuthToken;
this.authState = this.UNAUTHENTICATED;
this.signedAuthToken = null;
this.authToken = null;
let stateChangeData = {
oldAuthState,
newAuthState: this.authState
};
this.emit('authStateChange', stateChangeData);
this.emit('deauthenticate', {oldSignedAuthToken, oldAuthToken});
}
};
AGClientSocket.prototype._changeToAuthenticatedState = function (signedAuthToken) {
this.signedAuthToken = signedAuthToken;
this.authToken = this._extractAuthTokenData(signedAuthToken);
if (this.authState !== this.AUTHENTICATED) {
let oldAuthState = this.authState;
this.authState = this.AUTHENTICATED;
let stateChangeData = {
oldAuthState,
newAuthState: this.authState,
signedAuthToken: signedAuthToken,
authToken: this.authToken
};
if (!this.preparingPendingSubscriptions) {
this.processPendingSubscriptions();
}
this.emit('authStateChange', stateChangeData);
}
this.emit('authenticate', {signedAuthToken, authToken: this.authToken});
};
AGClientSocket.prototype.decodeBase64 = function (encodedString) {
return Buffer.from(encodedString, 'base64').toString('utf8');
};
AGClientSocket.prototype.encodeBase64 = function (decodedString) {
return Buffer.from(decodedString, 'utf8').toString('base64');
};
AGClientSocket.prototype._extractAuthTokenData = function (signedAuthToken) {
let tokenParts = (signedAuthToken || '').split('.');
let encodedTokenData = tokenParts[1];
if (encodedTokenData != null) {
let tokenData = encodedTokenData;
try {
tokenData = this.decodeBase64(tokenData);
return JSON.parse(tokenData);
} catch (e) {
return tokenData;
}
}
return null;
};
AGClientSocket.prototype.getAuthToken = function () {
return this.authToken;
};
AGClientSocket.prototype.getSignedAuthToken = function () {
return this.signedAuthToken;
};
// Perform client-initiated authentication by providing an encrypted token string.
AGClientSocket.prototype.authenticate = async function (signedAuthToken) {
let authStatus;
try {
authStatus = await this.invoke('#authenticate', signedAuthToken);
} catch (err) {
if (err.name !== 'BadConnectionError' && err.name !== 'TimeoutError') {
// In case of a bad/closed connection or a timeout, we maintain the last
// known auth state since those errors don't mean that the token is invalid.
this._changeToUnauthenticatedStateAndClearTokens();
}
await wait(0);
throw err;
}
if (authStatus && authStatus.isAuthenticated != null) {
// If authStatus is correctly formatted (has an isAuthenticated property),
// then we will rehydrate the authError.
if (authStatus.authError) {
authStatus.authError = scErrors.hydrateError(authStatus.authError);
}
} else {
// Some errors like BadConnectionError and TimeoutError will not pass a valid
// authStatus object to the current function, so we need to create it ourselves.
authStatus = {
isAuthenticated: this.authState,
authError: null
};
}
if (authStatus.isAuthenticated) {
this._changeToAuthenticatedState(signedAuthToken);
} else {
this._changeToUnauthenticatedStateAndClearTokens();
}
(async () => {
try {
await this.auth.saveToken(this.authTokenName, signedAuthToken, {});
} catch (err) {
this._onError(err);
}
})();
await wait(0);
return authStatus;
};
AGClientSocket.prototype._tryReconnect = function (initialDelay) {
let exponent = this.connectAttempts++;
let reconnectOptions = this.options.autoReconnectOptions;
let timeout;
if (initialDelay == null || exponent > 0) {
let initialTimeout = Math.round(reconnectOptions.initialDelay + (reconnectOptions.randomness || 0) * Math.random());
timeout = Math.round(initialTimeout * Math.pow(reconnectOptions.multiplier, exponent));
} else {
timeout = initialDelay;
}
if (timeout > reconnectOptions.maxDelay) {
timeout = reconnectOptions.maxDelay;
}
clearTimeout(this._reconnectTimeoutRef);
this.pendingReconnect = true;
this.pendingReconnectTimeout = timeout;
this._reconnectTimeoutRef = setTimeout(() => {
this.connect();
}, timeout);
};
AGClientSocket.prototype._onOpen = function (status) {
if (this.isBatching) {
this._startBatching();
} else if (this.batchOnHandshake) {
this._startBatching();
setTimeout(() => {
if (!this.isBatching) {
this._stopBatching();
}
}, this.batchOnHandshakeDuration);
}
this.preparingPendingSubscriptions = true;
if (status) {
this.id = status.id;
this.pingTimeout = status.pingTimeout;
if (status.isAuthenticated) {
this._changeToAuthenticatedState(status.authToken);
} else {
this._changeToUnauthenticatedStateAndClearTokens();
}
} else {
// This can happen if auth.loadToken (in transport.js) fails with
// an error - This means that the signedAuthToken cannot be loaded by
// the auth engine and therefore, we need to unauthenticate the client.
this._changeToUnauthenticatedStateAndClearTokens();
}
this.connectAttempts = 0;
if (this.options.autoSubscribeOnConnect) {
this.processPendingSubscriptions();
}
// If the user invokes the callback while in autoSubscribeOnConnect mode, it
// won't break anything.
this.emit('connect', {
...status,
processPendingSubscriptions: () => {
this.processPendingSubscriptions();
}
});
if (this.state === this.OPEN) {
this._flushOutboundBuffer();
}
};
AGClientSocket.prototype._onError = function (error) {
this.emit('error', {error});
};
AGClientSocket.prototype._suspendSubscriptions = function () {
Object.keys(this._channelMap).forEach((channelName) => {
let channel = this._channelMap[channelName];
this._triggerChannelUnsubscribe(channel, true);
});
};
AGClientSocket.prototype._abortAllPendingEventsDueToBadConnection = function (failureType) {
let currentNode = this._outboundBuffer.head;
let nextNode;
while (currentNode) {
nextNode = currentNode.next;
let eventObject = currentNode.data;
clearTimeout(eventObject.timeout);
delete eventObject.timeout;
currentNode.detach();
currentNode = nextNode;
let callback = eventObject.callback;
if (callback) {
delete eventObject.callback;
let errorMessage = `Event "${eventObject.event}" was aborted due to a bad connection`;
let error = new BadConnectionError(errorMessage, failureType);
callback.call(eventObject, error, eventObject);
}
// Cleanup any pending response callback in the transport layer too.
if (eventObject.cid) {
this.transport.cancelPendingResponse(eventObject.cid);
}
}
};
AGClientSocket.prototype._destroy = function (code, reason, openAbort) {
this.id = null;
this._cancelBatching();
if (this.transport) {
this.transport.clearAllListeners();
}
this.pendingReconnect = false;
this.pendingReconnectTimeout = null;
clearTimeout(this._reconnectTimeoutRef);
this._suspendSubscriptions();
if (openAbort) {
this.emit('connectAbort', {code, reason});
} else {
this.emit('disconnect', {code, reason});
}
this.emit('close', {code, reason});
if (!AGClientSocket.ignoreStatuses[code]) {
let closeMessage;
if (reason) {
closeMessage = 'Socket connection closed with status code ' + code + ' and reason: ' + reason;
} else {
closeMessage = 'Socket connection closed with status code ' + code;
}
let err = new SocketProtocolError(AGClientSocket.errorStatuses[code] || closeMessage, code);
this._onError(err);
}
this._abortAllPendingEventsDueToBadConnection(openAbort ? 'connectAbort' : 'disconnect');
// Try to reconnect
// on server ping timeout (4000)
// or on client pong timeout (4001)
// or on close without status (1005)
// or on handshake failure (4003)
// or on handshake rejection (4008)
// or on socket hung up (1006)
if (this.options.autoReconnect) {
if (code === 4000 || code === 4001 || code === 1005) {
// If there is a ping or pong timeout or socket closes without
// status, don't wait before trying to reconnect - These could happen
// if the client wakes up after a period of inactivity and in this case we
// want to re-establish the connection as soon as possible.
this._tryReconnect(0);
// Codes 4500 and above will be treated as permanent disconnects.
// Socket will not try to auto-reconnect.
} else if (code !== 1000 && code < 4500) {
this._tryReconnect();
}
}
};
AGClientSocket.prototype._onInboundTransmit = function (event, data) {
let handler = this._privateDataHandlerMap[event];
if (handler) {
handler.call(this, data);
} else {
this._receiverDemux.write(event, data);
}
};
AGClientSocket.prototype._onInboundInvoke = function (request) {
let {procedure, data} = request;
let handler = this._privateRPCHandlerMap[procedure];
if (handler) {
handler.call(this, data, request);
} else {
this._procedureDemux.write(procedure, request);
}
};
AGClientSocket.prototype.decode = function (message) {
return this.transport.decode(message);
};
AGClientSocket.prototype.encode = function (object) {
return this.transport.encode(object);
};
AGClientSocket.prototype._flushOutboundBuffer = function () {
let currentNode = this._outboundBuffer.head;
let nextNode;
while (currentNode) {
nextNode = currentNode.next;
let eventObject = currentNode.data;
currentNode.detach();
this.transport.transmitObject(eventObject);
currentNode = nextNode;
}
};
AGClientSocket.prototype._handleEventAckTimeout = function (eventObject, eventNode) {
if (eventNode) {
eventNode.detach();
}
delete eventObject.timeout;
let callback = eventObject.callback;
if (callback) {
delete eventObject.callback;
let error = new TimeoutError(`Event response for "${eventObject.event}" timed out`);
callback.call(eventObject, error, eventObject);
}
// Cleanup any pending response callback in the transport layer too.
if (eventObject.cid) {
this.transport.cancelPendingResponse(eventObject.cid);
}
};
AGClientSocket.prototype._processOutboundEvent = function (event, data, options, expectResponse) {
options = options || {};
if (this.state === this.CLOSED) {
this.connect();
}
let eventObject = {
event
};
let promise;
if (expectResponse) {
promise = new Promise((resolve, reject) => {
eventObject.callback = (err, data) => {
if (err) {
reject(err);
return;
}
resolve(data);
};
});
} else {
promise = Promise.resolve();
}
let eventNode = new LinkedList.Item();
if (this.options.cloneData) {
eventObject.data = cloneDeep(data);
} else {
eventObject.data = data;
}
eventNode.data = eventObject;
let ackTimeout = options.ackTimeout == null ? this.ackTimeout : options.ackTimeout;
eventObject.timeout = setTimeout(() => {
this._handleEventAckTimeout(eventObject, eventNode);
}, ackTimeout);
this._outboundBuffer.append(eventNode);
if (this.state === this.OPEN) {
this._flushOutboundBuffer();
}
return promise;
};
AGClientSocket.prototype.send = function (data) {
this.transport.send(data);
};
AGClientSocket.prototype.transmit = function (event, data, options) {
return this._processOutboundEvent(event, data, options);
};
AGClientSocket.prototype.invoke = function (event, data, options) {
return this._processOutboundEvent(event, data, options, true);
};
AGClientSocket.prototype.transmitPublish = function (channelName, data) {
let pubData = {
channel: this._decorateChannelName(channelName),
data
};
return this.transmit('#publish', pubData);
};
AGClientSocket.prototype.invokePublish = function (channelName, data) {
let pubData = {
channel: this._decorateChannelName(channelName),
data
};
return this.invoke('#publish', pubData);
};
AGClientSocket.prototype._triggerChannelSubscribe = function (channel, subscriptionOptions) {
let channelName = channel.name;
if (channel.state !== AGChannel.SUBSCRIBED) {
let oldChannelState = channel.state;
channel.state = AGChannel.SUBSCRIBED;
let stateChangeData = {
oldChannelState,
newChannelState: channel.state,
subscriptionOptions
};
this._channelEventDemux.write(`${channelName}/subscribeStateChange`, stateChangeData);
this._channelEventDemux.write(`${channelName}/subscribe`, {
subscriptionOptions
});
this.emit('subscribeStateChange', {
channel: channelName,
...stateChangeData
});
this.emit('subscribe', {
channel: channelName,
subscriptionOptions
});
}
};
AGClientSocket.prototype._triggerChannelSubscribeFail = function (err, channel, subscriptionOptions) {
let channelName = channel.name;
let meetsAuthRequirements = !channel.options.waitForAuth || this.authState === this.AUTHENTICATED;
let hasChannel = !!this._channelMap[channelName];
if (hasChannel && meetsAuthRequirements) {
delete this._channelMap[channelName];
this._channelEventDemux.write(`${channelName}/subscribeFail`, {
error: err,
subscriptionOptions
});
this.emit('subscribeFail', {
error: err,
channel: channelName,
subscriptionOptions: subscriptionOptions
});
}
};
// Cancel any pending subscribe callback
AGClientSocket.prototype._cancelPendingSubscribeCallback = function (channel) {
if (channel._pendingSubscriptionCid != null) {
this.transport.cancelPendingResponse(channel._pendingSubscriptionCid);
delete channel._pendingSubscriptionCid;
}
};
AGClientSocket.prototype._decorateChannelName = function (channelName) {
if (this.channelPrefix) {
channelName = this.channelPrefix + channelName;
}
return channelName;
};
AGClientSocket.prototype._undecorateChannelName = function (decoratedChannelName) {
if (this.channelPrefix && decoratedChannelName.indexOf(this.channelPrefix) === 0) {
return decoratedChannelName.replace(this.channelPrefix, '');
}
return decoratedChannelName;
};
AGClientSocket.prototype.startBatch = function () {
this.transport.startBatch();
};
AGClientSocket.prototype.flushBatch = function () {
this.transport.flushBatch();
};
AGClientSocket.prototype.cancelBatch = function () {
this.transport.cancelBatch();
};
AGClientSocket.prototype._startBatching = function () {
if (this._batchingIntervalId != null) {
return;
}
this.startBatch();
this._batchingIntervalId = setInterval(() => {
this.flushBatch();
this.startBatch();
}, this.options.batchInterval);
};
AGClientSocket.prototype.startBatching = function () {
this.isBatching = true;
this._startBatching();
};
AGClientSocket.prototype._stopBatching = function () {
if (this._batchingIntervalId != null) {
clearInterval(this._batchingIntervalId);
}
this._batchingIntervalId = null;
this.flushBatch();
};
AGClientSocket.prototype.stopBatching = function () {
this.isBatching = false;
this._stopBatching();
};
AGClientSocket.prototype._cancelBatching = function () {
if (this._batchingIntervalId != null) {
clearInterval(this._batchingIntervalId);
}
this._batchingIntervalId = null;
this.cancelBatch();
};
AGClientSocket.prototype.cancelBatching = function () {
this.isBatching = false;
this._cancelBatching();
};
AGClientSocket.prototype._trySubscribe = function (channel) {
let meetsAuthRequirements = !channel.options.waitForAuth || this.authState === this.AUTHENTICATED;
// We can only ever have one pending subscribe action at any given time on a channel
if (
this.state === this.OPEN &&
!this.preparingPendingSubscriptions &&
channel._pendingSubscriptionCid == null &&
meetsAuthRequirements
) {
let options = {
noTimeout: true
};
let subscriptionOptions = {};
if (channel.options.waitForAuth) {
options.waitForAuth = true;
subscriptionOptions.waitForAuth = options.waitForAuth;
}
if (channel.options.data) {
subscriptionOptions.data = channel.options.data;
}
channel._pendingSubscriptionCid = this.transport.invokeRaw(
'#subscribe',
{
channel: this._decorateChannelName(channel.name),
...subscriptionOptions
},
options,
(err) => {
if (err) {
if (err.name === 'BadConnectionError') {
// In case of a failed connection, keep the subscription
// as pending; it will try again on reconnect.
return;
}
delete channel._pendingSubscriptionCid;
this._triggerChannelSubscribeFail(err, channel, subscriptionOptions);
} else {
delete channel._pendingSubscriptionCid;
this._triggerChannelSubscribe(channel, subscriptionOptions);
}
}
);
this.emit('subscribeRequest', {
channel: channel.name,
subscriptionOptions
});
}
};
AGClientSocket.prototype.subscribe = function (channelName, options) {
options = options || {};
let channel = this._channelMap[channelName];
let sanitizedOptions = {
waitForAuth: !!options.waitForAuth
};
if (options.priority != null) {
sanitizedOptions.priority = options.priority;
}
if (options.data !== undefined) {
sanitizedOptions.data = options.data;
}
if (!channel) {
channel = {
name: channelName,
state: AGChannel.PENDING,
options: sanitizedOptions
};
this._channelMap[channelName] = channel;
this._trySubscribe(channel);
} else if (options) {
channel.options = sanitizedOptions;
}
let channelIterable = new AGChannel(
channelName,
this,
this._channelEventDemux,
this._channelDataDemux
);
return channelIterable;
};
AGClientSocket.prototype._triggerChannelUnsubscribe = function (channel, setAsPending) {
let channelName = channel.name;
this._cancelPendingSubscribeCallback(channel);
if (channel.state === AGChannel.SUBSCRIBED) {
let stateChangeData = {
oldChannelState: channel.state,
newChannelState: setAsPending ? AGChannel.PENDING : AGChannel.UNSUBSCRIBED
};
this._channelEventDemux.write(`${channelName}/subscribeStateChange`, stateChangeData);
this._channelEventDemux.write(`${channelName}/unsubscribe`, {});
this.emit('subscribeStateChange', {
channel: channelName,
...stateChangeData
});
this.emit('unsubscribe', {channel: channelName});
}
if (setAsPending) {
channel.state = AGChannel.PENDING;
} else {
delete this._channelMap[channelName];
}
};
AGClientSocket.prototype._tryUnsubscribe = function (channel) {
if (this.state === this.OPEN) {
let options = {
noTimeout: true
};
// If there is a pending subscribe action, cancel the callback
this._cancelPendingSubscribeCallback(channel);
// This operation cannot fail because the TCP protocol guarantees delivery
// so long as the connection remains open. If the connection closes,
// the server will automatically unsubscribe the client and thus complete
// the operation on the server side.
let decoratedChannelName = this._decorateChannelName(channel.name);
this.transport.transmit('#unsubscribe', decoratedChannelName, options);
}
};
AGClientSocket.prototype.unsubscribe = function (channelName) {
let channel = this._channelMap[channelName];
if (channel) {
this._triggerChannelUnsubscribe(channel);
this._tryUnsubscribe(channel);
}
};
// ---- Receiver logic ----
AGClientSocket.prototype.receiver = function (receiverName) {
return this._receiverDemux.stream(receiverName);
};
AGClientSocket.prototype.closeReceiver = function (receiverName) {
this._receiverDemux.close(receiverName);
};
AGClientSocket.prototype.closeAllReceivers = function () {
this._receiverDemux.closeAll();
};
AGClientSocket.prototype.killReceiver = function (receiverName) {
this._receiverDemux.kill(receiverName);
};
AGClientSocket.prototype.killAllReceivers = function () {
this._receiverDemux.killAll();
};
AGClientSocket.prototype.killReceiverConsumer = function (consumerId) {
this._receiverDemux.killConsumer(consumerId);
};
AGClientSocket.prototype.getReceiverConsumerStats = function (consumerId) {
return this._receiverDemux.getConsumerStats(consumerId);
};
AGClientSocket.prototype.getReceiverConsumerStatsList = function (receiverName) {
return this._receiverDemux.getConsumerStatsList(receiverName);
};
AGClientSocket.prototype.getAllReceiversConsumerStatsList = function () {
return this._receiverDemux.getConsumerStatsListAll();
};
AGClientSocket.prototype.getReceiverBackpressure = function (receiverName) {
return this._receiverDemux.getBackpressure(receiverName);
};
AGClientSocket.prototype.getAllReceiversBackpressure = function () {
return this._receiverDemux.getBackpressureAll();
};
AGClientSocket.prototype.getReceiverConsumerBackpressure = function (consumerId) {
return this._receiverDemux.getConsumerBackpressure(consumerId);
};
AGClientSocket.prototype.hasReceiverConsumer = function (receiverName, consumerId) {
return this._receiverDemux.hasConsumer(receiverName, consumerId);
};
AGClientSocket.prototype.hasAnyReceiverConsumer = function (consumerId) {
return this._receiverDemux.hasConsumerAll(consumerId);
};
// ---- Procedure logic ----
AGClientSocket.prototype.procedure = function (procedureName) {
return this._procedureDemux.stream(procedureName);
};
AGClientSocket.prototype.closeProcedure = function (procedureName) {
this._procedureDemux.close(procedureName);
};
AGClientSocket.prototype.closeAllProcedures = function () {
this._procedureDemux.closeAll();
};
AGClientSocket.prototype.killProcedure = function (procedureName) {
this._procedureDemux.kill(procedureName);
};
AGClientSocket.prototype.killAllProcedures = function () {
this._procedureDemux.killAll();
};
AGClientSocket.prototype.killProcedureConsumer = function (consumerId) {
this._procedureDemux.killConsumer(consumerId);
};
AGClientSocket.prototype.getProcedureConsumerStats = function (consumerId) {
return this._procedureDemux.getConsumerStats(consumerId);
};
AGClientSocket.prototype.getProcedureConsumerStatsList = function (procedureName) {
return this._procedureDemux.getConsumerStatsList(procedureName);
};
AGClientSocket.prototype.getAllProceduresConsumerStatsList = function () {
return this._procedureDemux.getConsumerStatsListAll();
};
AGClientSocket.prototype.getProcedureBackpressure = function (procedureName) {
return this._procedureDemux.getBackpressure(procedureName);
};
AGClientSocket.prototype.getAllProceduresBackpressure = function () {
return this._procedureDemux.getBackpressureAll();
};
AGClientSocket.prototype.getProcedureConsumerBackpressure = function (consumerId) {
return this._procedureDemux.getConsumerBackpressure(consumerId);
};
AGClientSocket.prototype.hasProcedureConsumer = function (procedureName, consumerId) {
return this._procedureDemux.hasConsumer(procedureName, consumerId);
};
AGClientSocket.prototype.hasAnyProcedureConsumer = function (consumerId) {
return this._procedureDemux.hasConsumerAll(consumerId);
};
// ---- Channel logic ----
AGClientSocket.prototype.channel = function (channelName) {
let currentChannel = this._channelMap[channelName];
let channelIterable = new AGChannel(
channelName,
this,
this._channelEventDemux,
this._channelDataDemux
);
return channelIterable;
};
AGClientSocket.prototype.closeChannel = function (channelName) {
this.channelCloseOutput(channelName);
this.channelCloseAllListeners(channelName);
};
AGClientSocket.prototype.closeAllChannelOutputs = function () {
this._channelDataDemux.closeAll();
};
AGClientSocket.prototype.closeAllChannelListeners = function () {
this._channelEventDemux.closeAll();
};
AGClientSocket.prototype.closeAllChannels = function () {
this.closeAllChannelOutputs();
this.closeAllChannelListeners();
};
AGClientSocket.prototype.killChannel = function (channelName) {
this.channelKillOutput(channelName);
this.channelKillAllListeners(channelName);
};
AGClientSocket.prototype.killAllChannelOutputs = function () {
this._channelDataDemux.killAll();
};
AGClientSocket.prototype.killAllChannelListeners = function () {
this._channelEventDemux.killAll();
};
AGClientSocket.prototype.killAllChannels = function () {
this.killAllChannelOutputs();
this.killAllChannelListeners();
};
AGClientSocket.prototype.killChannelOutputConsumer = function (consumerId) {
this._channelDataDemux.killConsumer(consumerId);
};
AGClientSocket.prototype.killChannelListenerConsumer = function (consumerId) {
this._channelEventDemux.killConsumer(consumerId);
};
AGClientSocket.prototype.getChannelOutputConsumerStats = function (consumerId) {
return this._channelDataDemux.getConsumerStats(consumerId);
};
AGClientSocket.prototype.getChannelListenerConsumerStats = function (consumerId) {
return this._channelEventDemux.getConsumerStats(consumerId);
};
AGClientSocket.prototype.getAllChannelOutputsConsumerStatsList = function () {
return this._channelDataDemux.getConsumerStatsListAll();
};
AGClientSocket.prototype.getAllChannelListenersConsumerStatsList = function () {
return this._channelEventDemux.getConsumerStatsListAll();
};
AGClientSocket.prototype.getChannelBackpressure = function (channelName) {
return Math.max(
this.channelGetOutputBackpressure(channelName),
this.channelGetAllListenersBackpressure(channelName)
);
};
AGClientSocket.prototype.getAllChannelOutputsBackpressure = function () {
return this._channelDataDemux.getBackpressureAll();
};
AGClientSocket.prototype.getAllChannelListenersBackpressure = function () {
return this._channelEventDemux.getBackpressureAll();
};
AGClientSocket.prototype.getAllChannelsBackpressure = function () {
return Math.max(
this.getAllChannelOutputsBackpressure(),
this.getAllChannelListenersBackpressure()
);
};
AGClientSocket.prototype.getChannelListenerConsumerBackpressure = function (consumerId) {
return this._channelEventDemux.getConsumerBackpressure(consumerId);
};
AGClientSocket.prototype.getChannelOutputConsumerBackpressure = function (consumerId) {
return this._channelDataDemux.getConsumerBackpressure(consumerId);
};
AGClientSocket.prototype.hasAnyChannelOutputConsumer = function (consumerId) {
return this._channelDataDemux.hasConsumerAll(consumerId);
};
AGClientSocket.prototype.hasAnyChannelListenerConsumer = function (consumerId) {
return this._channelEventDemux.hasConsumerAll(consumerId);
};
AGClientSocket.prototype.getChannelState = function (channelName) {
let channel = this._channelMap[channelName];
if (channel) {
return channel.state;
}
return AGChannel.UNSUBSCRIBED;
};
AGClientSocket.prototype.getChannelOptions = function (channelName) {
let channel = this._channelMap[channelName];
if (channel) {
return {...channel.options};
}
return {};
};
AGClientSocket.prototype._getAllChannelStreamNames = function (channelName) {
let streamNamesLookup = this._channelEventDemux.getConsumerStatsListAll()
.filter((stats) => {
return stats.stream.indexOf(`${channelName}/`) === 0;
})
.reduce((accumulator, stats) => {
accumulator[stats.stream] = true;
return accumulator;
}, {});
return Object.keys(streamNamesLookup);
};
AGClientSocket.prototype.channelCloseOutput = function (channelName) {
this._channelDataDemux.close(channelName);
};
AGClientSocket.prototype.channelCloseListener = function (channelName, eventName) {
this._channelEventDemux.close(`${channelName}/${eventName}`);
};
AGClientSocket.prototype.channelCloseAllListeners = function (channelName) {
let listenerStreams = this._getAllChannelStreamNames(channelName)
.forEach((streamName) => {
this._channelEventDemux.close(streamName);
});
};
AGClientSocket.prototype.channelKillOutput = function (channelName) {
this._channelDataDemux.kill(channelName);
};
AGClientSocket.prototype.channelKillListener = function (channelName, eventName) {
this._channelEventDemux.kill(`${channelName}/${eventName}`);
};
AGClientSocket.prototype.channelKillAllListeners = function (channelName) {
let listenerStreams = this._getAllChannelStreamNames(channelName)
.forEach((streamName) => {
this._channelEventDemux.kill(streamName);
});
};
AGClientSocket.prototype.channelGetOutputConsumerStatsList = function (channelName) {
return this._channelDataDemux.getConsumerStatsList(channelName);
};
AGClientSocket.prototype.channelGetListenerConsumerStatsList = function (channelName, eventName) {
return this._channelEventDemux.getConsumerStatsList(`${channelName}/${eventName}`);
};
AGClientSocket.prototype.channelGetAllListenersConsumerStatsList = function (channelName) {
return this._getAllChannelStreamNames(channelName)
.map((streamName) => {
return this._channelEventDemux.getConsumerStatsList(streamName);
})
.reduce((accumulator, statsList) => {
statsList.forEach((stats) => {
accumulator.push(stats);
});
return accumulator;
}, []);
};
AGClientSocket.prototype.channelGetOutputBackpressure = function (channelName) {
return this._channelDataDemux.getBackpressure(channelName);
};
AGClientSocket.prototype.channelGetListenerBackpressure = function (channelName, eventName) {
return this._channelEventDemux.getBackpressure(`${channelName}/${eventName}`);
};
AGClientSocket.prototype.channelGetAllListenersBackpressure = function (channelName) {
let listenerStreamBackpressures = this._getAllChannelStreamNames(channelName)
.map((streamName) => {
return this._channelEventDemux.getBackpressure(streamName);
});
return Math.max(...listenerStreamBackpressures.concat(0));
};
AGClientSocket.prototype.channelHasOutputConsumer = function (channelName, consumerId) {
return this._channelDataDemux.hasConsumer(channelName, consumerId);
};
AGClientSocket.prototype.channelHasListenerConsumer = function (channelName, eventName, consumerId) {
return this._channelEventDemux.hasConsumer(`${channelName}/${eventName}`, consumerId);
};
AGClientSocket.prototype.channelHasAnyListenerConsumer = function (channelName, consumerId) {
return this._getAllChannelStreamNames(channelName)
.some((streamName) => {
return this._channelEventDemux.hasConsumer(streamName, consumerId);
});
};
AGClientSocket.prototype.subscriptions = function (includePending) {
let subs = [];
Object.keys(this._channelMap).forEach((channelName) => {
if (includePending || this._channelMap[channelName].state === AGChannel.SUBSCRIBED) {
subs.push(channelName);
}
});
return subs;
};
AGClientSocket.prototype.isSubscribed = function (channelName, includePending) {
let channel = this._channelMap[channelName];
if (includePending) {
return !!channel;
}
return !!channel && channel.state === AGChannel.SUBSCRIBED;
};
AGClientSocket.prototype.processPendingSubscriptions = function () {
this.preparingPendingSubscriptions = false;
let pendingChannels = [];
Object.keys(this._channelMap).forEach((channelName) => {
let channel = this._channelMap[channelName];
if (channel.state === AGChannel.PENDING) {
pendingChannels.push(channel);
}
});
pendingChannels.sort((a, b) => {
let ap = a.options.priority || 0;
let bp = b.options.priority || 0;
if (ap > bp) {
return -1;
}
if (ap < bp) {
return 1;
}
return 0;
});
pendingChannels.forEach((channel) => {
this._trySubscribe(channel);
});
};
module.exports = AGClientSocket;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./auth":1,"./transport":4,"./wait":5,"ag-channel":7,"async-stream-emitter":9,"buffer/":12,"clone-deep":13,"linked-list":20,"querystring":23,"sc-errors":25,"sc-formatter":26,"stream-demux":29}],3:[function(require,module,exports){
(function (global){
const AGClientSocket = require('./clientsocket');
const uuid = require('uuid');
const scErrors = require('sc-errors');
const InvalidArgumentsError = scErrors.InvalidArgumentsError;
function isUrlSecure() {
return global.location && location.protocol === 'https:';
}
function getPort(options, isSecureDefault) {
let isSecure = options.secure == null ? isSecureDefault : options.secure;
return options.port || (global.location && location.port ? location.port : isSecure ? 443 : 80);
}
function create(options) {
options = options || {};
if (options.host && !options.host.match(/[^:]+:\d{2,5}/)) {
throw new InvalidArgumentsError(
'The host option should include both' +
' the hostname and the port number in the format "hostname:port"'
);
}
if (options.host && options.hostname) {
throw new InvalidArgumentsError(
'The host option should already include' +
' the hostname and the port number in the format "hostname:port"' +
' - Because of this, you should never use host and hostname options together'
);
}
if (options.host && options.port) {
throw new InvalidArgumentsError(
'The host option should already include' +
' the hostname and the port number in the format "hostname:port"' +
' - Because of this, you should never use host and port options together'
);
}
let isSecureDefault = isUrlSecure();
let opts = {
clientId: uuid.v4(),
port: getPort(options, isSecureDefault),
hostname: global.location && location.hostname || 'localhost',
secure: isSecureDefault
};
Object.assign(opts, options);
return new AGClientSocket(opts);
}
module.exports = {
create
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./clientsocket":2,"sc-errors":25,"uuid":30}],4:[function(require,module,exports){
(function (global){
const AGRequest = require('ag-request');
const querystring = require('querystring');
let WebSocket;
let createWebSocket;
if (global.WebSocket) {
WebSocket = global.WebSocket;
createWebSocket = function (uri, options) {
return new WebSocket(uri);
};
} else {
WebSocket = require('ws');
createWebSocket = function (uri, options) {
return new WebSocket(uri, null, options);
};
}
const scErrors = require('sc-errors');
const TimeoutError = scErrors.TimeoutError;
const BadConnectionError = scErrors.BadConnectionError;
function AGTransport(authEngine, codecEngine, options, wsOptions, handlers) {
this.state = this.CLOSED;
this.auth = authEngine;
this.codec = codecEngine;
this.options = options;
this.wsOptions = wsOptions;
this.protocolVersion = options.protocolVersion;
this.connectTimeout = options.connectTimeout;
this.pingTimeout = options.pingTimeout;
this.pingTimeoutDisabled = !!options.pingTimeoutDisabled;
this.callIdGenerator = options.callIdGenerator;
this.authTokenName = options.authTokenName;
this.isBufferingBatch = false;
this._pingTimeoutTicker = null;
this._callbackMap = {};
this._batchBuffer = [];
if (!handlers) {
handlers = {};
}
this._onOpenHandler = handlers.onOpen || function () {};
this._onOpenAbortHandler = handlers.onOpenAbort || function () {};
this._onCloseHandler = handlers.onClose || function () {};
this._onEventHandler = handlers.onEvent || function () {};
this._onErrorHandler = handlers.onError || function () {};
this._onInboundInvokeHandler = handlers.onInboundInvoke || function () {};
this._onInboundTransmitHandler = handlers.onInboundTransmit || function () {};
// Open the connection.
this.state = this.CONNECTING;
let uri = this.uri();
let wsSocket = createWebSocket(uri, wsOptions);
wsSocket.binaryType = this.options.binaryType;
this.socket = wsSocket;
wsSocket.onopen = () => {
this._onOpen();
};
wsSocket.onclose = async (event) => {
let code;
if (event.code == null) {
// This is to handle an edge case in React Native whereby
// event.code is undefined when the mobile device is locked.
// TODO: This is not ideal since this condition could also apply to
// an abnormal close (no close control frame) which would be a 1006.
code = 1005;
} else {
code = event.code;
}
this._destroy(code, event.reason);
};
wsSocket.onmessage = (message, flags) => {
this._onMessage(message.data);
};
wsSocket.onerror = (error) => {
// The onclose event will be called automatically after the onerror event
// if the socket is connected - Otherwise, if it's in the middle of
// connecting, we want to close it manually with a 1006 - This is necessary
// to prevent inconsistent behavior when running the client in Node.js
// vs in a browser.
if (this.state === this.CONNECTING) {
this._destroy(1006);
}
};
this._connectTimeoutRef = setTimeout(() => {
this._destroy(4007);
this.socket.close(4007);
}, this.connectTimeout);
if (this.protocolVersion === 1) {
this._handlePing = (message) => {
if (message === '#1') {
this._resetPingTimeout();
if (this.socket.readyState === this.socket.OPEN) {
this.send('#2');
}
return true;
}
return false;
};
} else {
this._handlePing = (message) => {
if (message === '') {
this._resetPingTimeout();
if (this.socket.readyState === this.socket.OPEN) {
this.send('');
}
return true;
}
return false;
};
}
}
AGTransport.CONNECTING = AGTransport.prototype.CONNECTING = 'connecting';
AGTransport.OPEN = AGTransport.prototype.OPEN = 'open';
AGTransport.CLOSED = AGTransport.prototype.CLOSED = 'closed';
AGTransport.prototype.uri = function () {
let query = this.options.query || {};
let scheme;
if (this.options.protocolScheme == null) {
scheme = this.options.secure ? 'wss' : 'ws';
} else {
scheme = this.options.protocolScheme;
}
if (this.options.timestampRequests) {
query[this.options.timestampParam] = (new Date()).getTime();
}
query = querystring.encode(query);
if (query.length) {
query = '?' + query;
}
let host;
let path;
if (this.options.socketPath == null) {
if (this.options.host) {
host = this.options.host;
} else {
let port = '';
if (this.options.port && ((scheme === 'wss' && this.options.port !== 443)
|| (scheme === 'ws' && this.options.port !== 80))) {
port = ':' + this.options.port;
}
host = this.options.hostname + port;
}
path = this.options.path;
} else {
host = this.options.socketPath;
path = `:${this.options.path}`;
}
return scheme + '://' + host + path + query;
};
AGTransport.prototype._onOpen = async function () {
clearTimeout(this._connectTimeoutRef);
this._resetPingTimeout();
let status;
try {
status = await this._handshake();
} catch (err) {
if (err.statusCode == null) {
err.statusCode = 4003;
}
this._onError(err);
this._destroy(err.statusCode, err.toString());
this.socket.close(err.statusCode);
return;
}
this.state = this.OPEN;
if (status) {
this.pingTimeout = status.pingTimeout;
}
this._resetPingTimeout();
this._onOpenHandler(status);
};
AGTransport.prototype._handshake = async function () {
let token = await this.auth.loadToken(this.authTokenName);
// Don't wait for this.state to be 'open'.
// The underlying WebSocket (this.socket) is already open.
let options = {
force: true
};
let status = await this.invoke('#handshake', {authToken: token}, options);
if (status) {
// Add the token which was used as part of authentication attempt
// to the status object.
status.authToken = token;
if (status.authError) {
status.authError = scErrors.hydrateError(status.authError);
}
}
return status;
};
AGTransport.prototype._abortAllPendingEventsDueToBadConnection = function (failureType) {
Object.keys(this._callbackMap || {}).forEach((i) => {
let eventObject = this._callbackMap[i];
delete this._callbackMap[i];
clearTimeout(eventObject.timeout);
delete eventObject.timeout;
let errorMessage = `Event "${eventObject.event}" was aborted due to a bad connection`;
let badConnectionError = new BadConnectionError(errorMessage, failureType);
let callback = eventObject.callback;
if (callback) {
delete eventObject.callback;
callback.call(eventObject, badConnectionError, eventObject);
}
});
};
AGTransport.prototype._destroy = function (code, reason) {
let protocolReason = scErrors.socketProtocolErrorStatuses[code];
if (!reason && scErrors.socketProtocolErrorStatuses[code]) {
reason = scErrors.socketProtocolErrorStatuses[code];
}
delete this.socket.onopen;
delete this.socket.onclose;
delete this.socket.onmessage;
delete this.socket.onerror;
clearTimeout(this._connectTimeoutRef);
clearTimeout(this._pingTimeoutTicker);
if (this.state === this.OPEN) {
this.state = this.CLOSED;
this._abortAllPendingEventsDueToBadConnection('disconnect');
this._onCloseHandler({code, reason});
} else if (this.state === this.CONNECTING) {
this.state = this.CLOSED;
this._abortAllPendingEventsDueToBadConnection('connectAbort');
this._onOpenAbortHandler({code, reason});
} else if (this.state === this.CLOSED) {
this._abortAllPendingEventsDueToBadConnection('connectAbort');
}
};
AGTransport.prototype._processInboundPacket = function (packet, message) {
if (packet && packet.event != null) {
if (packet.cid == null) {
this._onInboundTransmitHandler({...packet});
} else {
let request = new AGRequest(this, packet.cid, packet.event, packet.data);
this._onInboundInvokeHandler(request);
}
} else if (packet && packet.rid != null) {
let eventObject = this._callbackMap[packet.rid];
if (eventObject) {
clearTimeout(eventObject.timeout);
delete eventObject.timeout;
delete this._callbackMap[packet.rid];
if (eventObject.callback) {
let rehydratedError = scErrors.hydrateError(packet.error);
eventObject.callback(rehydratedError, packet.data);
}
}
} else {
this._onEventHandler({event: 'raw', data: {message}});
}
};
AGTransport.prototype._onMessage = function (message) {
this._onEventHandler({event: 'message', data: {message}});
if (this._handlePing(message)) {
return;
}
let packet = this.decode(message);
if (Array.isArray(packet)) {
let len = packet.length;
for (let i = 0; i < len; i++) {
this._processInboundPacket(packet[i], message);
}
} else {
this._processInboundPacket(packet, message);
}
};
AGTransport.prototype._onError = function (error) {
this._onErrorHandler({error});
};
AGTransport.prototype._resetPingTimeout = function () {
if (this.pingTimeoutDisabled) {
return;
}
let now = (new Date()).getTime();
clearTimeout(this._pingTimeoutTicker);
this._pingTimeoutTicker = setTimeout(() => {
this._destroy(4000);
this.socket.close(4000);
}, this.pingTimeout);
};
AGTransport.prototype.clearAllListeners = function () {
this._onOpenHandler = function () {};
this._onOpenAbortHandler = function () {};
this._onCloseHandler = function () {};
this._onEventHandler = function () {};
this._onErrorHandler = function () {};
this._onInboundInvokeHandler = function () {};
this._onInboundTransmitHandler = function () {};
};
AGTransport.prototype.startBatch = function () {
this.isBufferingBatch = true;
this._batchBuffer = [];
};
AGTransport.prototype.flushBatch = function () {
this.isBufferingBatch = false;
if (!this._batchBuffer.length) {
return;
}
let serializedBatch = this.serializeObject(this._batchBuffer);
this._batchBuffer = [];
this.send(serializedBatch);
};
AGTransport.prototype.cancelBatch = function () {
this.isBufferingBatch = false;
this._batchBuffer = [];
};
AGTransport.prototype.getBytesReceived = function () {
return this.socket.bytesReceived;
};
AGTransport.prototype.close = function (code, reason) {
if (this.state === this.OPEN || this.state === this.CONNECTING) {
code = code || 1000;
this._destroy(code, reason);
this.socket.close(code, reason);
}
};
AGTransport.prototype.transmitObject = function (eventObject) {
let simpleEventObject = {
event: eventObject.event,
data: eventObject.data
};
if (eventObject.callback) {
simpleEventObject.cid = eventObject.cid = this.callIdGenerator();
this._callbackMap[eventObject.cid] = eventObject;
}
this.sendObject(simpleEventObject);
return eventObject.cid || null;
};
AGTransport.prototype._handleEventAckTimeout = function (eventObject) {
if (eventObject.cid) {
delete this._callbackMap[eventObject.cid];
}
delete eventObject.timeout;
let callback = eventObject.callback;
if (callback) {
delete eventObject.callback;
let error = new TimeoutError(`Event response for "${eventObject.event}" timed out`);
callback.call(eventObject, error, eventObject);
}
};
AGTransport.prototype.transmit = function (event, data, options) {
let eventObject = {
event,
data
};
if (this.state === this.OPEN || options.force) {
this.transmitObject(eventObject);
}
return Promise.resolve();
};
AGTransport.prototype.invokeRaw = function (event, data, options, callback) {
let eventObject = {
event,
data,
callback
};
if (!options.noTimeout) {
eventObject.timeout = setTimeout(() => {
this._handleEventAckTimeout(eventObject);
}, this.options.ackTimeout);
}
let cid = null;
if (this.state === this.OPEN || options.force) {
cid = this.transmitObject(eventObject);
}
return cid;
};
AGTransport.prototype.invoke = function (event, data, options) {
return new Promise((resolve, reject) => {
this.invokeRaw(event, data, options, (err, data) => {
if (err) {
reject(err);
return;
}
resolve(data);
});
});
};
AGTransport.prototype.cancelPendingResponse = function (cid) {
delete this._callbackMap[cid];
};
AGTransport.prototype.decode = function (message) {
return this.codec.decode(message);
};
AGTransport.prototype.encode = function (object) {
return this.codec.encode(object);
};
AGTransport.prototype.send = function (data) {
if (this.socket.readyState !== this.socket.OPEN) {
this._destroy(1005);
} else {
this.socket.send(data);
}
};
AGTransport.prototype.serializeObject = function (object) {
let str;
try {
str = this.encode(object);
} catch (error) {
this._onError(error);
return null;
}
return str;
};
AGTransport.prototype.sendObject = function (object) {
if (this.isBufferingBatch) {
this._batchBuffer.push(object);
return;
}
let str = this.serializeObject(object);
if (str != null) {
this.send(str);
}
};
module.exports = AGTransport;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"ag-request":8,"querystring":23,"sc-errors":25,"ws":6}],5:[function(require,module,exports){
function wait(duration) {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, duration);
});
}
module.exports = wait;
},{}],6:[function(require,module,exports){
let global;
if (typeof WorkerGlobalScope !== 'undefined') {
global = self;
} else {
global = typeof window !== 'undefined' && window || (function() { return this; })();
}
const WebSocket = global.WebSocket || global.MozWebSocket;
/**
* WebSocket constructor.
*
* The third `opts` options object gets ignored in web browsers, since it's
* non-standard, and throws a TypeError if passed to the constructor.
* See: https://github.com/einaros/ws/issues/227
*
* @param {String} uri
* @param {Array} protocols (optional)
* @param {Object} opts (optional)
* @api public
*/
function ws(uri, protocols, opts) {
let instance;
if (protocols) {
instance = new WebSocket(uri, protocols);
} else {
instance = new WebSocket(uri);
}
return instance;
}
if (WebSocket) ws.prototype = WebSocket.prototype;
module.exports = WebSocket ? ws : null;
},{}],7:[function(require,module,exports){
const ConsumableStream = require('consumable-stream');
class AGChannel extends ConsumableStream {
constructor(name, client, eventDemux, dataDemux) {
super();
this.PENDING = AGChannel.PENDING;
this.SUBSCRIBED = AGChannel.SUBSCRIBED;
this.UNSUBSCRIBED = AGChannel.UNSUBSCRIBED;
this.name = name;
this.client = client;
this._eventDemux = eventDemux;
this._dataStream = dataDemux.stream(this.name);
}
createConsumer(timeout) {
return this._dataStream.createConsumer(timeout);
}
listener(eventName) {
return this._eventDemux.stream(`${this.name}/${eventName}`);
}
close() {
this.client.closeChannel(this.name);
}
kill() {
this.client.killChannel(this.name);
}
killOutputConsumer(consumerId) {
if (this.hasOutputConsumer(consumerId)) {
this.client.killChannelOutputConsumer(consumerId);
}
}
killListenerConsumer(consumerId) {
if (this.hasAnyListenerConsumer(consumerId)) {
this.client.killChannelListenerConsumer(consumerId);
}
}
getOutputConsumerStats(consumerId) {
if (this.hasOutputConsumer(consumerId)) {
return this.client.getChannelOutputConsumerStats(consumerId);
}
return undefined;
}
getListenerConsumerStats(consumerId) {
if (this.hasAnyListenerConsumer(consumerId)) {
return this.client.getChannelListenerConsumerStats(consumerId);
}
return undefined;
}
getBackpressure() {
return this.client.getChannelBackpressure(this.name);
}
getListenerConsumerBackpressure(consumerId) {
if (this.hasAnyListenerConsumer(consumerId)) {
return this.client.getChannelListenerConsumerBackpressure(consumerId);
}
return 0;
}
getOutputConsumerBackpressure(consumerId) {
if (this.hasOutputConsumer(consumerId)) {
return this.client.getChannelOutputConsumerBackpressure(consumerId);
}
return 0;
}
closeOutput() {
this.client.channelCloseOutput(this.name);
}
closeListener(eventName) {
this.client.channelCloseListener(this.name, eventName);
}
closeAllListeners() {
this.client.channelCloseAllListeners(this.name);
}
killOutput() {
this.client.channelKillOutput(this.name);
}
killListener(eventName) {
this.client.channelKillListener(this.name, eventName);
}
killAllListeners() {
this.client.channelKillAllListeners(this.name);
}
getOutputConsumerStatsList() {
return this.client.channelGetOutputConsumerStatsList(this.name);
}
getListenerConsumerStatsList(eventName) {
return this.client.channelGetListenerConsumerStatsList(this.name, eventName);
}
getAllListenersConsumerStatsList() {
return this.client.channelGetAllListenersConsumerStatsList(this.name);
}
getOutputBackpressure() {
return this.client.channelGetOutputBackpressure(this.name);
}
getListenerBackpressure(eventName) {
return this.client.channelGetListenerBackpressure(this.name, eventName);
}
getAllListenersBackpressure() {
return this.client.channelGetAllListenersBackpressure(this.name);
}
hasOutputConsumer(consumerId) {
return this.client.channelHasOutputConsumer(this.name, consumerId);
}
hasListenerConsumer(eventName, consumerId) {
return this.client.channelHasListenerConsumer(this.name, eventName, consumerId);
}
hasAnyListenerConsumer(consumerId) {
return this.client.channelHasAnyListenerConsumer(this.name, consumerId);
}
get state() {
return this.client.getChannelState(this.name);
}
set state(value) {
throw new Error('Cannot directly set channel state');
}
get options() {
return this.client.getChannelOptions(this.name);
}
set options(value) {
throw new Error('Cannot directly set channel options');
}
subscribe(options) {
this.client.subscribe(this.name, options);
}
unsubscribe() {
this.client.unsubscribe(this.name);
}
isSubscribed(includePending) {
return this.client.isSubscribed(this.name, includePending);
}
transmitPublish(data) {
return this.client.transmitPublish(this.name, data);
}
invokePublish(data) {
return this.client.invokePublish(this.name, data);
}
}
AGChannel.PENDING = 'pending';
AGChannel.SUBSCRIBED = 'subscribed';
AGChannel.UNSUBSCRIBED = 'unsubscribed';
module.exports = AGChannel;
},{"consumable-stream":14}],8:[function(require,module,exports){
const scErrors = require('sc-errors');
const InvalidActionError = scErrors.InvalidActionError;
function AGRequest(socket, id, procedureName, data) {
this.socket = socket;
this.id = id;
this.procedure = procedureName;
this.data = data;
this.sent = false;
this._respond = (responseData, options) => {
if (this.sent) {
throw new InvalidActionError(`Response to request ${this.id} has already been sent`);
}
this.sent = true;
this.socket.sendObject(responseData, options);
};
this.end = (data, options) => {
let responseData = {
rid: this.id
};
if (data !== undefined) {
responseData.data = data;
}
this._respond(responseData, options);
};
this.error = (error, options) => {
let responseData = {
rid: this.id,
error: scErrors.dehydrateError(error)
};
this._respond(responseData, options);
};
}
module.exports = AGRequest;
},{"sc-errors":25}],9:[function(require,module,exports){
const StreamDemux = require('stream-demux');
function AsyncStreamEmitter() {
this._listenerDemux = new StreamDemux();
}
AsyncStreamEmitter.prototype.emit = function (eventName, data) {
this._listenerDemux.write(eventName, data);
};
AsyncStreamEmitter.prototype.listener = function (eventName) {
return this._listenerDemux.stream(eventName);
};
AsyncStreamEmitter.prototype.closeListener = function (eventName) {
this._listenerDemux.close(eventName);
};
AsyncStreamEmitter.prototype.closeAllListeners = function () {
this._listenerDemux.closeAll();
};
AsyncStreamEmitter.prototype.getListenerConsumerStats = function (consumerId) {
return this._listenerDemux.getConsumerStats(consumerId);
};
AsyncStreamEmitter.prototype.getListenerConsumerStatsList = function (eventName) {
return this._listenerDemux.getConsumerStatsList(eventName);
};
AsyncStreamEmitter.prototype.getAllListenersConsumerStatsList = function () {
return this._listenerDemux.getConsumerStatsListAll();
};
AsyncStreamEmitter.prototype.killListener = function (eventName) {
this._listenerDemux.kill(eventName);
};
AsyncStreamEmitter.prototype.killAllListeners = function () {
this._listenerDemux.killAll();
};
AsyncStreamEmitter.prototype.killListenerConsumer = function (consumerId) {
this._listenerDemux.killConsumer(consumerId);
};
AsyncStreamEmitter.prototype.getListenerBackpressure = function (eventName) {
return this._listenerDemux.getBackpressure(eventName);
};
AsyncStreamEmitter.prototype.getAllListenersBackpressure = function () {
return this._listenerDemux.getBackpressureAll();
};
AsyncStreamEmitter.prototype.getListenerConsumerBackpressure = function (consumerId) {
return this._listenerDemux.getConsumerBackpressure(consumerId);
};
AsyncStreamEmitter.prototype.hasListenerConsumer = function (eventName, consumerId) {
return this._listenerDemux.hasConsumer(eventName, consumerId);
};
AsyncStreamEmitter.prototype.hasAnyListenerConsumer = function (consumerId) {
return this._listenerDemux.hasConsumerAll(consumerId);
};
module.exports = AsyncStreamEmitter;
},{"stream-demux":29}],10:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function getLens (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
var validLen = b64.indexOf('=')
if (validLen === -1) validLen = len
var placeHoldersLen = validLen === len
? 0
: 4 - (validLen % 4)
return [validLen, placeHoldersLen]
}
// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function _byteLength (b64, validLen, placeHoldersLen) {
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function toByteArray (b64) {
var tmp
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
var curByte = 0
// if there are placeholders, only get up to the last complete 4 chars
var len = placeHoldersLen > 0
? validLen - 4
: validLen
var i
for (i = 0; i < len; i += 4) {
tmp =
(revLookup[b64.charCodeAt(i)] << 18) |
(revLookup[b64.charCodeAt(i + 1)] << 12) |
(revLookup[b64.charCodeAt(i + 2)] << 6) |
revLookup[b64.charCodeAt(i + 3)]
arr[curByte++] = (tmp >> 16) & 0xFF
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 2) {
tmp =
(revLookup[b64.charCodeAt(i)] << 2) |
(revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 1) {
tmp =
(revLookup[b64.charCodeAt(i)] << 10) |
(revLookup[b64.charCodeAt(i + 1)] << 4) |
(revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] +
lookup[num >> 12 & 0x3F] +
lookup[num >> 6 & 0x3F] +
lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp =
((uint8[i] << 16) & 0xFF0000) +
((uint8[i + 1] << 8) & 0xFF00) +
(uint8[i + 2] & 0xFF)
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(
uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
parts.push(
lookup[tmp >> 2] +
lookup[(tmp << 4) & 0x3F] +
'=='
)
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1]
parts.push(
lookup[tmp >> 10] +
lookup[(tmp >> 4) & 0x3F] +
lookup[(tmp << 2) & 0x3F] +
'='
)
}
return parts.join('')
}
},{}],11:[function(require,module,exports){
(function (Buffer){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
typeof console.error === 'function') {
console.error(
'This browser lacks typed array (Uint8Array) support which is required by ' +
'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
)
}
function typedArraySupport () {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1)
arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
return arr.foo() === 42
} catch (e) {
return false
}
}
Object.defineProperty(Buffer.prototype, 'parent', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.buffer
}
})
Object.defineProperty(Buffer.prototype, 'offset', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.byteOffset
}
})
function createBuffer (length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('The value "' + length + '" is invalid for option "size"')
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length)
buf.__proto__ = Buffer.prototype
return buf
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new TypeError(
'The "string" argument must be of type string. Received type number'
)
}
return allocUnsafe(arg)
}
return from(arg, encodingOrOffset, length)
}
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species != null &&
Buffer[Symbol.species] === Buffer) {
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
enumerable: false,
writable: false
})
}
Buffer.poolSize = 8192 // not used by this implementation
function from (value, encodingOrOffset, length) {
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
if (ArrayBuffer.isView(value)) {
return fromArrayLike(value)
}
if (value == null) {
throw TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
if (isInstance(value, ArrayBuffer) ||
(value && isInstance(value.buffer, ArrayBuffer))) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'number') {
throw new TypeError(
'The "value" argument must not be of type number. Received type number'
)
}
var valueOf = value.valueOf && value.valueOf()
if (valueOf != null && valueOf !== value) {
return Buffer.from(valueOf, encodingOrOffset, length)
}
var b = fromObject(value)
if (b) return b
if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
typeof value[Symbol.toPrimitive] === 'function') {
return Buffer.from(
value[Symbol.toPrimitive]('string'), encodingOrOffset, length
)
}
throw new TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length)
}
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be of type number')
} else if (size < 0) {
throw new RangeError('The value "' + size + '" is invalid for option "size"')
}
}
function alloc (size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(size).fill(fill, encoding)
: createBuffer(size).fill(fill)
}
return createBuffer(size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding)
}
function allocUnsafe (size) {
assertSize(size)
return createBuffer(size < 0 ? 0 : checked(size) | 0)
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size)
}
function fromString (string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
var length = byteLength(string, encoding) | 0
var buf = createBuffer(length)
var actual = buf.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual)
}
return buf
}
function fromArrayLike (array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
var buf = createBuffer(length)
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255
}
return buf
}
function fromArrayBuffer (array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('"offset" is outside of buffer bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('"length" is outside of buffer bounds')
}
var buf
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array)
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset)
} else {
buf = new Uint8Array(array, byteOffset, length)
}
// Return an augmented `Uint8Array` instance
buf.__proto__ = Buffer.prototype
return buf
}
function fromObject (obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
var buf = createBuffer(len)
if (buf.length === 0) {
return buf
}
obj.copy(buf, 0, 0, len)
return buf
}
if (obj.length !== undefined) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0)
}
return fromArrayLike(obj)
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data)
}
}
function checked (length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return b != null && b._isBuffer === true &&
b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
}
Buffer.compare = function compare (a, b) {
if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError(
'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
)
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (isInstance(buf, Uint8Array)) {
buf = Buffer.from(buf)
}
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
throw new TypeError(
'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
'Received type ' + typeof string
)
}
var len = string.length
var mustMatch = (arguments.length > 2 && arguments[2] === true)
if (!mustMatch && len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) {
return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
}
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.toLocaleString = Buffer.prototype.toString
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
if (this.length > max) str += ' ... '
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (isInstance(target, Uint8Array)) {
target = Buffer.from(target, target.offset, target.byteLength)
}
if (!Buffer.isBuffer(target)) {
throw new TypeError(
'The "target" argument must be one of type Buffer or Uint8Array. ' +
'Received type ' + (typeof target)
)
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (numberIsNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
var strLen = string.length
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (numberIsNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0
if (isFinite(length)) {
length = length >>> 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf = this.subarray(start, end)
// Return an augmented `Uint8Array` instance
newBuf.__proto__ = Buffer.prototype
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
// Use built-in when available, missing from IE11
this.copyWithin(targetStart, start, end)
} else if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (var i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, end),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if ((encoding === 'utf8' && code < 128) ||
encoding === 'latin1') {
// Fast path: If `val` fits into a single byte, use that numeric value.
val = code
}
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: Buffer.from(val, encoding)
var len = bytes.length
if (len === 0) {
throw new TypeError('The value "' + val +
'" is invalid for argument "value"')
}
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
function base64clean (str) {
// Node takes equal signs as end of the Base64 encoding
str = str.split('=')[0]
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
// the `instanceof` check but they should be treated as of that type.
// See: https://github.com/feross/buffer/issues/166
function isInstance (obj, type) {
return obj instanceof type ||
(obj != null && obj.constructor != null && obj.constructor.name != null &&
obj.constructor.name === type.name)
}
function numberIsNaN (obj) {
// For IE11 support
return obj !== obj // eslint-disable-line no-self-compare
}
}).call(this,require("buffer").Buffer)
},{"base64-js":10,"buffer":11,"ieee754":15}],12:[function(require,module,exports){
(function (Buffer){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
var customInspectSymbol =
(typeof Symbol === 'function' && typeof Symbol.for === 'function')
? Symbol.for('nodejs.util.inspect.custom')
: null
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
typeof console.error === 'function') {
console.error(
'This browser lacks typed array (Uint8Array) support which is required by ' +
'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
)
}
function typedArraySupport () {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1)
var proto = { foo: function () { return 42 } }
Object.setPrototypeOf(proto, Uint8Array.prototype)
Object.setPrototypeOf(arr, proto)
return arr.foo() === 42
} catch (e) {
return false
}
}
Object.defineProperty(Buffer.prototype, 'parent', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.buffer
}
})
Object.defineProperty(Buffer.prototype, 'offset', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.byteOffset
}
})
function createBuffer (length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('The value "' + length + '" is invalid for option "size"')
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length)
Object.setPrototypeOf(buf, Buffer.prototype)
return buf
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new TypeError(
'The "string" argument must be of type string. Received type number'
)
}
return allocUnsafe(arg)
}
return from(arg, encodingOrOffset, length)
}
Buffer.poolSize = 8192 // not used by this implementation
function from (value, encodingOrOffset, length) {
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
if (ArrayBuffer.isView(value)) {
return fromArrayLike(value)
}
if (value == null) {
throw new TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
if (isInstance(value, ArrayBuffer) ||
(value && isInstance(value.buffer, ArrayBuffer))) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof SharedArrayBuffer !== 'undefined' &&
(isInstance(value, SharedArrayBuffer) ||
(value && isInstance(value.buffer, SharedArrayBuffer)))) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'number') {
throw new TypeError(
'The "value" argument must not be of type number. Received type number'
)
}
var valueOf = value.valueOf && value.valueOf()
if (valueOf != null && valueOf !== value) {
return Buffer.from(valueOf, encodingOrOffset, length)
}
var b = fromObject(value)
if (b) return b
if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
typeof value[Symbol.toPrimitive] === 'function') {
return Buffer.from(
value[Symbol.toPrimitive]('string'), encodingOrOffset, length
)
}
throw new TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length)
}
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)
Object.setPrototypeOf(Buffer, Uint8Array)
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be of type number')
} else if (size < 0) {
throw new RangeError('The value "' + size + '" is invalid for option "size"')
}
}
function alloc (size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(size).fill(fill, encoding)
: createBuffer(size).fill(fill)
}
return createBuffer(size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding)
}
function allocUnsafe (size) {
assertSize(size)
return createBuffer(size < 0 ? 0 : checked(size) | 0)
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size)
}
function fromString (string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
var length = byteLength(string, encoding) | 0
var buf = createBuffer(length)
var actual = buf.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual)
}
return buf
}
function fromArrayLike (array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
var buf = createBuffer(length)
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255
}
return buf
}
function fromArrayBuffer (array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('"offset" is outside of buffer bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('"length" is outside of buffer bounds')
}
var buf
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array)
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset)
} else {
buf = new Uint8Array(array, byteOffset, length)
}
// Return an augmented `Uint8Array` instance
Object.setPrototypeOf(buf, Buffer.prototype)
return buf
}
function fromObject (obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
var buf = createBuffer(len)
if (buf.length === 0) {
return buf
}
obj.copy(buf, 0, 0, len)
return buf
}
if (obj.length !== undefined) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0)
}
return fromArrayLike(obj)
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data)
}
}
function checked (length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return b != null && b._isBuffer === true &&
b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
}
Buffer.compare = function compare (a, b) {
if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError(
'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
)
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (isInstance(buf, Uint8Array)) {
buf = Buffer.from(buf)
}
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
throw new TypeError(
'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
'Received type ' + typeof string
)
}
var len = string.length
var mustMatch = (arguments.length > 2 && arguments[2] === true)
if (!mustMatch && len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) {
return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
}
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.toLocaleString = Buffer.prototype.toString
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
if (this.length > max) str += ' ... '
return '<Buffer ' + str + '>'
}
if (customInspectSymbol) {
Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (isInstance(target, Uint8Array)) {
target = Buffer.from(target, target.offset, target.byteLength)
}
if (!Buffer.isBuffer(target)) {
throw new TypeError(
'The "target" argument must be one of type Buffer or Uint8Array. ' +
'Received type ' + (typeof target)
)
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (numberIsNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
var strLen = string.length
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (numberIsNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0
if (isFinite(length)) {
length = length >>> 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += hexSliceLookupTable[buf[i]]
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf = this.subarray(start, end)
// Return an augmented `Uint8Array` instance
Object.setPrototypeOf(newBuf, Buffer.prototype)
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
// Use built-in when available, missing from IE11
this.copyWithin(targetStart, start, end)
} else if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (var i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, end),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if ((encoding === 'utf8' && code < 128) ||
encoding === 'latin1') {
// Fast path: If `val` fits into a single byte, use that numeric value.
val = code
}
}
} else if (typeof val === 'number') {
val = val & 255
} else if (typeof val === 'boolean') {
val = Number(val)
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: Buffer.from(val, encoding)
var len = bytes.length
if (len === 0) {
throw new TypeError('The value "' + val +
'" is invalid for argument "value"')
}
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
function base64clean (str) {
// Node takes equal signs as end of the Base64 encoding
str = str.split('=')[0]
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
// the `instanceof` check but they should be treated as of that type.
// See: https://github.com/feross/buffer/issues/166
function isInstance (obj, type) {
return obj instanceof type ||
(obj != null && obj.constructor != null && obj.constructor.name != null &&
obj.constructor.name === type.name)
}
function numberIsNaN (obj) {
// For IE11 support
return obj !== obj // eslint-disable-line no-self-compare
}
// Create lookup table for `toString('hex')`
// See: https://github.com/feross/buffer/issues/219
var hexSliceLookupTable = (function () {
var alphabet = '0123456789abcdef'
var table = new Array(256)
for (var i = 0; i < 16; ++i) {
var i16 = i * 16
for (var j = 0; j < 16; ++j) {
table[i16 + j] = alphabet[i] + alphabet[j]
}
}
return table
})()
}).call(this,require("buffer").Buffer)
},{"base64-js":10,"buffer":11,"ieee754":15}],13:[function(require,module,exports){
'use strict';
/**
* Module dependenices
*/
const clone = require('shallow-clone');
const typeOf = require('kind-of');
const isPlainObject = require('is-plain-object');
function cloneDeep(val, instanceClone) {
switch (typeOf(val)) {
case 'object':
return cloneObjectDeep(val, instanceClone);
case 'array':
return cloneArrayDeep(val, instanceClone);
default: {
return clone(val);
}
}
}
function cloneObjectDeep(val, instanceClone) {
if (typeof instanceClone === 'function') {
return instanceClone(val);
}
if (instanceClone || isPlainObject(val)) {
const res = new val.constructor();
for (let key in val) {
res[key] = cloneDeep(val[key], instanceClone);
}
return res;
}
return val;
}
function cloneArrayDeep(val, instanceClone) {
const res = new val.constructor(val.length);
for (let i = 0; i < val.length; i++) {
res[i] = cloneDeep(val[i], instanceClone);
}
return res;
}
/**
* Expose `cloneDeep`
*/
module.exports = cloneDeep;
},{"is-plain-object":16,"kind-of":18,"shallow-clone":27}],14:[function(require,module,exports){
class ConsumableStream {
async next(timeout) {
let asyncIterator = this.createConsumer(timeout);
let result = await asyncIterator.next();
asyncIterator.return();
return result;
}
async once(timeout) {
let result = await this.next(timeout);
if (result.done) {
// If stream was ended, this function should never resolve.
await new Promise(() => {});
}
return result.value;
}
createConsumer() {
throw new TypeError('Method must be overriden by subclass');
}
[Symbol.asyncIterator]() {
return this.createConsumer();
}
}
module.exports = ConsumableStream;
},{}],15:[function(require,module,exports){
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = ((value * c) - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],16:[function(require,module,exports){
/*!
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
'use strict';
var isObject = require('isobject');
function isObjectObject(o) {
return isObject(o) === true
&& Object.prototype.toString.call(o) === '[object Object]';
}
module.exports = function isPlainObject(o) {
var ctor,prot;
if (isObjectObject(o) === false) return false;
// If has modified constructor
ctor = o.constructor;
if (typeof ctor !== 'function') return false;
// If has modified prototype
prot = ctor.prototype;
if (isObjectObject(prot) === false) return false;
// If constructor does not have an Object-specific method
if (prot.hasOwnProperty('isPrototypeOf') === false) {
return false;
}
// Most likely a plain Object
return true;
};
},{"isobject":17}],17:[function(require,module,exports){
/*!
* isobject <https://github.com/jonschlinkert/isobject>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
'use strict';
module.exports = function isObject(val) {
return val != null && typeof val === 'object' && Array.isArray(val) === false;
};
},{}],18:[function(require,module,exports){
var toString = Object.prototype.toString;
module.exports = function kindOf(val) {
if (val === void 0) return 'undefined';
if (val === null) return 'null';
var type = typeof val;
if (type === 'boolean') return 'boolean';
if (type === 'string') return 'string';
if (type === 'number') return 'number';
if (type === 'symbol') return 'symbol';
if (type === 'function') {
return isGeneratorFn(val) ? 'generatorfunction' : 'function';
}
if (isArray(val)) return 'array';
if (isBuffer(val)) return 'buffer';
if (isArguments(val)) return 'arguments';
if (isDate(val)) return 'date';
if (isError(val)) return 'error';
if (isRegexp(val)) return 'regexp';
switch (ctorName(val)) {
case 'Symbol': return 'symbol';
case 'Promise': return 'promise';
// Set, Map, WeakSet, WeakMap
case 'WeakMap': return 'weakmap';
case 'WeakSet': return 'weakset';
case 'Map': return 'map';
case 'Set': return 'set';
// 8-bit typed arrays
case 'Int8Array': return 'int8array';
case 'Uint8Array': return 'uint8array';
case 'Uint8ClampedArray': return 'uint8clampedarray';
// 16-bit typed arrays
case 'Int16Array': return 'int16array';
case 'Uint16Array': return 'uint16array';
// 32-bit typed arrays
case 'Int32Array': return 'int32array';
case 'Uint32Array': return 'uint32array';
case 'Float32Array': return 'float32array';
case 'Float64Array': return 'float64array';
}
if (isGeneratorObj(val)) {
return 'generator';
}
// Non-plain objects
type = toString.call(val);
switch (type) {
case '[object Object]': return 'object';
// iterators
case '[object Map Iterator]': return 'mapiterator';
case '[object Set Iterator]': return 'setiterator';
case '[object String Iterator]': return 'stringiterator';
case '[object Array Iterator]': return 'arrayiterator';
}
// other
return type.slice(8, -1).toLowerCase().replace(/\s/g, '');
};
function ctorName(val) {
return typeof val.constructor === 'function' ? val.constructor.name : null;
}
function isArray(val) {
if (Array.isArray) return Array.isArray(val);
return val instanceof Array;
}
function isError(val) {
return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number');
}
function isDate(val) {
if (val instanceof Date) return true;
return typeof val.toDateString === 'function'
&& typeof val.getDate === 'function'
&& typeof val.setDate === 'function';
}
function isRegexp(val) {
if (val instanceof RegExp) return true;
return typeof val.flags === 'string'
&& typeof val.ignoreCase === 'boolean'
&& typeof val.multiline === 'boolean'
&& typeof val.global === 'boolean';
}
function isGeneratorFn(name, val) {
return ctorName(name) === 'GeneratorFunction';
}
function isGeneratorObj(val) {
return typeof val.throw === 'function'
&& typeof val.return === 'function'
&& typeof val.next === 'function';
}
function isArguments(val) {
try {
if (typeof val.length === 'number' && typeof val.callee === 'function') {
return true;
}
} catch (err) {
if (err.message.indexOf('callee') !== -1) {
return true;
}
}
return false;
}
/**
* If you need to support Safari 5-7 (8-10 yr-old browser),
* take a look at https://github.com/feross/is-buffer
*/
function isBuffer(val) {
if (val.constructor && typeof val.constructor.isBuffer === 'function') {
return val.constructor.isBuffer(val);
}
return false;
}
},{}],19:[function(require,module,exports){
'use strict';
/**
* Constants.
*/
var errorMessage;
errorMessage = 'An argument without append, prepend, ' +
'or detach methods was given to `List';
/**
* Creates a new List: A linked list is a bit like an Array, but
* knows nothing about how many items are in it, and knows only about its
* first (`head`) and last (`tail`) items. Each item (e.g. `head`, `tail`,
* &c.) knows which item comes before or after it (its more like the
* implementation of the DOM in JavaScript).
* @global
* @private
* @constructor
* @class Represents an instance of List.
*/
function List(/*items...*/) {
if (arguments.length) {
return List.from(arguments);
}
}
var ListPrototype;
ListPrototype = List.prototype;
/**
* Creates a new list from the arguments (each a list item) passed in.
* @name List.of
* @param {...ListItem} [items] - Zero or more items to attach.
* @returns {list} - A new instance of List.
*/
List.of = function (/*items...*/) {
return List.from.call(this, arguments);
};
/**
* Creates a new list from the given array-like object (each a list item)
* passed in.
* @name List.from
* @param {ListItem[]} [items] - The items to append.
* @returns {list} - A new instance of List.
*/
List.from = function (items) {
var list = new this(), length, iterator, item;
if (items && (length = items.length)) {
iterator = -1;
while (++iterator < length) {
item = items[iterator];
if (item !== null && item !== undefined) {
list.append(item);
}
}
}
return list;
};
/**
* List#head
* Default to `null`.
*/
ListPrototype.head = null;
/**
* List#tail
* Default to `null`.
*/
ListPrototype.tail = null;
/**
* Returns the list's items as an array. This does *not* detach the items.
* @name List#toArray
* @returns {ListItem[]} - An array of (still attached) ListItems.
*/
ListPrototype.toArray = function () {
var item = this.head,
result = [];
while (item) {
result.push(item);
item = item.next;
}
return result;
};
/**
* Prepends the given item to the list: Item will be the new first item
* (`head`).
* @name List#prepend
* @param {ListItem} item - The item to prepend.
* @returns {ListItem} - An instance of ListItem (the given item).
*/
ListPrototype.prepend = function (item) {
if (!item) {
return false;
}
if (!item.append || !item.prepend || !item.detach) {
throw new Error(errorMessage + '#prepend`.');
}
var self, head;
// Cache self.
self = this;
// If self has a first item, defer prepend to the first items prepend
// method, and return the result.
head = self.head;
if (head) {
return head.prepend(item);
}
// ...otherwise, there is no `head` (or `tail`) item yet.
// Detach the prependee.
item.detach();
// Set the prependees parent list to reference self.
item.list = self;
// Set self's first item to the prependee, and return the item.
self.head = item;
return item;
};
/**
* Appends the given item to the list: Item will be the new last item (`tail`)
* if the list had a first item, and its first item (`head`) otherwise.
* @name List#append
* @param {ListItem} item - The item to append.
* @returns {ListItem} - An instance of ListItem (the given item).
*/
ListPrototype.append = function (item) {
if (!item) {
return false;
}
if (!item.append || !item.prepend || !item.detach) {
throw new Error(errorMessage + '#append`.');
}
var self, head, tail;
// Cache self.
self = this;
// If self has a last item, defer appending to the last items append
// method, and return the result.
tail = self.tail;
if (tail) {
return tail.append(item);
}
// If self has a first item, defer appending to the first items append
// method, and return the result.
head = self.head;
if (head) {
return head.append(item);
}
// ...otherwise, there is no `tail` or `head` item yet.
// Detach the appendee.
item.detach();
// Set the appendees parent list to reference self.
item.list = self;
// Set self's first item to the appendee, and return the item.
self.head = item;
return item;
};
/**
* Creates a new ListItem: A linked list item is a bit like DOM node:
* It knows only about its "parent" (`list`), the item before it (`prev`),
* and the item after it (`next`).
* @global
* @private
* @constructor
* @class Represents an instance of ListItem.
*/
function ListItem() {}
List.Item = ListItem;
var ListItemPrototype = ListItem.prototype;
ListItemPrototype.next = null;
ListItemPrototype.prev = null;
ListItemPrototype.list = null;
/**
* Detaches the item operated on from its parent list.
* @name ListItem#detach
* @returns {ListItem} - The item operated on.
*/
ListItemPrototype.detach = function () {
// Cache self, the parent list, and the previous and next items.
var self = this,
list = self.list,
prev = self.prev,
next = self.next;
// If the item is already detached, return self.
if (!list) {
return self;
}
// If self is the last item in the parent list, link the lists last item
// to the previous item.
if (list.tail === self) {
list.tail = prev;
}
// If self is the first item in the parent list, link the lists first item
// to the next item.
if (list.head === self) {
list.head = next;
}
// If both the last and first items in the parent list are the same,
// remove the link to the last item.
if (list.tail === list.head) {
list.tail = null;
}
// If a previous item exists, link its next item to selfs next item.
if (prev) {
prev.next = next;
}
// If a next item exists, link its previous item to selfs previous item.
if (next) {
next.prev = prev;
}
// Remove links from self to both the next and previous items, and to the
// parent list.
self.prev = self.next = self.list = null;
// Return self.
return self;
};
/**
* Prepends the given item *before* the item operated on.
* @name ListItem#prepend
* @param {ListItem} item - The item to prepend.
* @returns {ListItem} - The item operated on, or false when that item is not
* attached.
*/
ListItemPrototype.prepend = function (item) {
if (!item || !item.append || !item.prepend || !item.detach) {
throw new Error(errorMessage + 'Item#prepend`.');
}
// Cache self, the parent list, and the previous item.
var self = this,
list = self.list,
prev = self.prev;
// If self is detached, return false.
if (!list) {
return false;
}
// Detach the prependee.
item.detach();
// If self has a previous item...
if (prev) {
// ...link the prependees previous item, to selfs previous item.
item.prev = prev;
// ...link the previous items next item, to self.
prev.next = item;
}
// Set the prependees next item to self.
item.next = self;
// Set the prependees parent list to selfs parent list.
item.list = list;
// Set the previous item of self to the prependee.
self.prev = item;
// If self is the first item in the parent list, link the lists first item
// to the prependee.
if (self === list.head) {
list.head = item;
}
// If the the parent list has no last item, link the lists last item to
// self.
if (!list.tail) {
list.tail = self;
}
// Return the prependee.
return item;
};
/**
* Appends the given item *after* the item operated on.
* @name ListItem#append
* @param {ListItem} item - The item to append.
* @returns {ListItem} - The item operated on, or false when that item is not
* attached.
*/
ListItemPrototype.append = function (item) {
// If item is falsey, return false.
if (!item || !item.append || !item.prepend || !item.detach) {
throw new Error(errorMessage + 'Item#append`.');
}
// Cache self, the parent list, and the next item.
var self = this,
list = self.list,
next = self.next;
// If self is detached, return false.
if (!list) {
return false;
}
// Detach the appendee.
item.detach();
// If self has a next item...
if (next) {
// ...link the appendees next item, to selfs next item.
item.next = next;
// ...link the next items previous item, to the appendee.
next.prev = item;
}
// Set the appendees previous item to self.
item.prev = self;
// Set the appendees parent list to selfs parent list.
item.list = list;
// Set the next item of self to the appendee.
self.next = item;
// If the the parent list has no last item or if self is the parent lists
// last item, link the lists last item to the appendee.
if (self === list.tail || !list.tail) {
list.tail = item;
}
// Return the appendee.
return item;
};
/**
* Expose `List`.
*/
module.exports = List;
},{}],20:[function(require,module,exports){
'use strict';
module.exports = require('./_source/linked-list.js');
},{"./_source/linked-list.js":19}],21:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
module.exports = function(qs, sep, eq, options) {
sep = sep || '&';
eq = eq || '=';
var obj = {};
if (typeof qs !== 'string' || qs.length === 0) {
return obj;
}
var regexp = /\+/g;
qs = qs.split(sep);
var maxKeys = 1000;
if (options && typeof options.maxKeys === 'number') {
maxKeys = options.maxKeys;
}
var len = qs.length;
// maxKeys <= 0 means that we should not limit keys count
if (maxKeys > 0 && len > maxKeys) {
len = maxKeys;
}
for (var i = 0; i < len; ++i) {
var x = qs[i].replace(regexp, '%20'),
idx = x.indexOf(eq),
kstr, vstr, k, v;
if (idx >= 0) {
kstr = x.substr(0, idx);
vstr = x.substr(idx + 1);
} else {
kstr = x;
vstr = '';
}
k = decodeURIComponent(kstr);
v = decodeURIComponent(vstr);
if (!hasOwnProperty(obj, k)) {
obj[k] = v;
} else if (isArray(obj[k])) {
obj[k].push(v);
} else {
obj[k] = [obj[k], v];
}
}
return obj;
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
},{}],22:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
var stringifyPrimitive = function(v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
module.exports = function(obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map(objectKeys(obj), function(k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray(obj[k])) {
return map(obj[k], function(v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function map (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
},{}],23:[function(require,module,exports){
'use strict';
exports.decode = exports.parse = require('./decode');
exports.encode = exports.stringify = require('./encode');
},{"./decode":21,"./encode":22}],24:[function(require,module,exports){
// Based on https://github.com/dscape/cycle/blob/master/cycle.js
module.exports = function decycle(object) {
// Make a deep copy of an object or array, assuring that there is at most
// one instance of each object or array in the resulting structure. The
// duplicate references (which might be forming cycles) are replaced with
// an object of the form
// {$ref: PATH}
// where the PATH is a JSONPath string that locates the first occurance.
// So,
// var a = [];
// a[0] = a;
// return JSON.stringify(JSON.decycle(a));
// produces the string '[{"$ref":"$"}]'.
// JSONPath is used to locate the unique object. $ indicates the top level of
// the object or array. [NUMBER] or [STRING] indicates a child member or
// property.
var objects = [], // Keep a reference to each unique object or array
paths = []; // Keep the path to each unique object or array
return (function derez(value, path) {
// The derez recurses through the object, producing the deep copy.
var i, // The loop counter
name, // Property name
nu; // The new object or array
// typeof null === 'object', so go on if this value is really an object but not
// one of the weird builtin objects.
if (typeof value === 'object' && value !== null &&
!(value instanceof Boolean) &&
!(value instanceof Date) &&
!(value instanceof Number) &&
!(value instanceof RegExp) &&
!(value instanceof String)) {
// If the value is an object or array, look to see if we have already
// encountered it. If so, return a $ref/path object. This is a hard way,
// linear search that will get slower as the number of unique objects grows.
for (i = 0; i < objects.length; i += 1) {
if (objects[i] === value) {
return {$ref: paths[i]};
}
}
// Otherwise, accumulate the unique value and its path.
objects.push(value);
paths.push(path);
// If it is an array, replicate the array.
if (Object.prototype.toString.apply(value) === '[object Array]') {
nu = [];
for (i = 0; i < value.length; i += 1) {
nu[i] = derez(value[i], path + '[' + i + ']');
}
} else {
// If it is an object, replicate the object.
nu = {};
for (name in value) {
if (Object.prototype.hasOwnProperty.call(value, name)) {
nu[name] = derez(value[name],
path + '[' + JSON.stringify(name) + ']');
}
}
}
return nu;
}
return value;
}(object, '$'));
};
},{}],25:[function(require,module,exports){
var decycle = require('./decycle');
var isStrict = (function () { return !this; })();
function AuthTokenExpiredError(message, expiry) {
this.name = 'AuthTokenExpiredError';
this.message = message;
this.expiry = expiry;
if (Error.captureStackTrace && !isStrict) {
Error.captureStackTrace(this, arguments.callee);
} else {
this.stack = (new Error()).stack;
}
}
AuthTokenExpiredError.prototype = Object.create(Error.prototype);
function AuthTokenInvalidError(message) {
this.name = 'AuthTokenInvalidError';
this.message = message;
if (Error.captureStackTrace && !isStrict) {
Error.captureStackTrace(this, arguments.callee);
} else {
this.stack = (new Error()).stack;
}
}
AuthTokenInvalidError.prototype = Object.create(Error.prototype);
function AuthTokenNotBeforeError(message, date) {
this.name = 'AuthTokenNotBeforeError';
this.message = message;
this.date = date;
if (Error.captureStackTrace && !isStrict) {
Error.captureStackTrace(this, arguments.callee);
} else {
this.stack = (new Error()).stack;
}
}
AuthTokenNotBeforeError.prototype = Object.create(Error.prototype);
// For any other auth token error.
function AuthTokenError(message) {
this.name = 'AuthTokenError';
this.message = message;
if (Error.captureStackTrace && !isStrict) {
Error.captureStackTrace(this, arguments.callee);
} else {
this.stack = (new Error()).stack;
}
}
AuthTokenError.prototype = Object.create(Error.prototype);
// For any other auth error; not specifically related to the auth token itself.
function AuthError(message) {
this.name = 'AuthError';
this.message = message;
if (Error.captureStackTrace && !isStrict) {
Error.captureStackTrace(this, arguments.callee);
} else {
this.stack = (new Error()).stack;
}
}
AuthError.prototype = Object.create(Error.prototype);
function SilentMiddlewareBlockedError(message, type) {
this.name = 'SilentMiddlewareBlockedError';
this.message = message;
this.type = type;
if (Error.captureStackTrace && !isStrict) {
Error.captureStackTrace(this, arguments.callee);
} else {
this.stack = (new Error()).stack;
}
}
SilentMiddlewareBlockedError.prototype = Object.create(Error.prototype);
function InvalidActionError(message) {
this.name = 'InvalidActionError';
this.message = message;
if (Error.captureStackTrace && !isStrict) {
Error.captureStackTrace(this, arguments.callee);
} else {
this.stack = (new Error()).stack;
}
}
InvalidActionError.prototype = Object.create(Error.prototype);
function InvalidArgumentsError(message) {
this.name = 'InvalidArgumentsError';
this.message = message;
if (Error.captureStackTrace && !isStrict) {
Error.captureStackTrace(this, arguments.callee);
} else {
this.stack = (new Error()).stack;
}
}
InvalidArgumentsError.prototype = Object.create(Error.prototype);
function InvalidOptionsError(message) {
this.name = 'InvalidOptionsError';
this.message = message;
if (Error.captureStackTrace && !isStrict) {
Error.captureStackTrace(this, arguments.callee);
} else {
this.stack = (new Error()).stack;
}
}
InvalidOptionsError.prototype = Object.create(Error.prototype);
function InvalidMessageError(message) {
this.name = 'InvalidMessageError';
this.message = message;
if (Error.captureStackTrace && !isStrict) {
Error.captureStackTrace(this, arguments.callee);
} else {
this.stack = (new Error()).stack;
}
}
InvalidMessageError.prototype = Object.create(Error.prototype);
function SocketProtocolError(message, code) {
this.name = 'SocketProtocolError';
this.message = message;
this.code = code;
if (Error.captureStackTrace && !isStrict) {
Error.captureStackTrace(this, arguments.callee);
} else {
this.stack = (new Error()).stack;
}
}
SocketProtocolError.prototype = Object.create(Error.prototype);
function ServerProtocolError(message) {
this.name = 'ServerProtocolError';
this.message = message;
if (Error.captureStackTrace && !isStrict) {
Error.captureStackTrace(this, arguments.callee);
} else {
this.stack = (new Error()).stack;
}
}
ServerProtocolError.prototype = Object.create(Error.prototype);
function HTTPServerError(message) {
this.name = 'HTTPServerError';
this.message = message;
if (Error.captureStackTrace && !isStrict) {
Error.captureStackTrace(this, arguments.callee);
} else {
this.stack = (new Error()).stack;
}
}
HTTPServerError.prototype = Object.create(Error.prototype);
function ResourceLimitError(message) {
this.name = 'ResourceLimitError';
this.message = message;
if (Error.captureStackTrace && !isStrict) {
Error.captureStackTrace(this, arguments.callee);
} else {
this.stack = (new Error()).stack;
}
}
ResourceLimitError.prototype = Object.create(Error.prototype);
function TimeoutError(message) {
this.name = 'TimeoutError';
this.message = message;
if (Error.captureStackTrace && !isStrict) {
Error.captureStackTrace(this, arguments.callee);
} else {
this.stack = (new Error()).stack;
}
}
TimeoutError.prototype = Object.create(Error.prototype);
function BadConnectionError(message, type) {
this.name = 'BadConnectionError';
this.message = message;
this.type = type;
if (Error.captureStackTrace && !isStrict) {
Error.captureStackTrace(this, arguments.callee);
} else {
this.stack = (new Error()).stack;
}
}
BadConnectionError.prototype = Object.create(Error.prototype);
function BrokerError(message) {
this.name = 'BrokerError';
this.message = message;
if (Error.captureStackTrace && !isStrict) {
Error.captureStackTrace(this, arguments.callee);
} else {
this.stack = (new Error()).stack;
}
}
BrokerError.prototype = Object.create(Error.prototype);
function ProcessExitError(message, code) {
this.name = 'ProcessExitError';
this.message = message;
this.code = code;
if (Error.captureStackTrace && !isStrict) {
Error.captureStackTrace(this, arguments.callee);
} else {
this.stack = (new Error()).stack;
}
}
ProcessExitError.prototype = Object.create(Error.prototype);
function UnknownError(message) {
this.name = 'UnknownError';
this.message = message;
if (Error.captureStackTrace && !isStrict) {
Error.captureStackTrace(this, arguments.callee);
} else {
this.stack = (new Error()).stack;
}
}
UnknownError.prototype = Object.create(Error.prototype);
// Expose all error types.
module.exports = {
AuthTokenExpiredError: AuthTokenExpiredError,
AuthTokenInvalidError: AuthTokenInvalidError,
AuthTokenNotBeforeError: AuthTokenNotBeforeError,
AuthTokenError: AuthTokenError,
AuthError: AuthError,
SilentMiddlewareBlockedError: SilentMiddlewareBlockedError,
InvalidActionError: InvalidActionError,
InvalidArgumentsError: InvalidArgumentsError,
InvalidOptionsError: InvalidOptionsError,
InvalidMessageError: InvalidMessageError,
SocketProtocolError: SocketProtocolError,
ServerProtocolError: ServerProtocolError,
HTTPServerError: HTTPServerError,
ResourceLimitError: ResourceLimitError,
TimeoutError: TimeoutError,
BadConnectionError: BadConnectionError,
BrokerError: BrokerError,
ProcessExitError: ProcessExitError,
UnknownError: UnknownError
};
module.exports.socketProtocolErrorStatuses = {
1001: 'Socket was disconnected',
1002: 'A WebSocket protocol error was encountered',
1003: 'Server terminated socket because it received invalid data',
1005: 'Socket closed without status code',
1006: 'Socket hung up',
1007: 'Message format was incorrect',
1008: 'Encountered a policy violation',
1009: 'Message was too big to process',
1010: 'Client ended the connection because the server did not comply with extension requirements',
1011: 'Server encountered an unexpected fatal condition',
4000: 'Server ping timed out',
4001: 'Client pong timed out',
4002: 'Server failed to sign auth token',
4003: 'Failed to complete handshake',
4004: 'Client failed to save auth token',
4005: 'Did not receive #handshake from client before timeout',
4006: 'Failed to bind socket to message broker',
4007: 'Client connection establishment timed out',
4008: 'Server rejected handshake from client',
4009: 'Server received a message before the client handshake'
};
module.exports.socketProtocolIgnoreStatuses = {
1000: 'Socket closed normally',
1001: 'Socket hung up'
};
// Properties related to error domains cannot be serialized.
var unserializableErrorProperties = {
domain: 1,
domainEmitter: 1,
domainThrown: 1
};
// Convert an error into a JSON-compatible type which can later be hydrated
// back to its *original* form.
module.exports.dehydrateError = function dehydrateError(error, includeStackTrace) {
var dehydratedError;
if (error && typeof error === 'object') {
dehydratedError = {
message: error.message
};
if (includeStackTrace) {
dehydratedError.stack = error.stack;
}
for (var i in error) {
if (!unserializableErrorProperties[i]) {
dehydratedError[i] = error[i];
}
}
} else if (typeof error === 'function') {
dehydratedError = '[function ' + (error.name || 'anonymous') + ']';
} else {
dehydratedError = error;
}
return decycle(dehydratedError);
};
// Convert a dehydrated error back to its *original* form.
module.exports.hydrateError = function hydrateError(error) {
var hydratedError = null;
if (error != null) {
if (typeof error === 'object') {
hydratedError = new Error(error.message);
for (var i in error) {
if (error.hasOwnProperty(i)) {
hydratedError[i] = error[i];
}
}
} else {
hydratedError = error;
}
}
return hydratedError;
};
module.exports.decycle = decycle;
},{"./decycle":24}],26:[function(require,module,exports){
(function (global){
var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var validJSONStartRegex = /^[ \n\r\t]*[{\[]/;
var arrayBufferToBase64 = function (arraybuffer) {
var bytes = new Uint8Array(arraybuffer);
var len = bytes.length;
var base64 = '';
for (var i = 0; i < len; i += 3) {
base64 += base64Chars[bytes[i] >> 2];
base64 += base64Chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64 += base64Chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64 += base64Chars[bytes[i + 2] & 63];
}
if ((len % 3) === 2) {
base64 = base64.substring(0, base64.length - 1) + '=';
} else if (len % 3 === 1) {
base64 = base64.substring(0, base64.length - 2) + '==';
}
return base64;
};
var binaryToBase64Replacer = function (key, value) {
if (global.ArrayBuffer && value instanceof global.ArrayBuffer) {
return {
base64: true,
data: arrayBufferToBase64(value)
};
} else if (global.Buffer) {
if (value instanceof global.Buffer){
return {
base64: true,
data: value.toString('base64')
};
}
// Some versions of Node.js convert Buffers to Objects before they are passed to
// the replacer function - Because of this, we need to rehydrate Buffers
// before we can convert them to base64 strings.
if (value && value.type === 'Buffer' && Array.isArray(value.data)) {
var rehydratedBuffer;
if (global.Buffer.from) {
rehydratedBuffer = global.Buffer.from(value.data);
} else {
rehydratedBuffer = new global.Buffer(value.data);
}
return {
base64: true,
data: rehydratedBuffer.toString('base64')
};
}
}
return value;
};
// Decode the data which was transmitted over the wire to a JavaScript Object in a format which SC understands.
// See encode function below for more details.
module.exports.decode = function (input) {
if (input == null) {
return null;
}
// Leave ping or pong message as is
if (input === '#1' || input === '#2') {
return input;
}
var message = input.toString();
// Performance optimization to detect invalid JSON packet sooner.
if (!validJSONStartRegex.test(message)) {
return message;
}
try {
return JSON.parse(message);
} catch (err) {}
return message;
};
// Encode a raw JavaScript object (which is in the SC protocol format) into a format for
// transfering it over the wire. In this case, we just convert it into a simple JSON string.
// If you want to create your own custom codec, you can encode the object into any format
// (e.g. binary ArrayBuffer or string with any kind of compression) so long as your decode
// function is able to rehydrate that object back into its original JavaScript Object format
// (which adheres to the SC protocol).
// See https://github.com/SocketCluster/socketcluster/blob/master/socketcluster-protocol.md
// for details about the SC protocol.
module.exports.encode = function (object) {
// Leave ping or pong message as is
if (object === '#1' || object === '#2') {
return object;
}
return JSON.stringify(object, binaryToBase64Replacer);
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],27:[function(require,module,exports){
(function (Buffer){
/*!
* shallow-clone <https://github.com/jonschlinkert/shallow-clone>
*
* Copyright (c) 2015-present, Jon Schlinkert.
* Released under the MIT License.
*/
'use strict';
const valueOf = Symbol.prototype.valueOf;
const typeOf = require('kind-of');
function clone(val, deep) {
switch (typeOf(val)) {
case 'array':
return val.slice();
case 'object':
return Object.assign({}, val);
case 'date':
return new val.constructor(Number(val));
case 'map':
return new Map(val);
case 'set':
return new Set(val);
case 'buffer':
return cloneBuffer(val);
case 'symbol':
return cloneSymbol(val);
case 'arraybuffer':
return cloneArrayBuffer(val);
case 'float32array':
case 'float64array':
case 'int16array':
case 'int32array':
case 'int8array':
case 'uint16array':
case 'uint32array':
case 'uint8clampedarray':
case 'uint8array':
return cloneTypedArray(val);
case 'regexp':
return cloneRegExp(val);
case 'error':
return Object.create(val);
default: {
return val;
}
}
}
function cloneRegExp(val) {
const flags = val.flags !== void 0 ? val.flags : (/\w+$/.exec(val) || void 0);
const re = new val.constructor(val.source, flags);
re.lastIndex = val.lastIndex;
return re;
}
function cloneArrayBuffer(val) {
const res = new val.constructor(val.byteLength);
new Uint8Array(res).set(new Uint8Array(val));
return res;
}
function cloneTypedArray(val, deep) {
return new val.constructor(val.buffer, val.byteOffset, val.length);
}
function cloneBuffer(val) {
const len = val.length;
const buf = Buffer.allocUnsafe ? Buffer.allocUnsafe(len) : Buffer.from(len);
val.copy(buf);
return buf;
}
function cloneSymbol(val) {
return valueOf ? Object(valueOf.call(val)) : {};
}
/**
* Expose `clone`
*/
module.exports = clone;
}).call(this,require("buffer").Buffer)
},{"buffer":11,"kind-of":18}],28:[function(require,module,exports){
const ConsumableStream = require('consumable-stream');
class DemuxedConsumableStream extends ConsumableStream {
constructor(streamDemux, name) {
super();
this.name = name;
this._streamDemux = streamDemux;
}
createConsumer(timeout) {
return this._streamDemux.createConsumer(this.name, timeout);
}
}
module.exports = DemuxedConsumableStream;
},{"consumable-stream":14}],29:[function(require,module,exports){
const WritableConsumableStream = require('writable-consumable-stream');
const DemuxedConsumableStream = require('./demuxed-consumable-stream');
class StreamDemux {
constructor() {
this._mainStream = new WritableConsumableStream();
}
write(streamName, value) {
this._mainStream.write({
stream: streamName,
data: {
value,
done: false
}
});
}
close(streamName, value) {
this._mainStream.write({
stream: streamName,
data: {
value,
done: true
}
});
}
closeAll(value) {
this._mainStream.close(value);
}
writeToConsumer(consumerId, value) {
this._mainStream.writeToConsumer(consumerId, {
consumerId,
data: {
value,
done: false
}
});
}
closeConsumer(consumerId, value) {
this._mainStream.closeConsumer(consumerId, {
consumerId,
data: {
value,
done: true
}
});
}
getConsumerStats(consumerId) {
return this._mainStream.getConsumerStats(consumerId);
}
getConsumerStatsList(streamName) {
let consumerList = this._mainStream.getConsumerStatsList();
return consumerList.filter((consumerStats) => {
return consumerStats.stream === streamName;
});
}
getConsumerStatsListAll() {
return this._mainStream.getConsumerStatsList();
}
kill(streamName, value) {
let consumerList = this.getConsumerStatsList(streamName);
let len = consumerList.length;
for (let i = 0; i < len; i++) {
this.killConsumer(consumerList[i].id, value);
}
}
killAll(value) {
this._mainStream.kill(value);
}
killConsumer(consumerId, value) {
this._mainStream.killConsumer(consumerId, value);
}
getBackpressure(streamName) {
let consumerList = this.getConsumerStatsList(streamName);
let len = consumerList.length;
let maxBackpressure = 0;
for (let i = 0; i < len; i++) {
let consumer = consumerList[i];
if (consumer.backpressure > maxBackpressure) {
maxBackpressure = consumer.backpressure;
}
}
return maxBackpressure;
}
getBackpressureAll() {
return this._mainStream.getBackpressure();
}
getConsumerBackpressure(consumerId) {
return this._mainStream.getConsumerBackpressure(consumerId);
}
hasConsumer(streamName, consumerId) {
let consumerStats = this._mainStream.getConsumerStats(consumerId);
return !!consumerStats && consumerStats.stream === streamName;
}
hasConsumerAll(consumerId) {
return this._mainStream.hasConsumer(consumerId);
}
createConsumer(streamName, timeout) {
let mainStreamConsumer = this._mainStream.createConsumer(timeout);
let consumerNext = mainStreamConsumer.next;
mainStreamConsumer.next = async function () {
while (true) {
let packet = await consumerNext.apply(this, arguments);
if (packet.value) {
if (
packet.value.stream === streamName ||
packet.value.consumerId === this.id
) {
if (packet.value.data.done) {
this.return();
}
return packet.value.data;
}
}
if (packet.done) {
return packet;
}
}
};
let consumerGetStats = mainStreamConsumer.getStats;
mainStreamConsumer.getStats = function () {
let stats = consumerGetStats.apply(this, arguments);
stats.stream = streamName;
return stats;
};
let consumerApplyBackpressure = mainStreamConsumer.applyBackpressure;
mainStreamConsumer.applyBackpressure = function (packet) {
if (packet.value) {
if (
packet.value.stream === streamName ||
packet.value.consumerId === this.id
) {
consumerApplyBackpressure.apply(this, arguments);
return;
}
}
if (packet.done) {
consumerApplyBackpressure.apply(this, arguments);
}
};
let consumerReleaseBackpressure = mainStreamConsumer.releaseBackpressure;
mainStreamConsumer.releaseBackpressure = function (packet) {
if (packet.value) {
if (
packet.value.stream === streamName ||
packet.value.consumerId === this.id
) {
consumerReleaseBackpressure.apply(this, arguments);
return;
}
}
if (packet.done) {
consumerReleaseBackpressure.apply(this, arguments);
}
};
return mainStreamConsumer;
}
stream(streamName) {
return new DemuxedConsumableStream(this, streamName);
}
}
module.exports = StreamDemux;
},{"./demuxed-consumable-stream":28,"writable-consumable-stream":36}],30:[function(require,module,exports){
var v1 = require('./v1');
var v4 = require('./v4');
var uuid = v4;
uuid.v1 = v1;
uuid.v4 = v4;
module.exports = uuid;
},{"./v1":33,"./v4":34}],31:[function(require,module,exports){
/**
* Convert array of 16 byte values to UUID string format of the form:
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
*/
var byteToHex = [];
for (var i = 0; i < 256; ++i) {
byteToHex[i] = (i + 0x100).toString(16).substr(1);
}
function bytesToUuid(buf, offset) {
var i = offset || 0;
var bth = byteToHex;
// join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
return ([
bth[buf[i++]], bth[buf[i++]],
bth[buf[i++]], bth[buf[i++]], '-',
bth[buf[i++]], bth[buf[i++]], '-',
bth[buf[i++]], bth[buf[i++]], '-',
bth[buf[i++]], bth[buf[i++]], '-',
bth[buf[i++]], bth[buf[i++]],
bth[buf[i++]], bth[buf[i++]],
bth[buf[i++]], bth[buf[i++]]
]).join('');
}
module.exports = bytesToUuid;
},{}],32:[function(require,module,exports){
// Unique ID creation requires a high quality random # generator. In the
// browser this is a little complicated due to unknown quality of Math.random()
// and inconsistent support for the `crypto` API. We do the best we can via
// feature-detection
// getRandomValues needs to be invoked in a context where "this" is a Crypto
// implementation. Also, find the complete implementation of crypto on IE11.
var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
(typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
if (getRandomValues) {
// WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
module.exports = function whatwgRNG() {
getRandomValues(rnds8);
return rnds8;
};
} else {
// Math.random()-based (RNG)
//
// If all else fails, use Math.random(). It's fast, but is of unspecified
// quality.
var rnds = new Array(16);
module.exports = function mathRNG() {
for (var i = 0, r; i < 16; i++) {
if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
}
return rnds;
};
}
},{}],33:[function(require,module,exports){
var rng = require('./lib/rng');
var bytesToUuid = require('./lib/bytesToUuid');
// **`v1()` - Generate time-based UUID**
//
// Inspired by https://github.com/LiosK/UUID.js
// and http://docs.python.org/library/uuid.html
var _nodeId;
var _clockseq;
// Previous uuid creation time
var _lastMSecs = 0;
var _lastNSecs = 0;
// See https://github.com/uuidjs/uuid for API details
function v1(options, buf, offset) {
var i = buf && offset || 0;
var b = buf || [];
options = options || {};
var node = options.node || _nodeId;
var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
// node and clockseq need to be initialized to random values if they're not
// specified. We do this lazily to minimize issues related to insufficient
// system entropy. See #189
if (node == null || clockseq == null) {
var seedBytes = rng();
if (node == null) {
// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
node = _nodeId = [
seedBytes[0] | 0x01,
seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
];
}
if (clockseq == null) {
// Per 4.2.2, randomize (14 bit) clockseq
clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
}
}
// UUID timestamps are 100 nano-second units since the Gregorian epoch,
// (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
// time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
// (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
// Per 4.2.1.2, use count of uuid's generated during the current clock
// cycle to simulate higher resolution clock
var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
// Time since last uuid creation (in msecs)
var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
// Per 4.2.1.2, Bump clockseq on clock regression
if (dt < 0 && options.clockseq === undefined) {
clockseq = clockseq + 1 & 0x3fff;
}
// Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
// time interval
if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
nsecs = 0;
}
// Per 4.2.1.2 Throw error if too many uuids are requested
if (nsecs >= 10000) {
throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
}
_lastMSecs = msecs;
_lastNSecs = nsecs;
_clockseq = clockseq;
// Per 4.1.4 - Convert from unix epoch to Gregorian epoch
msecs += 12219292800000;
// `time_low`
var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
b[i++] = tl >>> 24 & 0xff;
b[i++] = tl >>> 16 & 0xff;
b[i++] = tl >>> 8 & 0xff;
b[i++] = tl & 0xff;
// `time_mid`
var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
b[i++] = tmh >>> 8 & 0xff;
b[i++] = tmh & 0xff;
// `time_high_and_version`
b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
b[i++] = tmh >>> 16 & 0xff;
// `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
b[i++] = clockseq >>> 8 | 0x80;
// `clock_seq_low`
b[i++] = clockseq & 0xff;
// `node`
for (var n = 0; n < 6; ++n) {
b[i + n] = node[n];
}
return buf ? buf : bytesToUuid(b);
}
module.exports = v1;
},{"./lib/bytesToUuid":31,"./lib/rng":32}],34:[function(require,module,exports){
var rng = require('./lib/rng');
var bytesToUuid = require('./lib/bytesToUuid');
function v4(options, buf, offset) {
var i = buf && offset || 0;
if (typeof(options) == 'string') {
buf = options === 'binary' ? new Array(16) : null;
options = null;
}
options = options || {};
var rnds = options.random || (options.rng || rng)();
// Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[6] = (rnds[6] & 0x0f) | 0x40;
rnds[8] = (rnds[8] & 0x3f) | 0x80;
// Copy bytes to buffer, if provided
if (buf) {
for (var ii = 0; ii < 16; ++ii) {
buf[i + ii] = rnds[ii];
}
}
return buf || bytesToUuid(rnds);
}
module.exports = v4;
},{"./lib/bytesToUuid":31,"./lib/rng":32}],35:[function(require,module,exports){
class Consumer {
constructor(stream, id, startNode, timeout) {
this.id = id;
this._backpressure = 0;
this.stream = stream;
this.currentNode = startNode;
this.timeout = timeout;
this.isAlive = true;
this.stream.setConsumer(this.id, this);
}
getStats() {
let stats = {
id: this.id,
backpressure: this._backpressure
};
if (this.timeout != null) {
stats.timeout = this.timeout;
}
return stats;
}
_resetBackpressure() {
this._backpressure = 0;
}
applyBackpressure(packet) {
this._backpressure++;
}
releaseBackpressure(packet) {
this._backpressure--;
}
getBackpressure() {
return this._backpressure;
}
write(packet) {
if (this._timeoutId !== undefined) {
clearTimeout(this._timeoutId);
delete this._timeoutId;
}
this.applyBackpressure(packet);
if (this._resolve) {
this._resolve();
delete this._resolve;
}
}
kill(value) {
if (this._timeoutId !== undefined) {
clearTimeout(this._timeoutId);
delete this._timeoutId;
}
this._killPacket = {value, done: true};
this._destroy();
if (this._resolve) {
this._resolve();
delete this._resolve;
}
}
_destroy() {
this.isAlive = false;
this._resetBackpressure();
this.stream.removeConsumer(this.id);
}
async _waitForNextItem(timeout) {
return new Promise((resolve, reject) => {
this._resolve = resolve;
let timeoutId;
if (timeout !== undefined) {
// Create the error object in the outer scope in order
// to get the full stack trace.
let error = new Error('Stream consumer iteration timed out');
(async () => {
let delay = wait(timeout);
timeoutId = delay.timeoutId;
await delay.promise;
error.name = 'TimeoutError';
delete this._resolve;
reject(error);
})();
}
this._timeoutId = timeoutId;
});
}
async next() {
this.stream.setConsumer(this.id, this);
while (true) {
if (!this.currentNode.next) {
try {
await this._waitForNextItem(this.timeout);
} catch (error) {
this._destroy();
throw error;
}
}
if (this._killPacket) {
this._destroy();
let killPacket = this._killPacket;
delete this._killPacket;
return killPacket;
}
this.currentNode = this.currentNode.next;
this.releaseBackpressure(this.currentNode.data);
if (this.currentNode.consumerId && this.currentNode.consumerId !== this.id) {
continue;
}
if (this.currentNode.data.done) {
this._destroy();
}
return this.currentNode.data;
}
}
return() {
delete this.currentNode;
this._destroy();
return {};
}
[Symbol.asyncIterator]() {
return this;
}
}
function wait(timeout) {
let timeoutId;
let promise = new Promise((resolve) => {
timeoutId = setTimeout(resolve, timeout);
});
return {timeoutId, promise};
}
module.exports = Consumer;
},{}],36:[function(require,module,exports){
const ConsumableStream = require('consumable-stream');
const Consumer = require('./consumer');
class WritableConsumableStream extends ConsumableStream {
constructor() {
super();
this.nextConsumerId = 1;
this._consumers = {};
// Tail node of a singly linked list.
this._tailNode = {
next: null,
data: {
value: undefined,
done: false
}
};
}
_write(value, done, consumerId) {
let dataNode = {
data: {value, done},
next: null
};
if (consumerId) {
dataNode.consumerId = consumerId;
}
this._tailNode.next = dataNode;
this._tailNode = dataNode;
let consumerList = Object.values(this._consumers);
let len = consumerList.length;
for (let i = 0; i < len; i++) {
let consumer = consumerList[i];
consumer.write(dataNode.data);
}
}
write(value) {
this._write(value, false);
}
close(value) {
this._write(value, true);
}
writeToConsumer(consumerId, value) {
this._write(value, false, consumerId);
}
closeConsumer(consumerId, value) {
this._write(value, true, consumerId);
}
kill(value) {
let consumerIdList = Object.keys(this._consumers);
let len = consumerIdList.length;
for (let i = 0; i < len; i++) {
this.killConsumer(consumerIdList[i], value);
}
}
killConsumer(consumerId, value) {
let consumer = this._consumers[consumerId];
if (!consumer) {
return;
}
consumer.kill(value);
}
getBackpressure() {
let consumerList = Object.values(this._consumers);
let len = consumerList.length;
let maxBackpressure = 0;
for (let i = 0; i < len; i++) {
let consumer = consumerList[i];
let backpressure = consumer.getBackpressure();
if (backpressure > maxBackpressure) {
maxBackpressure = backpressure;
}
}
return maxBackpressure;
}
getConsumerBackpressure(consumerId) {
let consumer = this._consumers[consumerId];
if (consumer) {
return consumer.getBackpressure();
}
return 0;
}
hasConsumer(consumerId) {
return !!this._consumers[consumerId];
}
setConsumer(consumerId, consumer) {
this._consumers[consumerId] = consumer;
if (!consumer.currentNode) {
consumer.currentNode = this._tailNode;
}
}
removeConsumer(consumerId) {
delete this._consumers[consumerId];
}
getConsumerStats(consumerId) {
let consumer = this._consumers[consumerId];
if (consumer) {
return consumer.getStats();
}
return undefined;
}
getConsumerStatsList() {
let consumerStats = [];
let consumerList = Object.values(this._consumers);
let len = consumerList.length;
for (let i = 0; i < len; i++) {
let consumer = consumerList[i];
consumerStats.push(consumer.getStats());
}
return consumerStats;
}
createConsumer(timeout) {
return new Consumer(this, this.nextConsumerId++, this._tailNode, timeout);
}
}
module.exports = WritableConsumableStream;
},{"./consumer":35,"consumable-stream":14}],"socketcluster-client":[function(require,module,exports){
const AGClientSocket = require('./lib/clientsocket');
const factory = require('./lib/factory');
const version = '16.0.2';
module.exports.factory = factory;
module.exports.AGClientSocket = AGClientSocket;
module.exports.create = function (options) {
return factory.create({...options, version});
};
module.exports.version = version;
},{"./lib/clientsocket":2,"./lib/factory":3}]},{},["socketcluster-client"])("socketcluster-client")
});
|
;(function(angular){
var app = angular.module('app');
app.directive('focus', function(){
return {
restrict: 'EA' ,
link: function(scope, element , attr){
element.on('click', function(){
element.parent().children().attr('class','');
element.addClass('active');
})
}
}
})
})(angular)
|
$(document).ready(function(){
//toggler btn
$('.navbar-toggler').click(function(){
$('.navbar-toggler').toggleClass('change')
})
//sticky navbar
$(window).scroll(function(){
let position = $(this).scrollTop();
// 718
if(position>= 600){
$('.navbar').addClass('navbar-background');
$('.navbar').addClass('fixed-top');
}else{
$('.navbar').removeClass('navbar-background');
$('.navbar').removeClass('fixed-top');
}
})
//smooth scroll
$('.nav-item a, .header-link, #back-to-top').click(function(link){
link.preventDefault();
let target = $(this).attr('href');
$('html, body').stop().animate({
scrollTop: $(target).offset().top-25
},3000);
})
//back-to-top
$(window).scroll(function(){
let position = $(this).scrollTop();
if(position >= 208){
$('#back-to-top').removeClass('scrollTop');
}else{
$('#back-to-top').addClass('scrollTop');
}
})
// ripple
$("#header,.info").ripples({
resolution: 128,
dropRadius: 10, //px
perturbance: 0.04,
interactive:false
});
setInterval(function() {
var $el = $('#header,.info');
var x = Math.random() * $el.outerWidth();
var y = Math.random() * $el.outerHeight();
var dropRadius = 20;
var strength = 0.04 + Math.random() * 0.04;
$el.ripples('drop', x, y, dropRadius, strength);
}, 4000);
//magnific popup
$('.parent-container').magnificPopup({
delegate: 'a', // child items selector, by clicking on it popup will open
type: 'image',
gallery: {
enabled: true
}
// other options
});
});
|
const find = require('lodash/find')
const extend = require('lodash/extend')
const includes = require('lodash/includes')
// For IE 11
if(typeof Promise === 'undefined'){
global.Promise = require('promise-polyfill')
}
global.Exception = class Exception extends Error {
constructor(message){
super(message);
this.message = message;
this.name = 'Exception';
}
}
/**
* Returns a numeric hash of a string
* @returns {number}
*/
String.prototype.hashCode = function(){
var hash = 0, i, chr, len;
if(this.length === 0) return hash;
for(i = 0, len = this.length; i < len; i++){
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash
}
/**
* Here we add a few ES6 polyfills since we dont want to include whole of babel-polyfill
*/
if(!String.prototype.startsWith){
String.prototype.startsWith = function(searchString, position){
position = position || 0;
return this.substr(position, searchString.length) === searchString;
};
}
if(!Array.prototype.find){
Array.prototype.find = function(predicate){
return find(this, predicate)
};
}
if(!Array.prototype.includes){
Array.prototype.includes = function(searchElement){
return includes(this, searchElement);
};
}
if(typeof Object.assign != 'function'){
Object.assign = extend;
}
if(!String.prototype.includes){
String.prototype.includes = function includes(str){
return this.indexOf(str) !== -1;
};
}
if(!String.prototype.trimLeft){
String.prototype.trimLeft = function trimLeft(str){
return remove(this, `^${str || '\\s'}+`);
};
}
if(!String.prototype.trimRight){
String.prototype.trimRight = function trimRight(str){
return remove(this, `${str || '\\s'}+$`);
};
}
function remove(str, rx){
return str.replace(new RegExp(rx), '');
}
|
//// [tests/cases/compiler/declarationEmitExpressionInExtends6.ts] ////
//// [index.d.ts]
declare const require: any;
//// [a.ts]
export class Foo {}
//// [b.ts]
const { Foo } = require("./a");
export default class extends Foo {}
//// [b.js]
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
exports.__esModule = true;
var Foo = require("./a").Foo;
var default_1 = /** @class */ (function (_super) {
__extends(default_1, _super);
function default_1() {
return _super !== null && _super.apply(this, arguments) || this;
}
return default_1;
}(Foo));
exports["default"] = default_1;
|
import React from 'react'
import { useStaticQuery, graphql } from "gatsby"
import Img from 'gatsby-image'
import './Hero.scss'
//props for text over hero
export default function Hero(props) {
const data = useStaticQuery(graphql`
query {
allContentfulAsset {
edges {
node {
id
title
description
fluid {
src
srcSet
aspectRatio
sizes
}
}
}
}
}
`)
// console.log('edges',data.allContentfulAsset.edges.node.fluid)
return (
<div className='hero-container'>
{
data.allContentfulAsset.edges.map((edge) => {
if (edge.node.title === props.heroImg){
// console.log('edge',edge)
return (
<Img
fluid={edge.node.fluid}
alt={edge.node.description}
key={edge.node.id}/>)
}
return null
})
}
<div className='open-nav-help'>
<p>
Click the icon to open sidebar for <br/> easy navigation through our site!
</p>
</div>
<div className='hero-text'>
<h1 className='hero-header'>
{props.header}
</h1>
<h2 className='hero-subHeader'>
{props.subHeader}
</h2>
</div>
</div>
)
}
|
const semver = require('semver')
const chalk = require('chalk')
module.exports = (version, pkgName) => {
if (!semver.satisfies(process.version, version, { includePrerelease: true })) {
let limit = semver.minVersion(version)
console.log(chalk.red(`
You are using Node ${process.version}, but ${pkgName} need Node Version above ${limit.version}.
Please upgrade your Node version.
`))
process.exit(1)
}
}
|
//# sourceMappingURL=/build/es2019/interfaces/audio-param.js.map
|
/*
* Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
* Copyright [2016-2018] EMBL-European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Ensembl.Panel.Content = Ensembl.Panel.Content.extend({
init: function() {
this.base.apply(this, arguments);
this.blastButtonEnabled = false;
Ensembl.EventManager.register('enableBlastButton', this, this.enableBlastButton);
Ensembl.EventManager.register('runBlastSeq', this, this.runBlastSeq);
},
enableBlastButton: function(seq) {
var panel = this;
if (!this.blastButtonEnabled) {
this.elLk.blastButton = this.el.find('._blast_button').removeClass('modal_link').filter(':not(._blast_no_button)').removeClass('hidden').end().on('click', function(e) {
e.preventDefault();
panel.runBlastSeq();
});
// rel attribute takes precedence over the sequence parsed on page
seq = this.elLk.blastButton.prop('rel') || seq;
if (seq && this.elLk.blastButton.length) {
this.elLk.blastForm = $('<form>').appendTo(document.body).hide()
.attr({action: this.elLk.blastButton.attr('href'), method: 'post'})
.append($.map(Ensembl.coreParams, function(v, n) { return $('<input type="hidden" name="' + n + '" value="' + v + '" />'); }))
.append($('<input type="hidden" name="query_sequence" value="' + this.filterBlastSeq(seq) + '" />'));
this.blastButtonEnabled = true;
}
}
return this.blastButtonEnabled;
},
runBlastSeq: function(seq) {
if (this.elLk.blastForm) {
if (seq) {
this.elLk.blastForm.find('input[name=query_sequence]').val(this.filterBlastSeq(seq));
}
this.elLk.blastForm.submit();
}
},
filterBlastSeq: function(seq) {
return seq.replace(/\[[^\]]+\]/g, '');
}
});
|
const a = Math.random() * 10;
const b = 3;
const c = 5;
const d = a < 3 ? b : c;
if (a < 3) {
console.log('A < 3');
}
const items = new Array(20).fill(0);
for (let i = 0; i < items.length; i++) {
console.log(items[i]);
}
|
export const forEach = (arr, fn) => {
if (!arr.length || !fn) return;
let i = -1;
const len = arr.length;
while (++i < len) {
const item = arr[i];
fn(item, i, arr);
}
};
/**
* @param {Array} arr1
* @param {Array} arr2
* @description 得到两个数组的交集, 两个数组的元素为数值或字符串
*/
export const getIntersection = (arr1, arr2) => {
const len = Math.min(arr1.length, arr2.length);
let i = -1;
const res = [];
while (++i < len) {
const item = arr2[i];
if (arr1.indexOf(item) > -1) res.push(item);
}
return res;
};
/**
* @param {Array} arr1
* @param {Array} arr2
* @description 得到两个数组的并集, 两个数组的元素为数值或字符串
*/
export const getUnion = (arr1, arr2) => {
return Array.from(new Set([...arr1, ...arr2]));
};
/**
* @param {Array} target 目标数组
* @param {Array} arr 需要查询的数组
* @description 判断要查询的数组是否至少有一个元素包含在目标数组中
*/
export const hasOneOf = (targetarr, arr) => {
return targetarr.some(_ => arr.indexOf(_) > -1);
};
/**
* @param {String|Number} value 要验证的字符串或数值
* @param {*} validList 用来验证的列表
*/
export function oneOf(value, validList) {
for (let i = 0; i < validList.length; i++) {
if (value === validList[i]) {
return true;
}
}
return false;
}
/**
* @param {Number} timeStamp 判断时间戳格式是否是毫秒
* @returns {Boolean}
*/
const isMillisecond = timeStamp => {
const timeStr = String(timeStamp);
return timeStr.length > 10;
};
/**
* @param {Number} timeStamp 传入的时间戳
* @param {Number} currentTime 当前时间时间戳
* @returns {Boolean} 传入的时间戳是否早于当前时间戳
*/
const isEarly = (timeStamp, currentTime) => {
return timeStamp < currentTime;
};
/**
* @param {Number} num 数值
* @returns {String} 处理后的字符串
* @description 如果传入的数值小于10,即位数只有1位,则在前面补充0
*/
const getHandledValue = num => {
return num < 10 ? '0' + num : num;
};
/**
* @param {Number} timeStamp 传入的时间戳
* @param {Number} startType 要返回的时间字符串的格式类型,传入'year'则返回年开头的完整时间
*/
const getDate = (timeStamp, startType) => {
const d = new Date(timeStamp * 1000);
const year = d.getFullYear();
const month = getHandledValue(d.getMonth() + 1);
const date = getHandledValue(d.getDate());
const hours = getHandledValue(d.getHours());
const minutes = getHandledValue(d.getMinutes());
const second = getHandledValue(d.getSeconds());
let resStr = '';
if (startType === 'year') resStr = year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + second;
else resStr = month + '-' + date + ' ' + hours + ':' + minutes;
return resStr;
};
/**
* @param {String|Number} timeStamp 时间戳
* @returns {String} 相对时间字符串
*/
export const getRelativeTime = timeStamp => {
// 判断当前传入的时间戳是秒格式还是毫秒
const IS_MILLISECOND = isMillisecond(timeStamp);
// 如果是毫秒格式则转为秒格式
if (IS_MILLISECOND) Math.floor(timeStamp /= 1000);
// 传入的时间戳可以是数值或字符串类型,这里统一转为数值类型
timeStamp = Number(timeStamp);
// 获取当前时间时间戳
const currentTime = Math.floor(Date.parse(new Date()) / 1000);
// 判断传入时间戳是否早于当前时间戳
const IS_EARLY = isEarly(timeStamp, currentTime);
// 获取两个时间戳差值
let diff = currentTime - timeStamp;
// 如果IS_EARLY为false则差值取反
if (!IS_EARLY) diff = -diff;
let resStr = '';
const dirStr = IS_EARLY ? '前' : '后';
// 少于等于59秒
if (diff <= 59) resStr = diff + '秒' + dirStr;
// 多于59秒,少于等于59分钟59秒
else if (diff > 59 && diff <= 3599) resStr = Math.floor(diff / 60) + '分钟' + dirStr;
// 多于59分钟59秒,少于等于23小时59分钟59秒
else if (diff > 3599 && diff <= 86399) resStr = Math.floor(diff / 3600) + '小时' + dirStr;
// 多于23小时59分钟59秒,少于等于29天59分钟59秒
else if (diff > 86399 && diff <= 2623859) resStr = Math.floor(diff / 86400) + '天' + dirStr;
// 多于29天59分钟59秒,少于364天23小时59分钟59秒,且传入的时间戳早于当前
else if (diff > 2623859 && diff <= 31567859 && IS_EARLY) resStr = getDate(timeStamp);
else resStr = getDate(timeStamp, 'year');
return resStr;
};
/**
* @returns {String} 当前浏览器名称
*/
export const getExplorer = () => {
const ua = window.navigator.userAgent;
const isExplorer = (exp) => {
return ua.indexOf(exp) > -1;
};
if (isExplorer('MSIE')) return 'IE';
else if (isExplorer('Firefox')) return 'Firefox';
else if (isExplorer('Chrome')) return 'Chrome';
else if (isExplorer('Opera')) return 'Opera';
else if (isExplorer('Safari')) return 'Safari';
};
/**
* @description 绑定事件 on(element, event, handler)
*/
export const on = (function() {
if (document.addEventListener) {
return function(element, event, handler) {
if (element && event && handler) {
element.addEventListener(event, handler, false);
}
};
} else {
return function(element, event, handler) {
if (element && event && handler) {
element.attachEvent('on' + event, handler);
}
};
}
})();
/**
* @description 解绑事件 off(element, event, handler)
*/
export const off = (function() {
if (document.removeEventListener) {
return function(element, event, handler) {
if (element && event) {
element.removeEventListener(event, handler, false);
}
};
} else {
return function(element, event, handler) {
if (element && event) {
element.detachEvent('on' + event, handler);
}
};
}
})();
/**
* 判断一个对象是否存在key,如果传入第二个参数key,则是判断这个obj对象是否存在key这个属性
* 如果没有传入key这个参数,则判断obj对象是否有键值对
*/
export const hasKey = (obj, key) => {
if (key) return key in obj;
else {
const keysArr = Object.keys(obj);
return keysArr.length;
}
};
/**
* @param {*} obj1 对象
* @param {*} obj2 对象
* @description 判断两个对象是否相等,这两个对象的值只能是数字或字符串
*/
export const objEqual = (obj1, obj2) => {
const keysArr1 = Object.keys(obj1);
const keysArr2 = Object.keys(obj2);
if (keysArr1.length !== keysArr2.length) return false;
else if (keysArr1.length === 0 && keysArr2.length === 0) return true;
/* eslint-disable-next-line */
else return !keysArr1.some(key => obj1[key] != obj2[key])
};
export const dedupe = (array) => {
return Array.from(new Set(array));
};
/**
* @param value string
* @description 过滤特殊字符串,针对输入的部分
*/
export const stripScript = (value) => {
var pattern = new RegExp('[`~!@#$^&*()=|{}\':;\',\\[\\].<>/?~!@#¥……&*()——|{}【】‘;:”“\'。,、?]');
var rs = '';
for (var i = 0; i < value.length; i++) {
rs = rs + value.substr(i, 1).replace(pattern, '');
}
return rs;
}
export const getDateFormat = (date) => {
const month = date.getMonth() + 1;
const day = date.getDate();
const weekday = date.getDay();
let weekdayStr = '';
switch (weekday) {
case 1:
weekdayStr = '周一';
break;
case 2:
weekdayStr = '周二';
break;
case 3:
weekdayStr = '周三';
break;
case 4:
weekdayStr = '周四';
break;
case 5:
weekdayStr = '周五';
break;
case 6:
weekdayStr = '周六';
break;
case 0:
weekdayStr = '周天';
break;
}
return month + '-' + day + ' ' + weekdayStr + ' ';
}
export const getUrlParam = (name) => {
const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
const result = window.location.search.substr(1).match(reg);
return result ? decodeURIComponent(result[2]) : null;
}
|
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
module.exports = `/**
* Welcome to your Workbox-powered service worker!
*
* You'll need to register this file in your web app and you should
* disable HTTP caching for this file too.
* See https://goo.gl/nhQhGp
*
* The rest of the code is auto-generated. Please don't update this file
* directly; instead, make changes to your Workbox build configuration
* and re-run your build process.
* See https://goo.gl/YYPcyY
*/
<% if (importScripts) { %>
importScripts(
<%= importScripts.map(JSON.stringify).join(',\\n ') %>
);
<% } %>
<% if (modulePathPrefix) { %>workbox.setConfig({modulePathPrefix: <%= JSON.stringify(modulePathPrefix) %>});<% } %>
<% if (cacheId) { %>workbox.core.setCacheNameDetails({prefix: <%= JSON.stringify(cacheId) %>});<% } %>
<% if (skipWaiting) { %>workbox.skipWaiting();<% } %>
<% if (clientsClaim) { %>workbox.clientsClaim();<% } %>
<% if (Array.isArray(manifestEntries)) {%>
/**
* The workboxSW.precacheAndRoute() method efficiently caches and responds to
* requests for URLs in the manifest.
* See https://goo.gl/S9QRab
*/
self.__precacheManifest = <%= JSON.stringify(manifestEntries, null, 2) %>.concat(self.__precacheManifest || []);
workbox.precaching.suppressWarnings();
workbox.precaching.precacheAndRoute(self.__precacheManifest, <%= precacheOptionsString %>);
<% } else { %>
if (Array.isArray(self.__precacheManifest)) {
workbox.precaching.suppressWarnings();
workbox.precaching.precacheAndRoute(self.__precacheManifest, <%= precacheOptionsString %>);
}
<% } %>
<% if (navigateFallback) { %>workbox.routing.registerNavigationRoute(<%= JSON.stringify(navigateFallback) %><% if (navigateFallbackWhitelist || navigateFallbackBlacklist) { %>, {
<% if (navigateFallbackWhitelist) { %>whitelist: [<%= navigateFallbackWhitelist %>],<% } %>
<% if (navigateFallbackBlacklist) { %>blacklist: [<%= navigateFallbackBlacklist %>],<% } %>
}<% } %>);<% } %>
<% if (runtimeCaching) { runtimeCaching.forEach(runtimeCachingString => {%><%= runtimeCachingString %><% });} %>`;
|
// This function will be converted into a string so
// the scope is limited to this function only.
// To pass external data use the 'input' function. See other examples.
export function spCode() {
// Put your Shader Park Code here
sphere(.5);
};
|
!function(e){var t={};function n(i){if(t[i])return t[i].exports;var o=t[i]={i:i,l:!1,exports:{}};return e[i].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,i){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(i,o,function(t){return e[t]}.bind(null,o));return i},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=4)}([function(e,t){e.exports=React},function(e,t){e.exports=NetlifyCmsApp},function(e,t){e.exports=function(e){return e&&e.__esModule?e:{default:e}}},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(i){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){n(5),n(6),e.exports=n(11)},function(e,t,n){"use strict";var i=n(2),o=i(n(1)),r=i(n(12));window.___emitter=r.default,window.___loader={enqueue:function(){},hovering:function(){}},o.default.init(),o.default.registerPreviewStyle("cms.css")},function(e,t,n){"use strict";(function(e){var t=n(2)(n(10));window.netlifyIdentity=t.default;var i=function(){return t.default.on("login",(function(){document.location.href="/admin/"}))};t.default.on("init",(function(e){e?t.default.on("logout",(function(){i()})):i()})),e((function(){t.default.init()}))}).call(this,n(7).setImmediate)},function(e,t,n){(function(e){var i=void 0!==e&&e||"undefined"!=typeof self&&self||window,o=Function.prototype.apply;function r(e,t){this._id=e,this._clearFn=t}t.setTimeout=function(){return new r(o.call(setTimeout,i,arguments),clearTimeout)},t.setInterval=function(){return new r(o.call(setInterval,i,arguments),clearInterval)},t.clearTimeout=t.clearInterval=function(e){e&&e.close()},r.prototype.unref=r.prototype.ref=function(){},r.prototype.close=function(){this._clearFn.call(i,this._id)},t.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},t.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},t._unrefActive=t.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout((function(){e._onTimeout&&e._onTimeout()}),t))},n(8),t.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==e&&e.setImmediate||this&&this.setImmediate,t.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==e&&e.clearImmediate||this&&this.clearImmediate}).call(this,n(3))},function(e,t,n){(function(e,t){!function(e,n){"use strict";if(!e.setImmediate){var i,o,r,a,u,c=1,s={},l=!1,f=e.document,d=Object.getPrototypeOf&&Object.getPrototypeOf(e);d=d&&d.setTimeout?d:e,"[object process]"==={}.toString.call(e.process)?i=function(e){t.nextTick((function(){p(e)}))}:!function(){if(e.postMessage&&!e.importScripts){var t=!0,n=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=n,t}}()?e.MessageChannel?((r=new MessageChannel).port1.onmessage=function(e){p(e.data)},i=function(e){r.port2.postMessage(e)}):f&&"onreadystatechange"in f.createElement("script")?(o=f.documentElement,i=function(e){var t=f.createElement("script");t.onreadystatechange=function(){p(e),t.onreadystatechange=null,o.removeChild(t),t=null},o.appendChild(t)}):i=function(e){setTimeout(p,0,e)}:(a="setImmediate$"+Math.random()+"$",u=function(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(a)&&p(+t.data.slice(a.length))},e.addEventListener?e.addEventListener("message",u,!1):e.attachEvent("onmessage",u),i=function(t){e.postMessage(a+t,"*")}),d.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),n=0;n<t.length;n++)t[n]=arguments[n+1];var o={callback:e,args:t};return s[c]=o,i(c),c++},d.clearImmediate=m}function m(e){delete s[e]}function p(e){if(l)setTimeout(p,0,e);else{var t=s[e];if(t){l=!0;try{!function(e){var t=e.callback,n=e.args;switch(n.length){case 0:t();break;case 1:t(n[0]);break;case 2:t(n[0],n[1]);break;case 3:t(n[0],n[1],n[2]);break;default:t.apply(void 0,n)}}(t)}finally{m(e),l=!1}}}}}("undefined"==typeof self?void 0===e?this:e:self)}).call(this,n(3),n(9))},function(e,t){var n,i,o=e.exports={};function r(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function u(e){if(n===setTimeout)return setTimeout(e,0);if((n===r||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:r}catch(e){n=r}try{i="function"==typeof clearTimeout?clearTimeout:a}catch(e){i=a}}();var c,s=[],l=!1,f=-1;function d(){l&&c&&(l=!1,c.length?s=c.concat(s):f=-1,s.length&&m())}function m(){if(!l){var e=u(d);l=!0;for(var t=s.length;t;){for(c=s,s=[];++f<t;)c&&c[f].run();f=-1,t=s.length}c=null,l=!1,function(e){if(i===clearTimeout)return clearTimeout(e);if((i===a||!i)&&clearTimeout)return i=clearTimeout,clearTimeout(e);try{i(e)}catch(t){try{return i.call(null,e)}catch(t){return i.call(this,e)}}}(e)}}function p(e,t){this.fun=e,this.array=t}function h(){}o.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];s.push(new p(e,t)),1!==s.length||l||u(m)},p.prototype.run=function(){this.fun.apply(null,this.array)},o.title="browser",o.browser=!0,o.env={},o.argv=[],o.version="",o.versions={},o.on=h,o.addListener=h,o.once=h,o.off=h,o.removeListener=h,o.removeAllListeners=h,o.emit=h,o.prependListener=h,o.prependOnceListener=h,o.listeners=function(e){return[]},o.binding=function(e){throw new Error("process.binding is not supported")},o.cwd=function(){return"/"},o.chdir=function(e){throw new Error("process.chdir is not supported")},o.umask=function(){return 0}},function(e,t){e.exports=netlifyIdentity},function(e,t,n){"use strict";n.r(t);var i=n(1),o=n.n(i),r=n(0),a=n.n(r),u=function(e){var t=e.entry,n=(0,e.widgetFor)("body"),i=t.getIn(["data","title"]);return a.a.createElement("div",{className:"page"},a.a.createElement("h1",{className:"page__title"},i),a.a.createElement("div",{className:"page__body"},n))},c=function(e){var t=e.entry,n=(0,e.widgetFor)("body"),i=t.getIn(["data","title"]);return a.a.createElement("div",{className:"post"},a.a.createElement("h1",{className:"post__title"},i),a.a.createElement("div",{className:"post__body"},n))};o.a.registerPreviewTemplate("pages",u),o.a.registerPreviewTemplate("posts",c)},function(e,t,n){"use strict";n.r(t);const i=function(e){return e=e||Object.create(null),{on:function(t,n){(e[t]||(e[t]=[])).push(n)},off:function(t,n){e[t]&&e[t].splice(e[t].indexOf(n)>>>0,1)},emit:function(t,n){(e[t]||[]).slice().map((function(e){e(n)})),(e["*"]||[]).slice().map((function(e){e(t,n)}))}}}();t.default=i}]);
//# sourceMappingURL=cms.js.map
|
sap.ui.define(["sap/ui/webc/common/thirdparty/base/asset-registries/Icons"],function(t){"use strict";const q="attachment-audio";const s="M160 320q-15 0-22-5t-9-11q-3-7-1-16v-32q-2-9 1-16 2-6 9-11t22-5h27q5 0 10-3l97-74q4-3 10-3t11 4.5 5 11.5v224q0 8-5 12t-11 4-10-3l-97-74q-5-3-10-3h-27zm0-32h27q16 0 29 10l72 54V192l-72 55q-12 9-29 9h-27v32zm192 160h32v32q0 14-9 23t-23 9H32q-14 0-23-9t-9-23V128L128 0h224q13 0 22.5 9t9.5 23v32h-32V32H160v96q0 14-9.5 23t-23.5 9H32v320h320v-32zm26-259q17 15 27.5 36.5T416 272q0 24-9.5 45T381 353l-27-20q14-11 22-26.5t8-34.5q0-20-9-36t-23-27v-1zm78-59q26 28 41 64t15 78q0 40-14 75.5T459 410l-26-19q22-23 34.5-53.5T480 272q0-36-13.5-67.5T430 150z";const a=false;const c="SAP-icons";const e="@ui5/webcomponents-icons";t.registerIcon(q,{pathData:s,ltr:a,collection:c,packageName:e});var n={pathData:s};return n});
|
/**
* Emerging Citizens
*
* GameGameUser Model
* @module tweet
* @class tweet
* @author Johnny Richardson
*
* For field docs: http://keystonejs.com/docs/database/
*
* ==========
*/
var keystone = require('keystone');
var Types = keystone.Field.Types;
/**
* GameUser Model
* ==========
*/
var GameUser = new keystone.List('GameUser');
GameUser.add({
name: { type: String, required: true, index: true }
});
/**
* Registration
*/
GameUser.defaultColumns = 'name';
GameUser.register();
|
// @flow
import type {
lf$Transaction,
} from 'lovefield';
import {
asDisplayCutoff,
asGetAllUtxos,
asGetAllAccounting,
asHasLevels,
} from '../models/PublicDeriver/traits';
import type {
IPublicDeriver,
Address, AddressType, Value, Addressing, UsedStatus,
} from '../models/PublicDeriver/interfaces';
import { ConceptualWallet } from '../models/ConceptualWallet/index';
import {
getAllSchemaTables,
raii,
mapToTables,
} from '../database/utils';
import {
GetAddress,
GetPathWithSpecific,
GetToken,
AssociateToken,
} from '../database/primitives/api/read';
import type {
AddressRow,
TokenRow,
TokenListRow,
} from '../database/primitives/tables';
import type {
CoreAddressT
} from '../database/primitives/enums';
import {
GetDerivationSpecific,
} from '../database/walletTypes/common/api/read';
import {
GetUtxoTxOutputsWithTx,
} from '../database/transactionModels/utxo/api/read';
import {
rawGetAddressesForDisplay,
} from '../models/utils';
export async function rawGetAllAddressesForDisplay(
tx: lf$Transaction,
deps: {|
GetUtxoTxOutputsWithTx: Class<GetUtxoTxOutputsWithTx>,
GetAddress: Class<GetAddress>,
GetPathWithSpecific: Class<GetPathWithSpecific>,
GetDerivationSpecific: Class<GetDerivationSpecific>,
|},
request: {|
publicDeriver: IPublicDeriver<>,
type: CoreAddressT,
|},
derivationTables: Map<number, string>,
): Promise<Array<{| ...Address, ...AddressType, ...Value, ...Addressing, ...UsedStatus |}>> {
const withUtxos = asGetAllUtxos(request.publicDeriver);
let utxoAddresses = withUtxos != null
? await withUtxos.rawGetAllUtxoAddresses(
tx,
{
GetAddress: deps.GetAddress,
GetPathWithSpecific: deps.GetPathWithSpecific,
GetDerivationSpecific: deps.GetDerivationSpecific,
},
undefined,
derivationTables,
)
: [];
const withAccounting = asGetAllAccounting(request.publicDeriver);
const accountingAddresses = withAccounting != null
? await withAccounting.rawGetAllAccountingAddresses(
tx,
{
GetPathWithSpecific: deps.GetPathWithSpecific,
GetAddress: deps.GetAddress,
GetDerivationSpecific: deps.GetDerivationSpecific,
},
undefined,
derivationTables,
)
: [];
// when public deriver level = chain we still have a display cutoff
const hasCutoff = asDisplayCutoff(request.publicDeriver);
if (hasCutoff != null) {
const cutoff = await hasCutoff.rawGetCutoff(
tx,
{
GetPathWithSpecific: deps.GetPathWithSpecific,
GetDerivationSpecific: deps.GetDerivationSpecific,
},
undefined,
derivationTables,
);
utxoAddresses = utxoAddresses.filter(address => (
address.addressing.path[address.addressing.path.length - 1] <= cutoff
));
}
const addresses = [
...utxoAddresses,
...accountingAddresses,
];
return await rawGetAddressesForDisplay(
request.publicDeriver.getDb(), tx,
{ GetUtxoTxOutputsWithTx: deps.GetUtxoTxOutputsWithTx },
{
addresses,
type: request.type,
networkId: request.publicDeriver.getParent().getNetworkInfo().NetworkId,
defaultToken: request.publicDeriver.getParent().getDefaultToken(),
},
);
}
export async function getAllAddressesForDisplay(
request: {|
publicDeriver: IPublicDeriver<ConceptualWallet>,
type: CoreAddressT,
|},
): Promise<Array<{| ...Address, ...AddressType, ...Value, ...Addressing, ...UsedStatus |}>> {
const withLevels = asHasLevels<ConceptualWallet>(request.publicDeriver);
const derivationTables = withLevels == null
? new Map()
: withLevels.getParent().getDerivationTables();
const deps = Object.freeze({
GetUtxoTxOutputsWithTx,
GetAddress,
GetPathWithSpecific,
GetDerivationSpecific,
});
const depTables = Object
.keys(deps)
.map(key => deps[key])
.flatMap(table => getAllSchemaTables(request.publicDeriver.getDb(), table));
return await raii<PromisslessReturnType<typeof getAllAddressesForDisplay>>(
request.publicDeriver.getDb(),
[
...depTables,
...mapToTables(
request.publicDeriver.getDb(),
derivationTables
),
],
async tx => await rawGetAllAddressesForDisplay(
tx,
deps,
{
publicDeriver: request.publicDeriver,
type: request.type,
},
derivationTables,
)
);
}
export async function rawGetAddressRowsForWallet(
tx: lf$Transaction,
deps: {|
GetPathWithSpecific: Class<GetPathWithSpecific>,
GetAddress: Class<GetAddress>,
GetDerivationSpecific: Class<GetDerivationSpecific>,
|},
request: {| publicDeriver: IPublicDeriver<>, |},
derivationTables: Map<number, string>,
): Promise<{|
utxoAddresses: Array<$ReadOnly<AddressRow>>,
accountingAddresses: Array<$ReadOnly<AddressRow>>,
|}> {
const utxoAddresses = [];
const accountingAddresses = [];
const withUtxos = asGetAllUtxos(request.publicDeriver);
if (withUtxos != null) {
const addrResponse = await withUtxos.rawGetAllUtxoAddresses(
tx,
{
GetPathWithSpecific: deps.GetPathWithSpecific,
GetAddress: deps.GetAddress,
GetDerivationSpecific: deps.GetDerivationSpecific,
},
undefined,
derivationTables,
);
for (const family of addrResponse) {
for (const addr of family.addrs) {
utxoAddresses.push(addr);
}
}
}
const withAccounting = asGetAllAccounting(request.publicDeriver);
if (withAccounting != null) {
const addrResponse = await withAccounting.rawGetAllAccountingAddresses(
tx,
{
GetPathWithSpecific: deps.GetPathWithSpecific,
GetAddress: deps.GetAddress,
GetDerivationSpecific: deps.GetDerivationSpecific,
},
undefined,
derivationTables,
);
for (const family of addrResponse) {
for (const addr of family.addrs) {
accountingAddresses.push(addr);
}
}
}
return {
utxoAddresses,
accountingAddresses,
};
}
export async function buildTokenMap(
request: {|
publicDeriver: IPublicDeriver<ConceptualWallet>,
tokenListIds: Array<number>,
|},
): Promise<$ReadOnlyArray<{|
TokenList: $ReadOnly<TokenListRow>,
Token: $ReadOnly<TokenRow>,
|}>> {
const deps = Object.freeze({
AssociateToken,
GetToken,
});
const depTables = Object
.keys(deps)
.map(key => deps[key])
.flatMap(table => getAllSchemaTables(request.publicDeriver.getDb(), table));
return await raii<PromisslessReturnType<typeof buildTokenMap>>(
request.publicDeriver.getDb(),
depTables,
async tx => await deps.AssociateToken.join(
request.publicDeriver.getDb(), tx,
{
listIds: request.tokenListIds,
networkId: request.publicDeriver.getParent().getNetworkInfo().NetworkId,
}
)
);
}
|
import React from 'react';
import { ReactComponent as LoaderSvg } from '../../assets/svg/loader.svg';
const Loader = () => (
<div className="loader">
<LoaderSvg className="loader__svg" />
</div>
);
export default Loader;
|
import fonts from "./fonts";
const breakpointValues = {
xs: 0,
sm: 596,
md: 800,
lg: 1000,
xl: 1333,
};
// replace above with this later
// const breakpointValues = {
// mobile: 590,
// tablet: 970,
// browser: 1333,
// };
const commonSettings = {
direction: "ltr",
typography: {
fontSize: 16,
fontFamily: "Poppins",
h1: {
fontSize: "3.3rem",
},
h2: {
fontSize: "2.3rem",
fontWeight: 600,
letterSpacing: "1.3px",
},
h3: {
fontSize: "1.75rem",
},
h4: {
fontSize: "1.5rem",
},
h5: {
fontSize: "1.25rem",
letterSpacing: "0.4px",
},
h6: {
fontSize: "1rem",
},
body1: {
fontSize: "0.875rem",
fontWeight: 500,
lineHeight: 1,
},
body2: {
fontSize: "0.75rem",
fontWeight: 400,
lineHeight: 1,
},
button: {
textTransform: "none",
fontSize: "1.25rem",
},
},
overrides: {
MuiCssBaseline: {
"@global": {
"@font-face": fonts,
breakpoints: { values: breakpointValues },
body: {
backgroundRepeat: "no-repeat",
backgroundAttachment: "fixed",
},
},
},
MuiToolbar: {
root: {
justifyContent: "flex-end",
},
},
MuiPaper: {
root: {
// backdropFilter: "blur(33px)",
"&.ohm-card": {
padding: "20px 30px 30px 30px",
borderRadius: "10px",
maxWidth: "833px",
width: "97%",
marginBottom: "1.8rem",
borderRadius: "10px",
overflow: "hidden",
},
"&.ohm-menu": {
padding: "22px 0px",
borderRadius: "10px",
margin: "0px",
},
"&.ohm-chart-card": {
padding: "20px 0px",
whiteSpace: "nowrap",
maxWidth: "700px",
width: "97%",
marginBottom: "1.8rem",
},
},
},
MuiContainer: {
root: {
backgroundColor: "transparent",
flexGrow: 1,
},
},
MuiLink: {
root: {
textUnderlineOffset: ".23rem",
cursor: "pointer",
"&:hover": {
textDecoration: "none",
underline: "none",
},
},
},
MuiTable: {
root: {
margin: "10px 0px",
},
},
MuiTableCell: {
root: {
borderBottom: 0,
fontSize: "1rem",
},
head: {
color: "#999999",
},
},
MuiDrawer: {
root: {
width: "280px",
flexShrink: 0,
},
paper: {
width: "inherit",
// backdropFilter: "blur(33px)",
backgroundColor: "inherit",
padding: 0,
},
},
MuiBackdrop: {
root: {
backdropFilter: "blur(15px)",
zIndex: 0,
},
},
MuiToggleButton: {
root: {
border: 0,
borderRadius: "5px",
margin: "8px",
padding: "10px",
},
},
MuiButton: {
root: {
borderRadius: "5px",
textTransform: "none",
textDecoration: "none",
whiteSpace: "nowrap",
minWidth: "max-content",
maxHeight: "40px",
},
containedPrimary: {
border: 0,
fontWeight: "500",
},
containedSecondary: {
fontWeight: "400",
},
outlinedPrimary: {
height: "33px",
padding: "9px 20px",
},
outlinedSecondary: {
textTransform: "none",
textDecoration: "none",
height: "33px",
fontSize: "1.1em",
padding: "9px 20px",
},
text: {
"&:hover": {
backgroundColor: "#00000000",
},
},
textSecondary: {
textTransform: "none",
textDecoration: "none",
padding: "2px 2px",
"&:hover": {
backgroundColor: "#00000000",
},
},
},
MuiIconButton: {
root: {
"&:hover": {
backgroundColor: "#00000000",
},
},
},
MuiInputBase: {
root: {
height: "43px",
padding: "5px",
},
},
MuiInputLabel: {
outlined: {
transform: "translate(16px, 14px) scale(1)",
},
},
MuiTabs: {
root: {
minHeight: "40px",
height: "40px",
},
},
MuiTab: {
root: {
minWidth: "min-content !important",
width: "min-content",
padding: "0px",
margin: "0px 10px",
fontWeight: 400,
fontSize: "24px",
fontStyle: "normal",
lineHeight: "24px",
},
},
},
props: {
MuiButtonBase: {
disableRipple: true,
},
MuiButton: {
disableElevation: true,
disableFocusRipple: true,
disableRipple: true,
},
MuiTextButton: {
disableFocusRipple: true,
disableRipple: true,
},
MuiPaper: {
elevation: 0,
},
MuiTypograph: {
gutterBottom: true,
},
MuiLink: {
underline: "none",
},
MuiSvgIcon: {
viewBox: "0 0 20 20",
fontSize: "small",
},
MuiBackdrop: {
transitionDuration: 300,
},
MuiPopover: {
transitionDuration: 300,
},
},
};
export default commonSettings;
|
import {stringify} from 'qs';
import request from '../utils/request';
import {getPlainNode} from "../utils/utils";
/**
* 全部权限树
* @returns {Promise<Object>}
*/
export async function page(payload) {
return request(`/api/permission/page`, {
method: 'GET',
body: payload
});
}
export async function getPermissionByParentId(payload) {
return request(`/api/permission/getPermissionByParentId`, {
method: 'GET',
body: payload
});
}
/**
* 保存或者更新权限
* @param payload
* @returns {Promise<Object>}
*/
export async function saveOrUpdate(payload) {
return request(`/api/permission/saveOrUpdate`, {
method: 'POST',
body: payload
});
}
/**
* 批量删除权限
* @param payload
* @returns {Promise<Object>}
*/
export async function deleteBatch(payload) {
return request(`/api/permission/deleteBatch`, {
method: 'POST',
body: payload
});
}
|
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactDom = require('react-dom');
var _reactDom2 = _interopRequireDefault(_reactDom);
var _redux = require('redux');
var _reactRedux = require('react-redux');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function counter() {
var state = arguments.length <= 0 || arguments[0] === undefined ? { value: 0 } : arguments[0];
var action = arguments[1];
switch (action.type) {
case 'INCREMENT':
return _extends({}, state, { value: state.value + 1 });
case 'DECREMENT':
return _extends({}, state, { value: state.value - 1 });
default:
return state;
}
}
var store = (0, _redux.createStore)(counter);
function select(state) {
return state;
}
var App = function (_Component) {
_inherits(App, _Component);
function App() {
_classCallCheck(this, App);
return _possibleConstructorReturn(this, _Component.apply(this, arguments));
}
App.prototype.render = function render() {
return _react2.default.createElement(
'div',
null,
this.props.value
);
};
return App;
}(_react.Component);
var ConnectedApp = (0, _reactRedux.connect)(select)(App);
_reactDom2.default.render(_react2.default.createElement(
_reactRedux.Provider,
{ store: store },
_react2.default.createElement(ConnectedApp, null)
), document.getElementById("app"));
|
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`E2E lint assertions-mutually-exclusive-error 1`] = `
validating /openapi.yaml...
[1] openapi.yaml:18:5 at #/paths/~1pet~1findByStatus/get
Operation should not have summary and tags fields simultaneously
16 | paths:
17 | /pet/findByStatus:
18 | get:
| ^^^
19 | operationId: example
20 | summary: summary example
Error was generated by the assertion #1 rule.
/openapi.yaml: validated in <test>ms
❌ Validation failed with 1 error.
run \`openapi lint --generate-ignore-file\` to add all problems to the ignore file.
`;
|
module.exports = function(grunt){
'use strict';
grunt.initConfig({
jshint : {
all : {
files : {
src : ['Gruntfile.js', 'index.js', 'templates.json', 'test/index.js', 'test/transcript.json', 'examples/*.js']
},
options : {
node : true
}
}
},
test : {
options : {
require : ['should'],
ui : 'bdd',
reporter : 'spec'
},
all : {
src : 'test/index.js'
}
}
});
grunt.loadNpmTasks('grunt-cafe-mocha');
grunt.renameTask('cafemocha', 'test');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.registerTask('default', ['jshint', 'test']);
};
|
const fakeInstall = require("fake-build");
const owners = [
"ethereum",
"eosio",
"bitcoin",
"iotaledger",
"NemProject",
];
module.exports = async function() {
for (const owner of owners) {
await fakeInstall(owner);
}
}
|
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
export function getTypedMakeValidator(valueTypes) {
function makeValidatorFunction(validatorFunction) {
return validatorFunction;
}
return makeValidatorFunction;
}
export function makeValidatorFunction(validatorFunction) {
return validatorFunction;
}
var defaultRegexes = {
email: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
aNumber: /[0-9]/,
aNonNumber: /[^0-9]/,
anUppercaseLetter: /[A-Z]/,
aLowercaseLetter: /[a-z]/,
aSpace: /\s/,
};
export function makeValidatorUtils(customRegexes) {
var regexes = __assign(__assign({}, defaultRegexes), (customRegexes !== null && customRegexes !== void 0 ? customRegexes : {}));
function isString(value) {
return typeof value === "string";
}
function isTypedString(value) {
// is a string and not empty
return !isString(value) || !(isString(value) && value.length === 0);
}
function stringMatches(value, regexName) {
return isTypedString(value) && regexes[regexName].test(value);
}
function stringDoesntMatch(value, regexName) {
return isTypedString(value) && !regexes[regexName].test(value);
}
return {
isString: isString,
isTypedString: isTypedString,
stringMatches: stringMatches,
stringDoesntMatch: stringDoesntMatch,
};
}
|
import MuiGridListTileBar from '@material-ui/core/GridListTileBar'
export default MuiGridListTileBar
|
export default{
name: "beerInfo",
template: `
<div class="itemInfo-component">
<a class="btn bg-orange" v-on:click="back" style="color: white;"> ❮ Back </a>
<div v-if="beer.name" class="item-title">
<h1>{{beer.name}}</h1>
<h4>{{beer.tagline}}</h4>
</div>
<div class="itemInfo-conteiner">
<div class="item-left">
<div class="item-image">
<img id="beer_img" :src="beer.image_url">
</div>
</div>
<div class="item-right">
<div class="item-specific">
<div class="item-field">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M310.5 227.7c-16-20-24.8-44.8-26.3-73.9 -1.2-22.2 2.7-38.6 2.7-38.7l3.9-16.2 -16.3 3.2c-37.4 7.4-67.2 24-88.6 49.4 -17.7 21-29.8 48.4-36 81.5 -3.4-1.6-6.4-3.2-7.9-5.3l-11.8-15.4 -6.7 18.2c-9.6 26.1-13.1 51.2-10.6 74.6 2.3 21.4 9.5 40.9 21.5 58.1 12.1 17.3 28.7 31.6 48.2 41.5 18.4 9.3 38.4 14.3 57.9 14.3 0 0 0 0 0 0 0.1 0 0.1 0 0.2 0h0c0.1 0 0.1 0 0.2 0h10.6v-0.6c15.6-1.7 31.2-7 45.1-15.3 18-10.8 32-26 40.6-43.9C348.1 336.3 359.3 288.8 310.5 227.7zM317.9 349.9c-13.5 28.1-45.3 47.8-77.3 47.8 -34.2 0-69.1-18.3-88.9-46.6 -13.6-19.5-26.1-52.1-12.7-99.6 1.5 0.7 3 1.4 4.5 2.1 3.1 1.4 6.1 2.8 8.3 4.4l14.5 10.5 2.3-17.7c8.8-67.2 39.9-107.9 95-124 -0.8 7.4-1.2 16.8-0.7 27.5 1.6 33.5 12.3 63.5 31 86.8C324.6 279.6 333.2 318.2 317.9 349.9z"/><path d="M357.3 99.1c-23.6 0-42.7 19.1-42.7 42.7 0 23.6 19.1 42.7 42.7 42.7s42.7-19.1 42.7-42.7C400 118.2 380.9 99.1 357.3 99.1zM357.3 163.1c-11.8 0-21.3-9.6-21.3-21.3 0-11.8 9.6-21.3 21.3-21.3s21.3 9.6 21.3 21.3C378.7 153.5 369.1 163.1 357.3 163.1z"/></svg>
<span>{{beer.abv}}</span>
</div>
<div class="item-field">
<svg id="Layer_1" enable-background="new 0 0 512 512" height="512" viewBox="0 0 512 512" width="512" xmlns="http://www.w3.org/2000/svg"><g><path d="m446 40h-46v-24c0-8.836-7.163-16-16-16s-16 7.164-16 16v24h-224v-24c0-8.836-7.163-16-16-16s-16 7.164-16 16v24h-46c-36.393 0-66 29.607-66 66v340c0 36.393 29.607 66 66 66h380c36.393 0 66-29.607 66-66v-340c0-36.393-29.607-66-66-66zm-380 32h46v16c0 8.836 7.163 16 16 16s16-7.164 16-16v-16h224v16c0 8.836 7.163 16 16 16s16-7.164 16-16v-16h46c18.748 0 34 15.252 34 34v38h-448v-38c0-18.748 15.252-34 34-34zm380 408h-380c-18.748 0-34-15.252-34-34v-270h448v270c0 18.748-15.252 34-34 34z"/></g></svg>
<span>{{beer.first_brewed}}</span>
</div>
</div>
<div v-if="beer.description" class="item-more-info">
<h4> Description: </h4>
<div>
<p>
{{beer.description}}
</p>
</div>
</div>
</div>
</div>
</div>
`,
data() {
return {
beer: null
}
},
beforeMount() {
fetch("/api/beers/"+this.$route.params.id,{
credentials:"include"
})
.then(response=>response.json())
.then(data=>{
this.beer=data;
});
},
methods: {
back: function(){
this.$router.back();
}
},
}
|
import React from "react"
import {graphql} from "gatsby"
import Layout from "../components/layout"
import SectionHeader from "../components/Services/SectionHeader/SectionHeader"
import SectionBookAnAppointment from "../components/HomePageComponents/SectionBookAnAppointment/SectionBookAnAppointment"
import SectionForm from "../components/HomePageComponents/SectionForm/SectionForm"
import SectionListPosts from "../components/BlogPage/SectionListPosts/SectionListPosts"
import SEO from "../components/seo"
const Author = ({ data }) =>{
return(
<Layout>
<SEO seo={data.seo.SEO_Blog_Page} />
<SectionHeader
title={data.blogPage.Title}
background={data.blogPage.Background_Section_Header[0].url}
/>
<SectionListPosts
posts={data.authorPage.articles}
recentPosts={data.recentPosts.nodes}
author={data.authorPage.username}
shortText={true}
/>
<SectionBookAnAppointment />
<SectionForm />
</Layout>
)
}
export default Author
export const queryAuthor = graphql`
query UserTemplate($username: String) {
seo: strapiArticles {
SEO_Articles {
Description
Image_Url
Title
}
}
authorPage: strapiUsers(username: { eq: $username}) {
id
username
articles {
Title
slug
createdAt(formatString: "MMM D Y")
Text
author
category_article
Image {
alternativeText
url
}
}
}
blogPage: strapiBlogPage {
Title
Background_Section_Header {
alternativeText
url
}
}
recentPosts: allStrapiArticles(limit: 4) {
nodes {
Title
Text
author {
username
}
Image {
url
alternativeText
}
createdAt
}
}
}
`
|
// Material Design colors //////////////////////////////////////////////////////////////////////////
// https://material.io/design/color/the-color-system.html#tools-for-picking-colors
// https://material.io/resources/color/
// Material A 700 (very intense, too purple)
// const colorRed = '#d50000';
// const colorPink = '#c51162';
// const colorPurple = '#aa00ff';
// const colorDeepPurple = '#6200ea';
// const colorIndigo = '#304ffe';
// const colorBlue = '#2962ff';
// const colorLightBlue = '#0091ea';
// const colorCyan = '#00b8d4';
// const colorTeal = '#00bfa5';
// const colorGreen = '#00c853';
// const colorLightGreen = '#64dd17';
// const colorLime = '#aeea00';
// const colorYellow = '#ffd600';
// const colorAmber = '#ffab00';
// const colorOrange = '#ff6d00';
// const colorDeepOrange = '#dd2c00';
// Material A 400 (good)
// const colorRed = '#ff1744';
// const colorPink = '#f50057';
// const colorPurple = '#d500f9';
// const colorDeepPurple = '#651fff';
// const colorIndigo = '#3d5afe';
// const colorBlue = '#2979ff';
// const colorLightBlue = '#00b0ff';
// const colorCyan = '#00e5ff';
// const colorTeal = '#1de9b6';
// const colorGreen = '#00e676';
// const colorLightGreen = '#76ff03';
// const colorLime = '#c6ff00';
// const colorYellow = '#ffea00';
// const colorAmber = '#ffc400';
// const colorOrange = '#ff9100';
// const colorDeepOrange = '#ff3d00';
// Material 700 (depressive)
// const colorRed = '#d32f2f';
// const colorPink = '#c2185b';
// const colorPurple = '#7b1fa2';
// const colorDeepPurple = '#512da8';
// const colorIndigo = '#303f9f';
// const colorBlue = '#1976d2';
// const colorLightBlue = '#0288d1';
// const colorCyan = '#0097a7';
// const colorTeal = '#00796b';
// const colorGreen = '#388e3c';
// const colorLightGreen = '#689f38';
// const colorLime = '#afb42b';
// const colorYellow = '#fbc02d';
// const colorAmber = '#ffa000';
// const colorOrange = '#f57c00';
// const colorDeepOrange = '#e64a19';
// const colorBrown = '#5d4037';
// const colorGrey = '#616161';
// const colorBlueGrey = '#455a64';
// Material 600 (ok'ish)
// const colorRed = '#e53935';
// const colorPink = '#d81b60';
// const colorPurple = '#8e24aa';
// const colorDeepPurple = '#5e35b1';
// const colorIndigo = '#3949ab';
// const colorBlue = '#1e88e5';
// const colorLightBlue = '#039be5';
// const colorCyan = '#00acc1';
// const colorTeal = '#00897b';
// const colorGreen = '#43a047';
// const colorLightGreen = '#7cb342';
// const colorLime = '#c0ca33';
// const colorYellow = '#fdd835';
// const colorAmber = '#ffb300';
// const colorOrange = '#fb8c00';
// const colorDeepOrange = '#f4511e';
// const colorBrown = '#6d4c41';
// const colorGrey = '#757575';
// const colorBlueGrey = '#546e7a';
// Material 500 (best)
const colorRed = '#f44336';
const colorPink = '#e91e63';
const colorPurple = '#9c27b0';
const colorDeepPurple = '#673ab7';
const colorIndigo = '#3f51b5';
const colorBlue = '#2196f3';
const colorLightBlue = '#03a9f4';
const colorCyan = '#00bcd4';
const colorTeal = '#009688';
const colorGreen = '#4caf50';
const colorLightGreen = '#8bc34a';
const colorLime = '#cddc39';
const colorYellow = '#ffeb3b';
const colorAmber = '#ffc107';
const colorOrange = '#ff9800';
const colorDeepOrange = '#ff5722';
const colorBrown = '#795548';
const colorGrey = '#9e9e9e';
const colorBlueGrey = '#607d8b';
// Material 400 (too light)
// const colorRed = '#ef5350';
// const colorPink = '#ec407a';
// const colorPurple = '#ab47bc';
// const colorDeepPurple = '#7e57c2';
// const colorIndigo = '#5c6bc0';
// const colorBlue = '#42a5f5';
// const colorLightBlue = '#29b6f6';
// const colorCyan = '#26c6da';
// const colorTeal = '#26a69a';
// const colorGreen = '#66bb6a';
// const colorLightGreen = '#9ccc65';
// const colorLime = '#d4e157';
// const colorYellow = '#ffee58';
// const colorAmber = '#ffca28';
// const colorOrange = '#ffa726';
// const colorDeepOrange = '#ff7043';
// const colorBrown = '#8d6e63';
// const colorGrey = '#bdbdbd';
// const colorBlueGrey = '#78909c';
// Material 100 (supplemental)
const colorGrey100 = '#f5f5f5';
const colorGrey100Dark = '#c2c2c2';
// alpha values
const colorAlpha00 = '00';
const colorAlpha10 = '10';
const colorAlpha20 = '20';
const colorAlpha40 = '40';
// browser history handling ////////////////////////////////////////////////////////////////////////
let isHistoryBack = false;
window.onpopstate = function (event) {
if (event.state && event.state.min && event.state.max) {
isHistoryBack = true;
chart.xAxis[0].setExtremes(event.state.min, event.state.max);
}
};
// Highcharts Stock initialization /////////////////////////////////////////////////////////////////
const chart = Highcharts.stockChart('container', {
accessibility: {
keyboardNavigation: {
enabled: false,
},
},
chart: {
animation: false, // improves performance
shadow: false, // improves performance
events: {
render: function () {
// custom timeframe label
if (this.series[0]) {
if (!chart.labelTimeframe) {
chart.labelTimeframe = this.renderer
.label('', 0, 0)
.css({
fontWeight: 'bold',
})
.add();
}
const string =
(this.series[0].currentDataGrouping ? this.series[0].currentDataGrouping.count : '1') +
' ' +
(this.series[0].currentDataGrouping ? this.series[0].currentDataGrouping.unitName : 'minute') +
' time frame from ' +
Highcharts.dateFormat('%A %Y-%m-%d %H:%M', this.series[0].processedXData[0]) +
' to ' +
Highcharts.dateFormat(
'%A %Y-%m-%d %H:%M',
this.series[0].processedXData[this.series[0].processedXData.length - 1] +
(this.series[0].currentDataGrouping ? this.series[0].currentDataGrouping.unitRange : chart.series[0].basePointRange)
);
chart.labelTimeframe.attr({
text: string,
});
}
},
},
ignoreHiddenSeries: true,
margin: [0, 0, 0, 0], // margin between the outer edge of the chart and the plot area
spacing: [0, 0, 0, 0], // between outer edge of chart and content, like title or legend, or axis title and labels if present
zoomType: 'x',
},
credits: {
enabled: false,
},
legend: {
enabled: false,
},
navigator: {
height: 75,
maskFill: colorBlue + colorAlpha20,
},
plotOptions: {
series: {
animation: false,
dataGrouping: {
units: [
['minute', [1]],
['hour', [1]],
['day', [1]],
['month', [1]],
['year', [1]],
],
dateTimeLabelFormats: {
millisecond: ['%A %Y-%m-%d %H:%M:%S.%L'],
second: ['%A %Y-%m-%d, %H:%M:%S'],
minute: ['%A %Y-%m-%d %H:%M'],
hour: ['%A %Y-%m-%d %H:%M'],
day: ['%A %Y-%m-%d'],
week: ['%Y-%m-%d'],
month: ['%Y-%m'],
year: ['%Y'],
},
},
marker: {
enabled: false,
},
states: {
hover: {
enabled: false,
},
},
showInNavigator: false,
tooltip: {
headerFormat: '{point.key}', // floating date above the navigator and following the mouse cursor
pointFormat: '<span style="color:{point.color};">█ </span><span style="font-weight: bold;">{series.name}</span> {point.y}',
valueDecimals: 6,
},
},
candlestick: {
zIndex: 666,
showInNavigator: true,
color: colorBlue,
lineColor: colorBlue,
upColor: 'white',
upLineColor: colorBlue,
navigatorOptions: {
type: 'area',
color: colorBlue,
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 0.95, // original: 1
},
stops: [
[0, colorBlue + colorAlpha40],
[1, colorBlue + colorAlpha00],
],
},
lineWidth: 1,
},
tooltip: {
pointFormat:
'<span style="font-weight: bold;">{series.name}</span> ' + 'O {point.open} / ' + 'H {point.high} / ' + 'L {point.low} / ' + 'C {point.close}',
},
},
},
rangeSelector: {
height: 27, // fixes padding of unknown origin between range selector and plot area
inputEnabled: false,
buttonPosition: {
align: 'right',
x: 0,
y: 0,
},
buttonTheme: {
r: 0,
fill: colorGrey100,
style: {
color: colorBlue,
},
states: {
hover: {
fill: colorBlue,
style: {
color: 'white',
},
},
select: {
fontWeight: 'bold',
fill: colorGrey100Dark,
style: {
color: 'black',
},
},
disabled: {
style: {
color: colorGrey100Dark,
},
},
},
},
buttons: [
{ type: 'hour', count: 1, text: '1h' },
{ type: 'hour', count: 2, text: '2h' },
{ type: 'hour', count: 3, text: '3h' },
{ type: 'hour', count: 4, text: '4h' },
{ type: 'hour', count: 6, text: '6h' },
{ type: 'hour', count: 12, text: '12h' },
{ type: 'day', count: 1, text: '1d' },
{ type: 'day', count: 2, text: '2d' },
{ type: 'day', count: 3, text: '3d' },
{ type: 'day', count: 4, text: '4d' },
{ type: 'day', count: 5, text: '5d' },
{ type: 'day', count: 6, text: '6d' },
{ type: 'week', count: 1, text: '1w' },
{ type: 'week', count: 2, text: '2w' },
{ type: 'week', count: 3, text: '3w' },
{ type: 'month', count: 1, text: '1m' },
{ type: 'month', count: 2, text: '2m' },
{ type: 'month', count: 3, text: '3m' },
{ type: 'year', count: 1, text: '1y' },
{ type: 'all', text: 'All' },
],
selected: 19,
},
scrollbar: {
// enabled: false, // disables live redraw when scrolling, use height instead:
height: 0,
},
tooltip: {
// xDateFormat doesn't work, see https://stackoverflow.com/questions/15212475/xdateformat-string-doesnt-apply-to-large-amounts-of-data/15224477#15224477
// must be set in: series > dataGrouping > dateTimeLabelFormats
// xDateFormat: '%Y-%m-%d',
hideDelay: 0,
backgroundColor: colorGrey100Dark,
borderWidth: 0,
shape: 'square',
headerShape: 'callout',
shadow: false,
positioner: function (width, height, point) {
var chart = this.chart;
if (point.isHeader) {
return {
x: Math.max(
0, // left side limit
Math.min(
point.plotX + chart.plotLeft - width / 2,
chart.chartWidth - width - chart.marginRight // right side limit
)
),
y: chart.plotHeight,
};
} else {
return {
x: point.series.chart.plotLeft + (point.plotX > 400 ? 0 : 1000),
y: point.series.yAxis.top - point.series.chart.plotTop,
};
}
},
},
xAxis: {
// type: 'datetime', // not necessary
crosshair: {
color: colorGrey100Dark,
// this is being taken care of by the chart's tooltip header:
// label: {
// enabled: true,
// backgroundColor: colorBlue,
// },
},
events: {
afterSetExtremes: function (event) {
document.title = Highcharts.dateFormat('%A %Y-%m-%d %H:%M', event.min) + ' - ' + Highcharts.dateFormat('%A %Y-%m-%d %H:%M', event.max);
if (isHistoryBack) {
isHistoryBack = false;
} else {
history.pushState({ min: event.min, max: event.max }, '', '');
}
},
},
},
yAxis: [
{
height: '70%',
labels: {
format: '{value:.4f}',
},
startOnTick: false,
endOnTick: false,
crosshair: {
color: colorGrey100Dark,
label: {
enabled: true,
format: '{value:.6f}',
style: {
color: 'black',
},
backgroundColor: colorGrey100Dark,
},
},
},
{
top: '70%',
height: '15%',
gridLineWidth: 0,
startOnTick: false,
endOnTick: false,
labels: {
enabled: false,
format: '{value:.1f}',
},
plotLines: [
{
value: 0, // requires "gridLineWidth: 0;" on this yAxis to work
width: 1,
dashStyle: 'ShortDot',
color: colorBlue,
},
{ value: 100, width: 1, dashStyle: 'ShortDot', color: colorBlue },
{ value: 70, width: 1, dashStyle: 'ShortDot', color: colorBlue },
{ value: 50, width: 1, dashStyle: 'ShortDot', color: colorBlue },
{ value: 30, width: 1, dashStyle: 'ShortDot', color: colorBlue },
{ value: 0, width: 1, dashStyle: 'ShortDot', color: colorBlue },
],
plotBands: [
{ color: colorDeepOrange + colorAlpha10, from: 50, to: 1e4 },
{ color: colorLightGreen + colorAlpha10, from: 50, to: -1e4 },
{ color: colorBlue + colorAlpha40, from: 30, to: 70 },
],
},
{
top: '85%',
height: '15%',
gridLineWidth: 0,
startOnTick: false,
endOnTick: false,
labels: {
enabled: false,
format: '{value:.1f}',
},
plotLines: [
{
value: 0, // requires "gridLineWidth: 0;" on this yAxis to work
width: 1,
dashStyle: 'ShortDot',
color: colorBlue,
},
{ value: 100, width: 1, dashStyle: 'ShortDot', color: colorBlue },
{ value: -100, width: 1, dashStyle: 'ShortDot', color: colorBlue },
],
plotBands: [
{ color: colorDeepOrange + colorAlpha10, from: 0, to: 1e4 },
{ color: colorLightGreen + colorAlpha10, from: 0, to: -1e4 },
],
},
],
});
chart.showLoading();
// chart zoom functions ////////////////////////////////////////////////////////////////////////////
const chartZoom = (...parameters) => {
const [/*double*/ zoomFactor] = parameters;
chart.showLoading(zoomFactor >= 1 ? '-' : '+');
const extremes = chart.xAxis[0].getExtremes();
const zoomRange = extremes.max - extremes.min;
const zoomDiff = (zoomRange * zoomFactor - zoomRange) / 2;
const [min, max] = (() => {
const isOutOfDataMin = extremes.min - zoomDiff < extremes.dataMin;
const isOutOfDataMax = extremes.max + zoomDiff > extremes.dataMax;
if (isOutOfDataMin & isOutOfDataMax) {
return [extremes.dataMin, extremes.dataMax];
} else if (isOutOfDataMin) {
return [extremes.dataMin, extremes.dataMin + zoomRange * zoomFactor];
} else if (isOutOfDataMax) {
return [extremes.dataMax - zoomRange * zoomFactor, extremes.dataMax];
} else {
return [extremes.min - zoomDiff, extremes.max + zoomDiff];
}
})();
setTimeout(() => {
// only delayed setExtremes() works properly
chart.xAxis[0].setExtremes(min, max);
chart.hideLoading();
}, 100);
};
const chartPan = (...parameters) => {
const [/*boolean*/ isLeft] = parameters;
chart.showLoading(isLeft ? '◄ ' : '►');
const extremes = chart.xAxis[0].getExtremes();
if ((isLeft && extremes.min == extremes.dataMin) || (!isLeft && extremes.max == extremes.dataMax)) {
// the condition works also when "series.hasGroupedData" is true
chart.hideLoading();
return;
}
const series = chart.series[0];
const seriesIndexLast = series.options.data.length - 1;
const [rawBarIndexFirst, rawBarIndexLast] = (() => {
if (series.hasGroupedData) {
return [series.cropStart, series.dataGroupInfo.start + series.dataGroupInfo.length - 1];
}
return [series.points[0].index, series.points[series.points.length - 1].index];
})();
// const panRawBars = (rawBarIndexLast - rawBarIndexFirst + 1) * (isLeft ? -1 : 1); // pan by all visible bars
const panFactor = 0.5; // pan by fraction of visible bars
const panRawBars = Math.trunc((rawBarIndexLast - rawBarIndexFirst + 1) * (isLeft ? -1 : 1) * panFactor); // pan by fraction of visible bars
const [min, max] = (() => {
const isOutOfIndexMin = rawBarIndexFirst + panRawBars < 0;
const isOutOfIndexMax = rawBarIndexLast + panRawBars > seriesIndexLast;
if (isOutOfIndexMin && isOutOfIndexMax) {
return [null, null];
} else if (isOutOfIndexMin) {
// return [series.xData[0], series.xData[Math.abs(panRawBars)]]; // pan by all visible bars
return [series.xData[0], series.xData[Math.abs(panRawBars) / panFactor]]; // pan by fraction of visible bars
} else if (isOutOfIndexMax) {
// return [series.xData[seriesIndexLast - panRawBars], series.xData[seriesIndexLast]]; // pan by all visible bars
return [series.xData[seriesIndexLast - panRawBars / panFactor], series.xData[seriesIndexLast]]; // pan by fraction of visible bars
} else {
return [series.xData[rawBarIndexFirst + panRawBars], series.xData[rawBarIndexLast + panRawBars]];
}
})();
setTimeout(() => {
chart.xAxis[0].setExtremes(min, max);
chart.hideLoading();
}, 100);
};
const chartShiftRight = () => {
chart.showLoading('▲');
setTimeout(() => {
const length = 1000;
chart.xAxis[0].setExtremes(chart.series[0].xData[chart.series[0].xData.length - length], chart.series[0].xData[chart.series[0].xData.length - 1]);
chart.hideLoading();
}, 100);
};
const chartZoomAll = () => {
chart.showLoading('0');
setTimeout(() => {
chart.xAxis[0].setExtremes(null, null);
chart.hideLoading();
}, 100);
};
// key press handling //////////////////////////////////////////////////////////////////////////////
document.addEventListener('keydown', (event) => {
switch (event.keyCode) {
// see https://keycode.info/
case 48: // 0
case 96: // numpad 0
event.preventDefault(); // disable Firefox's "Search for text when I start typing"
chartZoomAll();
break;
case 38: // up arrow
chartShiftRight();
break;
case 40: // down arrow
break;
case 37: // left arrow
chartPan(true);
break;
case 39: // right arrow
chartPan(false);
break;
case 171: // plus
case 107: // numpad plus
event.preventDefault(); // disable Firefox's "Search for text when I start typing"
chartZoom(1 / 1.5);
break;
case 173: // minus
case 109: // numpad minus
event.preventDefault(); // disable Firefox's "Search for text when I start typing"
chartZoom(1.5);
break;
case 27: // ESC
case 63: // ?
event.preventDefault(); // disable Firefox's "Search for text when I start typing"
const element = document.querySelector('#containerHelp');
if (element) {
if (element.style.visibility === 'visible') {
element.style.visibility = 'hidden';
} else {
element.style.visibility = 'visible';
}
}
break;
}
});
// time series functions ///////////////////////////////////////////////////////////////////////////
const colors = {
range: [colorOrange, colorRed, colorPurple, colorIndigo, colorBlue, colorCyan, colorTeal, colorGreen, colorBrown, colorBlueGrey],
index: 0,
reset() {
this.index = 0;
},
get() {
if (this.index > this.range.length - 1) {
this.index = 0;
}
return this.range[this.index++];
},
};
const createSeriesLine = (line, yAxis, isTooltip) => {
const series = {
name: line.name ? line.name : 'undefined',
data: line.data,
type: 'line',
color: line.color ? line.color : colors.get(),
lineWidth: line.width > 0 ? line.width : 1,
states: {
hover: {
lineWidth: line.width > 0 ? line.width : 1,
},
},
};
if (line.step) {
series.step = true;
}
if (line.style) {
series.dashStyle = line.style;
}
if (line.connectNulls) {
series.connectNulls = true;
}
if (yAxis > 0) {
series.yAxis = yAxis;
}
if (isTooltip === false) {
// series.enableMouseTracking = false; // de-activates series generally and is problematic, instead use:
series.tooltip = {
pointFormatter: function () {
// properly disables tooltip
return false;
},
};
}
return series;
};
const createSeriesRange = (range, yAxis, isTooltip) => {
const series = {
name: range.name ? range.name : 'undefined',
data: range.data,
type: 'arearange',
color: range.color ? range.color : colors.get() + colorAlpha40,
lineWidth: 0,
};
if (range.step) {
series.step = true;
}
if (yAxis > 0) {
series.yAxis = yAxis;
}
if (isTooltip === false) {
series.tooltip = {
pointFormatter: function () {
return false;
},
};
}
return series;
};
const createPlotLine = (config) => {
const line = {
value: config.value,
color: config.color ? config.color : colorBlue,
width: config.width > 0 ? config.width : 1,
};
if (config.style) {
line.dashStyle = config.style;
}
if (config.label) {
line.label = {
rotation: 0,
text: config.label,
x: 5,
y: 20,
style: {
'font-weight': 'bold',
},
};
}
return line;
};
const createPlotBand = (config) => {
const band = {
from: config.valueFrom,
to: config.valueTo,
color: config.color ? config.color : colorBlue,
};
if (config.label) {
band.label = {
text: config.label,
textAlign: 'left',
x: 0,
};
}
return band;
};
// fetch data //////////////////////////////////////////////////////////////////////////////////////
// expected JSON structure
// =======================
// timeseries: { ... }
// ohlc: { name + data[] }
// lines: [ { name + data[] ( + step + color + style + width + connectNulls ) } ]
// range: { name + data[] ( + step + color ) }
// indicator1: { ... }
// extremes: { upper + lower }
// lines: see above
// range: see above
// indicator2: { ... }
// extremes: see above
// lines: see above
// range: see above
// markers: { ... }
// lines: [ { value ( + color + style + width + label ) } ]
// bands: [ { valueFrom + valueTo ( + color + label ) } ]
fetch('http://localhost:8888/json')
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
})
.then((response) => response.json())
.then((json) => {
chart.options.loading.labelStyle = {
'font-size': '500px',
fontWeight: 'bold',
color: colorBlue,
position: 'absolute',
top: 0,
right: 0,
bottom: 0,
left: 0,
display: 'flex',
'justify-content': 'center',
'align-items': 'center',
};
if (json.markers) {
if (json.markers.bands) {
json.markers.bands.forEach((band) => {
chart.xAxis[0].addPlotBand(createPlotBand(band));
});
}
if (json.markers.lines) {
json.markers.lines.forEach((line) => {
chart.xAxis[0].addPlotLine(createPlotLine(line));
});
}
}
if (json.timeseries) {
if (json.timeseries.ohlc) {
chart.addSeries({
type: 'candlestick',
name: json.timeseries.ohlc.name,
data: json.timeseries.ohlc.data,
});
}
if (json.timeseries.range) {
colors.reset();
chart.addSeries(createSeriesRange(json.timeseries.range));
}
if (json.timeseries.lines) {
colors.reset();
json.timeseries.lines.forEach((line) => chart.addSeries(createSeriesLine(line)));
}
}
if (json.indicator1) {
if (json.indicator1.extremes.lower && json.indicator1.extremes.upper) {
chart.yAxis[1].setExtremes(json.indicator1.extremes.lower * 1.025, json.indicator1.extremes.upper * 1.05); // ensures static min and max on zoom
}
if (json.indicator1.range) {
colors.reset();
chart.addSeries(createSeriesRange(json.indicator1.range, 1, false));
}
if (json.indicator1.lines) {
colors.reset();
json.indicator1.lines.forEach((line) => chart.addSeries(createSeriesLine(line, 1, false)));
}
}
if (json.indicator2) {
if (json.indicator2.extremes.lower && json.indicator2.extremes.upper) {
chart.yAxis[2].setExtremes(json.indicator2.extremes.lower * 1.05, json.indicator2.extremes.upper * 1.025); // ensures static min and max on zoom
}
if (json.indicator2.range) {
colors.reset();
chart.addSeries(createSeriesRange(json.indicator2.range, 2, false));
}
if (json.indicator2.lines) {
colors.reset();
json.indicator2.lines.forEach((line) => chart.addSeries(createSeriesLine(line, 2, false)));
}
}
chart.hideLoading();
})
.catch((error) => {
console.log(error);
chart.hideLoading();
});
|
import Vue from 'vue'
import Vuex from 'vuex'
import router from './router'
import axios from 'axios'
import {isNull} from "bootstrap-vue/esm/utils/inspect";
import {from} from "bootstrap-vue/esm/utils/array";
// test it.
Vue.use(Vuex)
export default new Vuex.Store({
state:{
userInfo: null,
isLogin: false,
isLoginError: true
},
mutations: {
//login success
loginSuccess(state){
state.isLogin = true,
state.isLoginError = false
},
//login fail
loginError(state){
state.isLogin = false,
state.isLoginError = true
},
logout(state) {
state.isLogin = false,
state.isLoginError = false,
sessionStorage.removeItem("access_token");
}
},
actions:{
getToken() {
const token = sessionStorage.getItem("access_token")
console.log(token)
return token
},
//try login
login({ commit}, loginObj) {
// Login => token return
axios
.post("/login", loginObj)
.then(res => {
let response = res.data
console.log(response)
if(response['code'] == '200')
{
sessionStorage.setItem("access_token", response['access_token'])
let token = sessionStorage.getItem("access_token")
let config = {
headers: {
"Authorization": token
}
}
commit('loginSuccess')
router.push("/Books")
}
else {
alert(' Check your Id&PW 1')
}
})
.catch(() => {
alert(' Check your Id&PW 2')
})
},
register({ commit }, registerObj) {
if (registerObj['password'] == registerObj['passwordConfirm'])
{
axios
.post("/api/register", registerObj)
.then(res => {
let response = res.data
{
console.log(response)
if (response['code'] == '404') {
alert(' Already exist ID')
} else {
alert(' Register Success')
router.go(-1)
}
}
})
}
else {
alert('password is not same')
}
},
loginRefresh( {commit} ) {
let token = sessionStorage.getItem("access_token");
if (token != null) {
commit("loginSuccess")
router.push("/dashboard")
}
else
commit('loginError')
},
logout({commit}) {
commit("logout")
router.push("/login")
},
}
})
|
// @flow
import React, { Component, type ComponentType, type ElementRef } from 'react';
import { omit, getDisplayName } from '../utils';
type Props = {
href?: string,
isActive?: boolean,
isFocus?: boolean,
isHover?: boolean,
isInteractive?: boolean,
onBlur?: () => mixed,
onClick?: () => mixed,
onFocus?: () => mixed,
onKeyDown?: () => mixed,
onKeyUp?: () => mixed,
onMouseDown?: () => mixed,
onMouseEnter?: () => mixed,
onMouseLeave?: () => mixed,
onMouseUp?: () => mixed,
};
const INTERNAL_HANDLERS = [
'onBlur',
'onFocus',
'onKeyDown',
'onKeyUp',
'onMouseDown',
'onMouseEnter',
'onMouseLeave',
'onMouseUp',
];
type State = {
isActive: boolean,
isFocus: boolean,
isHover: boolean,
isInteractive: boolean,
};
export default function withPseudoState<InnerProps: {}>(
WrappedComponent: ComponentType<InnerProps>,
) {
type CombinedProps = { ...$Exact<InnerProps>, ...$Exact<Props> };
return class ComponentWithPseudoState extends Component<
CombinedProps,
State,
> {
static displayName = getDisplayName('withPseudoState', WrappedComponent);
component: ElementRef<*>;
actionKeys: Array<string>;
componentWillMount() {
const { href, isInteractive, onClick } = this.props;
if (href || isInteractive || onClick) {
this.actionKeys = onClick || isInteractive ? ['Enter', ' '] : ['Enter'];
}
}
state: State = {
isActive: Boolean(this.props.isActive),
isFocus: Boolean(this.props.isActive),
isHover: Boolean(this.props.isActive),
isInteractive: Boolean(
this.props.href || this.props.isInteractive || this.props.onClick,
),
};
// expose blur/focus to consumers via ref
blur = () => {
if (this.component && this.component.blur) this.component.blur();
};
focus = () => {
if (this.component && this.component.focus) this.component.focus();
};
setComponent = (component: ElementRef<*>) => {
this.component = component;
};
onBlur = () => this.setState({ isActive: false, isFocus: false });
onFocus = () => this.setState({ isFocus: true });
onMouseLeave = () => this.setState({ isActive: false, isHover: false });
onMouseEnter = () => this.setState({ isHover: true });
onMouseUp = () => this.setState({ isActive: false });
onMouseDown = () => this.setState({ isActive: true });
onKeyDown = (event: KeyboardEvent) => {
if (this.actionKeys.indexOf(event.key) > -1) {
this.setState({ isActive: true });
}
};
onKeyUp = (event: KeyboardEvent) => {
if (this.actionKeys.indexOf(event.key) > -1) {
this.setState({ isActive: false });
}
};
getProps = (): CombinedProps => {
const { isInteractive } = this.state;
// strip the consumer's handlers off props, then merge with our handlers
// if the element is interactive
// We cannot properly type omit because of the inability to convert from
// an array to a union of the array's items. See https://github.com/facebook/flow/issues/961
// if you want to learn more about this
// $FlowFixMe
const props: CombinedProps = omit(this.props, ...INTERNAL_HANDLERS);
const self: Object = this;
if (isInteractive) {
INTERNAL_HANDLERS.forEach((handler: string) => {
if (this.props[handler]) {
props[handler] = (...args) => {
self[handler](...args);
this.props[handler](...args);
};
} else {
props[handler] = self[handler];
}
});
}
return props;
};
render() {
return (
<WrappedComponent
ref={this.setComponent}
{...this.state}
{...this.getProps()}
/>
);
}
};
}
|
var e10 = Math.sqrt(50),
e5 = Math.sqrt(10),
e2 = Math.sqrt(2);
/**
* 根据参数返回长度为count+1的刻度值数组,每个元素值都会转换为以10为底的幂
* @param {*} start
* @param {*} stop
* @param {*} count
*/
export default function(start, stop, count) {
var reverse,
i = -1,
n,
ticks,
step;
/** 下面的代码用于将数字串转换为数值型 */
stop = +stop, start = +start, count = +count;
if (start === stop && count > 0) return [start];
/** 确保start一定小于stop */
if (reverse = stop < start) n = start, start = stop, stop = n;
/** 当刻度间隔非常小,近似为0;或者step刻度间隔无穷大,则直接返回空 */
if ((step = tickIncrement(start, stop, count)) === 0 || !isFinite(step)) return [];
if (step > 0) {
start = Math.ceil(start / step);
stop = Math.floor(stop / step);
/** 没有count参与,通过刻度区间的缩放来实现 */
ticks = new Array(n = Math.ceil(stop - start + 1));
while (++i < n) ticks[i] = (start + i) * step;
} else {
start = Math.floor(start * step);
stop = Math.ceil(stop * step);
ticks = new Array(n = Math.ceil(start - stop + 1));
while (++i < n) ticks[i] = (start - i) / step;
}
if (reverse) ticks.reverse();
return ticks;
}
/**
* 类似tickStep函数,除了要求start小于等于step;
* 如果计算得到的tickStep小于
* @param {*} start
* @param {*} stop
* @param {*} count
*/
export function tickIncrement(start, stop, count) {
var step = (stop - start) / Math.max(0, count),
/** 当step小于1,则power为负数 */
power = Math.floor(Math.log(step) / Math.LN10),
error = step / Math.pow(10, power);
/** 当power大于0,则该函数功能与tickStep几乎一样;当power小于0,则 */
return power >= 0
? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power)
: -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);
}
/**
* 返回两个相邻刻度值的差值,由于IEEE754浮动限制,
* 返回值可能不是整数,可以使用d3-format模块进行格式化
* @param {*} start
* @param {*} stop
* @param {*} count
*/
export function tickStep(start, stop, count) {
/**
* step0表示数学意义上的均分值,
* 但是受计算机数值表示位数限制,step0并非精确均分
*/
var step0 = Math.abs(stop - start) / Math.max(0, count),
//Math.LN10表示10的自然对数值,Math.log表示以自然数e为底的对数
step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)),
error = step0 / step1;
/** 下面的精华,用于返回基于step0的四舍五入值 */
if (error >= e10) step1 *= 10;
else if (error >= e5) step1 *= 5;
else if (error >= e2) step1 *= 2;
return stop < start ? -step1 : step1;
}
|
// Ensure that sort behavior for undefined, missing, and null fields is the same for both find and
// aggregation. This test validates the fix for SERVER-42565, which was caused by inconsistent
// behavior for generating sort keys in aggregation.
(function() {
"use strict";
const coll = db.sort_key_with_missing_fields;
coll.drop();
assert.commandWorked(coll.insert([
{_id: 1, a: undefined},
{_id: 2, a: null},
{_id: 3, a: []},
{_id: 4},
{_id: 5},
{_id: 6, a: []},
{_id: 7, a: null},
{_id: 8, a: undefined},
]));
// Correct ordering treats {a: undefined} and {a: []} as the same value (undefined) and treats {a:
// null} and missing "a" as the same value (null). When we sort by the "a" field, we expect the sort
// to put all the undefined-like documents in one group (1, 3, 6, 8) and all null-like documents in
// another (2, 4, 5, 7). We break the ties within these two groups by sorting on the "_id" field.
const expectedOrderForward = [1, 3, 6, 8, 2, 4, 5, 7];
const expectedOrderReverse = [...expectedOrderForward].reverse();
function getArrayOfIds(arrayOfDocs) {
return arrayOfDocs.map(doc => doc._id);
}
function checkFindAndAggSorts(sortPattern, expectedOrder) {
// We include the sort key in the projection so that it will be included in the diagnostic
// output if the test fails as a result of incorrect output.
const findResult =
coll.find({}, {_id: 1, a: 1, key: {$meta: "sortKey"}}).sort(sortPattern).toArray();
assert.eq(getArrayOfIds(findResult), expectedOrder, findResult);
const aggResult =
coll.aggregate({$sort: sortPattern}, {$addFields: {key: {$meta: "sortKey"}}}).toArray();
assert.eq(getArrayOfIds(aggResult), expectedOrder, aggResult);
}
checkFindAndAggSorts({a: 1, _id: 1}, expectedOrderForward);
checkFindAndAggSorts({a: -1, _id: -1}, expectedOrderReverse);
// Repeat the above test, but this time we sort on a path that traverse an array, forcing the sort
// key generator to use its general path, instead of the fast path for sorting on non-array paths.
assert(coll.drop());
assert.commandWorked(coll.insert([
{_id: 1, a: [{b: undefined}]},
{_id: 2, a: [{b: null}]},
{_id: 3, a: [{b: []}]},
{_id: 4, a: [{}]},
{_id: 5},
{_id: 6, a: [{b: []}]},
{_id: 7, a: [{b: null}]},
{_id: 8, a: [{b: undefined}]},
]));
checkFindAndAggSorts({"a.b": 1, _id: 1}, expectedOrderForward);
checkFindAndAggSorts({"a.b": -1, _id: -1}, expectedOrderReverse);
}());
|
import React, { useState } from 'react';
import GradeDataService from '../services/GradeService';
const AddGrade = () => {
const initialGradeState = {
id: null,
name: '',
subject: '',
type: '',
value: '',
};
const [grade, setGrade] = useState(initialGradeState);
const [submitted, setSubmitted] = useState(false);
const handleInputChange = (event) => {
const { name, value } = event.target;
setGrade({ ...grade, [name]: value });
};
const saveGrade = () => {
var data = {
name: grade.name,
subject: grade.subject,
type: grade.type,
value: grade.value,
};
GradeDataService.create(data)
.then((response) => {
setGrade({
id: response.data.id,
name: response.data.name,
subject: response.data.img,
type: response.data.type,
value: response.data.value,
});
setSubmitted(true);
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
};
const newGrade = () => {
setGrade(initialGradeState);
setSubmitted(false);
};
return (
<div className="submit-form">
{submitted ? (
<div>
<h4>You submitted successfully!</h4>
<button className="btn btn-success" onClick={newGrade}>
Add
</button>
</div>
) : (
<div>
<div className="form-group">
<label htmlFor="name">Name</label>
<input
type="text"
className="form-control"
id="name"
required
value={grade.name}
onChange={handleInputChange}
name="name"
/>
</div>
<div className="form-group">
<label htmlFor="subject">Subject</label>
<input
type="text"
className="form-control"
id="subject"
required
value={grade.subject}
onChange={handleInputChange}
name="subject"
/>
</div>
<div className="form-group">
<label htmlFor="type">Type</label>
<input
type="text"
className="form-control"
id="type"
required
value={grade.type}
onChange={handleInputChange}
name="type"
/>
</div>
<div className="form-group">
<label htmlFor="value">Value</label>
<input
type="Number"
className="form-control"
id="value"
required
value={grade.value}
onChange={handleInputChange}
name="value"
/>
</div>
<button onClick={saveGrade} className="btn btn-success">
Submit
</button>
</div>
)}
</div>
);
};
export default AddGrade;
|
// Karma configuration
// Generated on Wed Jul 12 2017 09:28:46 GMT-0300 (BRT)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'base64-download.js',
'test/**/*Spec.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_DEBUG,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['ChromiumHeadless'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
|
(function(d){d['zh-cn']=Object.assign(d['zh-cn']||{},{a:"图片工具栏",b:"媒体工具栏",c:"表格工具栏",d:"Special characters",e:"块引用",f:"标题类型",g:"标题",h:"增加缩进",i:"减少缩进",j:"超链接",k:"编号列表",l:"项目列表",m:"媒体小部件",n:"插入媒体",o:"URL不可以为空。",p:"不支持此媒体URL。",q:"加粗",r:"倾斜",s:"代码",t:"删除线",u:"下划线",v:"图像小部件",w:"输入图片标题",x:"图片通栏显示",y:"图片侧边显示",z:"图片左侧对齐",aa:"图片居中",ab:"图片右侧对齐",ac:"插入图像",ad:"上传失败",ae:"小部件工具栏",af:"Table properties",ag:"移除格式",ah:"分割线",ai:"黄色标记",aj:"绿色标记",ak:"粉色标记",al:"蓝色标记",am:"红色笔",an:"绿色笔",ao:"清除高亮",ap:"高亮",aq:"文本高亮工具栏",ar:"正在上传",as:"插入代码块",at:"Character categories",au:"字体",av:"默认",aw:"字体大小",ax:"极小",ay:"小",az:"大",ba:"极大",bb:"字体颜色",bc:"字体背景色",bd:"更改图片替换文本",be:"下拉工具栏",bf:"移除颜色",bg:"文档中的颜色",bh:"保存",bi:"取消",bj:"替换文本",bk:"撤销",bl:"重做",bm:"第 %0 步,共 %1 步",bn:"上一步",bo:"下一步",bp:"编辑器工具栏",bq:"显示更多",br:"纯文本",bs:"黑色",bt:"暗灰色",bu:"灰色",bv:"浅灰色",bw:"白色",bx:"红色",by:"橙色",bz:"黄色",ca:"浅绿色",cb:"绿色",cc:"海蓝色",cd:"青色",ce:"浅蓝色",cf:"蓝色",cg:"紫色",ch:"None",ci:"Solid",cj:"Dotted",ck:"Dashed",cl:"Double",cm:"Groove",cn:"Ridge",co:"Inset",cp:"Outset",cq:"The color is invalid. Try \"#FF0000\" or \"rgb(255,0,0)\" or \"red\".",cr:"The value is invalid. Try \"10px\" or \"2em\" or simply \"2\".",cs:"Border",ct:"Style",cu:"Width",cv:"Color",cw:"Background",cx:"Dimensions",cy:"Height",cz:"Alignment",da:"Table alignment toolbar",db:"Align table to the left",dc:"Center table",dd:"Align table to the right",de:"在输入中粘贴媒体URL",df:"提示:将URL粘贴到内容中可更快地嵌入",dg:"媒体URL",dh:"在新标签页中打开",di:"可下载",dj:"取消超链接",dk:"修改链接",dl:"在新标签页中打开链接",dm:"此链接没有设置网址",dn:"链接网址",do:"段落",dp:"标题 1",dq:"标题 2",dr:"标题 3",ds:"标题 4",dt:"标题 5",du:"标题 6",dv:"左对齐",dw:"右对齐",dx:"居中",dy:"两端对齐",dz:"对齐",ea:"对齐工具栏",eb:"富文本编辑器, %0",ec:"插入表格",ed:"标题列",ee:"左侧插入列",ef:"右侧插入列",eg:"删除本列",eh:"列",ei:"标题行",ej:"在下面插入一行",ek:"在上面插入一行",el:"删除本行",em:"行",en:"向上合并单元格",eo:"向右合并单元格",ep:"向下合并单元格",eq:"向左合并单元格",er:"垂直拆分单元格",es:"水平分割单元格",et:"合并单元格"})})(window.CKEDITOR_TRANSLATIONS||(window.CKEDITOR_TRANSLATIONS={}));
|
'use strict';
/**
* Controller for Estado
**/
estadoModule.controller('EstadoCtrl', ['Estado', '$scope', '$routeParams', '$http', '$location', '$cookies', 'MessageHandler', 'restURL', function(Estado, $scope, $routeParams, $http, $location, $cookies, MessageHandler, restURL) {
// edition mode
$scope.mode = null;
// list of estados
$scope.estados = [];
// estado to edit
$scope.estado = null;
// referencies entities
$scope.items = {};
/**
* Load all referencies entities
*/
$scope.loadAllReferencies = function() {
};
/**
* Refresh estados list
*/
$scope.refreshEstadoList = function() {
try {
$scope.estados = [];
Estado.getAll().then(
function(success) {
$scope.estados = success.data;
},
MessageHandler.manageError);
} catch(ex) {
MessageHandler.manageException(ex);
}
}
/**
* Refresh estado
*/
$scope.refreshEstado = function(id) {
try {
$scope.estado = null;
Estado.get(id).then(
function(success) {
$scope.estado = success.data;
},
MessageHandler.manageError);
} catch(ex) {
MessageHandler.manageException(ex);
}
}
/**
* Go to the estados list page
*/
$scope.goToEstadoList = function() {
$scope.refreshEstadoList();
$location.path('/estado');
}
/**
* Go to the estado edit page
*/
$scope.goToEstado = function(id) {
$scope.refreshEstado(id);
$location.path('/estado/'+id);
}
// Actions
/**
* Save estado
*/
$scope.save = function() {
try {
MessageHandler.cleanMessage();
var save;
if( $scope.mode === 'create' ) {
save = Estado.create;
} else {
save = Estado.update;
}
save($scope.estado).then(
function(success) {
MessageHandler.addSuccess('save ok');
$scope.estado = success.data;
},
MessageHandler.manageError);
} catch(ex) {
MessageHandler.manageException(ex);
}
};
/**
* Delete estado
*/
$scope.delete = function(id) {
try {
MessageHandler.cleanMessage();
Estado.delete(id).then(
function(success) {
$scope.goToEstadoList();
},
MessageHandler.manageError);
} catch(ex) {
MessageHandler.manageException(ex);
}
};
// Main
MessageHandler.cleanMessage();
if( $location.path().endsWith('/new') ) {
// Creation page
$scope.estado = {};
$scope.mode = 'create';
$scope.loadAllReferencies();
$scope.bookorderitem = null;
} else if( $routeParams.id != null ) {
// Edit page
$scope.loadAllReferencies();
$scope.refreshEstado($routeParams.id);
} else {
// List page
$scope.refreshEstadoList();
}
}]);
|
import React from 'react';
const GithubIcon = () => {
return (
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path fill="currentColor" d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/>
</svg>
);
};
export default GithubIcon;
|
import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
const user = {
state: {
token: getToken(),
name: '',
avatar: '',
roles: [],
permissions: []
},
mutations: {
SET_TOKEN: (state, token) => {
state.token = token
},
SET_NAME: (state, name) => {
state.name = name
},
SET_AVATAR: (state, avatar) => {
state.avatar = avatar
},
SET_ROLES: (state, roles) => {
state.roles = roles
},
SET_PERMISSIONS: (state, permissions) => {
state.permissions = permissions
}
},
actions: {
// 登录
Login({ commit }, userInfo) {
const username = userInfo.username.trim()
const password = userInfo.password
const code = userInfo.code
const uuid = userInfo.uuid
return new Promise((resolve, reject) => {
login(username, password, code, uuid).then(res => {
res = res.data;
setToken(res.token)
commit('SET_TOKEN', res.token)
resolve()
}).catch(error => {
reject(error)
})
})
},
// 获取用户信息
GetInfo({ commit, state }) {
return new Promise((resolve, reject) => {
getInfo(state.token).then(res => {
res = res.data; // 读取 data 数据
const user = res.user
const avatar = user.avatar === "" ? require("@/assets/images/profile.jpg") : user.avatar;
if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
commit('SET_ROLES', res.roles)
commit('SET_PERMISSIONS', res.permissions)
} else {
commit('SET_ROLES', ['ROLE_DEFAULT'])
}
commit('SET_NAME', user.userName)
commit('SET_AVATAR', avatar)
resolve(res)
}).catch(error => {
reject(error)
})
})
},
// 退出系统
LogOut({ commit, state }) {
return new Promise((resolve, reject) => {
logout(state.token).then(() => {
commit('SET_TOKEN', '')
commit('SET_ROLES', [])
commit('SET_PERMISSIONS', [])
removeToken()
resolve()
}).catch(error => {
reject(error)
})
})
},
// 前端 登出
FedLogOut({ commit }) {
return new Promise(resolve => {
commit('SET_TOKEN', '')
removeToken()
resolve()
})
}
}
}
export default user
|
/// <reference types="Cypress" />
const md5 = require('blueimp-md5');
context('Layout widgets', () => {
before(() => {
cy.visit('http://localhost:3000/examples/components/vue-ncform/_layout-widgets.html')
})
it('layout:v & collapsed: false', () => {
let id = md5('layout:v & collapsed: false');
cy.get(`[data-cy=${id}]`).within(() => {
cy.get('legend').contains('user').as('userLegend');
cy.get('@userLegend').next().should('be.visible');
cy.get('@userLegend').next().then($dom => {
expect($dom.find('label').offset().top).to.be.lessThan($dom.find('input').offset().top);
expect($dom.find('label').offset().left).to.be.equal($dom.find('input').offset().left);
})
cy.get('@userLegend').click();
cy.get('@userLegend').next().should('not.be.visible');
})
})
it('layout:h & collapsed: true', () => {
let id = md5('layout:h & collapsed: true');
cy.get(`[data-cy=${id}]`).within(() => {
cy.get('legend').contains('user').as('userLegend');
cy.get('@userLegend').next().should('not.be.visible');
cy.get('@userLegend').click();
cy.get('@userLegend').next().should('be.visible');
cy.get('@userLegend').next().then($dom => {
expect($dom.find('label').offset().top).to.be.equal($dom.find('input').offset().top);
expect($dom.find('label').offset().left).to.be.lessThan($dom.find('input').offset().left);
})
})
})
it('disableCollapse: true', () => {
let id = md5('disableCollapse: true');
cy.get(`[data-cy=${id}]`).within(() => {
cy.get('legend').contains('user').as('userLegend');
cy.get('@userLegend').next().should('be.visible');
cy.get('@userLegend').click();
cy.get('@userLegend').next().should('be.visible');
})
})
it('array: all disableXXX are true', () => {
let id = md5('array: all disableXXX are true');
cy.get(`[data-cy=${id}]`).within(() => {
cy.get('legend').contains('user').as('userLegend');
cy.get('@userLegend').parent().children('div').should('be.visible');
cy.get('@userLegend').click();
cy.get('@userLegend').parent().children('div').should('be.visible');
cy.get('@userLegend').parent().find('button').should('not.exist');
})
})
it('array: some rows can not be deleted', () => {
let id = md5('array: some rows can not be deleted');
cy.get(`[data-cy=${id}]`).within(() => {
cy.get('legend').contains('user').as('userLegend');
cy.get('@userLegend').next().find('button.btn-danger').should('not.exist');
cy.get('@userLegend').next().next().find('button.btn-danger').should('exist');
})
})
it('array: collapsed / itemCollapse true and txts change', () => {
let id = md5('array: collapsed / itemCollapse true and txts change');
cy.get(`[data-cy=${id}]`).within(() => {
cy.get('legend').contains('user').as('userLegend');
cy.get('@userLegend').parent().children('div').should('not.be.visible');
cy.get('@userLegend').click();
cy.get('@userLegend').parent().children('div').should('be.visible');
cy.get('@userLegend').parent().find('input').should('not.be.visible');
cy.get('@userLegend').parent().find('button').contains('Expand').click();
cy.get('@userLegend').parent().find('input').should('be.visible');
cy.get('@userLegend').parent().find('button').contains('Add Item').should('exist');
cy.get('@userLegend').parent().find('button').contains('Remove All').should('exist');
})
})
it('table: all disableXXX are true', () => {
let id = md5('table: all disableXXX are true');
cy.get(`[data-cy=${id}]`).within(() => {
cy.get('legend').contains('user').as('userLegend');
cy.get('@userLegend').next().should('be.visible');
cy.get('@userLegend').click();
cy.get('@userLegend').next().should('be.visible');
cy.get('@userLegend').next().find('button').should('not.exist');
})
})
it('table: collapsed true and txts change', () => {
let id = md5('table: collapsed true and txts change');
cy.get(`[data-cy=${id}]`).within(() => {
cy.get('legend').contains('user').as('userLegend');
cy.get('@userLegend').next().should('not.be.visible');
cy.get('@userLegend').click();
cy.get('@userLegend').next().should('be.visible');
cy.get('@userLegend').next().find('button').contains('Add Item').should('exist');
cy.get('@userLegend').next().find('button').contains('Remove All').should('exist');
})
})
it('table: some rows can be deleted', () => {
let id = md5('table: some rows can be deleted');
cy.get(`[data-cy=${id}]`).within(() => {
cy.get('legend').contains('user').as('userLegend');
cy.get('@userLegend').next().find('button.btn-danger').should('have.length', 1);
})
})
it('table: set colums width', () => {
let id = md5('table: set colums width');
cy.get(`[data-cy=${id}]`).within(() => {
cy.get('thead th:last-child').should('have.prop', 'offsetWidth', 200);
})
})
it('array: showOneIfEmpty is true - No extra blank row when there has initial value', () => {
let id = md5('array: showOneIfEmpty is true - No extra blank row when there has initial value');
cy.get(`[data-cy=${id}]`).within(() => {
cy.get('input').should('have.length', 1);
})
})
})
|
module.exports = function toReadable(number) {
let units = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
let tens = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
if (number === 0) {
return 'zero'
}
else if (number > 0 && number < 20) {
return units[number - 1]
}
else if (number >= 20 && number < 100) {
let ten = +number.toString().split('')[0]
let unit = +number.toString().split('')[1]
if (unit != 0) {
return tens[ten - 2] + " " + units[unit - 1]
} else {
return tens[ten - 2]
}
}
else {
let hundred = +number.toString().split('')[0]
let ten = +number.toString().split('')[1]
let unit = +number.toString().split('')[2]
let combined = parseInt(ten.toString() + unit.toString())
if (unit === 0) {
if (ten === 0 && unit === 0) {
return units[hundred - 1] + " hundred"
}
else if (ten === 1 && unit === 0) {
return units[hundred - 1] + " hundred" + " ten"
}
else {
return units[hundred - 1] + " hundred " + tens[ten - 2]
}
}
else if (ten === 0) {
return units[hundred - 1] + " hundred " + units[unit - 1]
}
else if (ten === 1) {
return units[hundred - 1] + " hundred " + units[combined - 1]
}
else {
return units[hundred - 1] + " hundred " + tens[ten - 2] + " " + units[unit - 1]
}
}
}
|
/**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {CONFIGURATION_EVENT, ORIGIN, SHARE_EVENT} from './constants';
import {getData} from '../../../src/event-helper';
import {isObject} from '../../../src/types';
import {startsWith} from '../../../src/string';
import {tryParseJson} from '../../../src/json';
export class PostMessageDispatcher {
/**
* Creates an instance of PostMessageDispatcher.
*/
constructor() {
this.listeners_ = {};
}
/**
* Adds event listener.
* @param {string} eventType
* @param {!Function} listener
*/
on(eventType, listener) {
if (!this.listeners_[eventType]) {
this.listeners_[eventType] = [];
}
this.listeners_[eventType].push(listener);
}
/**
* @param {string} eventType
* @param {!Object} eventData
* @private
*/
emit_(eventType, eventData) {
if (!this.listeners_[eventType]) {
return;
}
this.listeners_[eventType].forEach(listener => listener(eventData));
}
/**
* Utility method to parse out the data from the supplied `postMessage` event.
* @param {!Event} event
* @private
*/
getMessageData_(event) {
const data = getData(event);
if (isObject(data)) {
return data;
}
if (typeof data === 'string' && startsWith(data, '{')) {
return tryParseJson(data);
}
return undefined;
}
/**
* Handles messages posted from amp-addthis iframes, ensuring the correct
* origin, etc.
* @param {!Event} event
*/
handleAddThisMessage(event) {
if (event.origin !== ORIGIN || !getData(event)) {
return;
}
const data = this.getMessageData_(event) || {};
switch (data.event) {
case CONFIGURATION_EVENT: {
this.emit_(
CONFIGURATION_EVENT,
Object.assign({}, data, {source: event.source})
);
break;
}
case SHARE_EVENT: {
this.emit_(SHARE_EVENT, data);
break;
}
}
}
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Redis = require('ioredis');
var RedisDatabase = (function () {
function RedisDatabase(options) {
this.options = options;
if (options.databaseConfig.redis.nodes && options.databaseConfig.redis.nodes.length != 0) {
this._redis = new Redis.Cluster(options.databaseConfig.redis.nodes, options.databaseConfig.redis.options);
}
else {
this._redis = new Redis(options.databaseConfig.redis);
}
}
RedisDatabase.prototype.get = function (key) {
var _this = this;
return new Promise(function (resolve, reject) {
_this._redis.get(key).then(function (value) { return resolve(JSON.parse(value)); });
});
};
RedisDatabase.prototype.set = function (key, value) {
this._redis.set(key, JSON.stringify(value));
if (this.options.databaseConfig.publishPresence === true && /^presence-.*:members$/.test(key)) {
this._redis.publish('PresenceChannelUpdated', JSON.stringify({
"event": {
"channel": key,
"members": value
}
}));
}
};
return RedisDatabase;
}());
exports.RedisDatabase = RedisDatabase;
|
import userIsLoggedIn from '../utils/userIsLoggedIn';
const initialState = {
auth: {
isAuthenticated: userIsLoggedIn(),
user: {},
},
users: {
signingIn: false,
error: '',
},
rides: {
rideOffers: [],
loadingRides: false,
error: '',
},
offerRide: {
loading: false,
error: {},
data: {},
},
myRides: {
loading: false,
error: '',
data: [],
},
requests: {
loading: false,
error: '',
rideInfo: {
data: {},
error: '',
},
requestInfo: {
data: [],
error: '',
},
requestResponseLoading: false,
},
profile: {
ridesOffered: {
data: [],
loading: false,
error: '',
},
ridesJoined: {
data: [],
loading: false,
error: '',
},
},
};
export default initialState;
|
'use strict';
var _16 = {
elem: 'svg',
attrs: {
xmlns: 'http://www.w3.org/2000/svg',
viewBox: '0 0 32 32',
width: 16,
height: 16,
},
content: [
{
elem: 'path',
attrs: {
d: 'M11 18l1.41 1.41L15 16.83V29h2V16.83l2.59 2.58L21 18l-5-5-5 5z',
},
},
{
elem: 'path',
attrs: {
d:
'M23.5 22H23v-2h.5a4.5 4.5 0 0 0 .36-9H23l-.1-.82a7 7 0 0 0-13.88 0L9 11h-.86a4.5 4.5 0 0 0 .36 9H9v2h-.5A6.5 6.5 0 0 1 7.2 9.14a9 9 0 0 1 17.6 0A6.5 6.5 0 0 1 23.5 22z',
},
},
],
name: 'cloud--upload',
size: 16,
};
module.exports = _16;
|
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles((theme) => ({
img: {
height: 240,
display: "block",
maxWidth: 400,
overflow: "hidden",
width: "100%",
},
imgRest: {
height: 360,
display: "block",
maxWidth: 500,
overflow: "hidden",
width: "100%",
borderRadius: "5%",
},
buttonLeft: {
position: "relative",
top: "-132px",
left: "-4%",
color: "white",
},
buttonRight: {
position: "relative",
top: "-132px",
right: "-62%",
color: "white",
},
buttonRightRest: {
right: "-72.5%",
},
}));
function SwipeableImages(props) {
const classes = useStyles();
const imagesArray = props.images;
let newImagesArray;
newImagesArray = imagesArray.map((image) => {
const imageUrlSplit = image.split("\\");
const imageUrl = imageUrlSplit[0] + "/" + imageUrlSplit[1];
return `${process.env.REACT_APP_SERVER_URL}/${imageUrl}`;
});
return (
<>
<div>
{newImagesArray.map((step, index) => (
<div key={step}>
<img
className={
props.type === "home" ? classes.img : classes.imgRest
}
src={step}
alt={step}
/>
</div>
))}
</div>
</>
);
}
export default SwipeableImages;
|
"use strict";module.exports=function(i){require("source-map-support").install();var n=require("modbus-serial"),u=require("./core/modbus-server-core"),d=require("./modbus-basics"),c=require("debug")("contribModbus:flex:server");try{i.nodes.registerType("modbus-flex-server",function(e){i.nodes.createNode(this,e);var r=(s=require("vm2")).VM,s=s.VMScript;this.name=e.name,this.logEnabled=e.logEnabled,this.serverAddress=e.serverAddress||"0.0.0.0",this.serverPort=parseInt(e.serverPort),this.responseDelay=parseInt(e.responseDelay),this.delayUnit=e.delayUnit,this.unitId=parseInt(e.unitId)||1,this.minAddress=parseInt(e.minAddress)||0,this.splitAddress=parseInt(e.splitAddress)||1e4,this.showErrors=e.showErrors,this.funcGetCoil=new s(e.funcGetCoil).compile(),this.funcGetDiscreteInput=new s(e.funcGetDiscreteInput).compile(),this.funcGetInputRegister=new s(e.funcGetInputRegister).compile(),this.funcGetHoldingRegister=new s(e.funcGetHoldingRegister).compile(),this.funcSetCoil=new s(e.funcSetCoil).compile(),this.funcSetRegister=new s(e.funcSetRegister).compile(),this.internalDebugLog=c,this.verboseLogging=i.settings.verbose;var t=this;function o(e){return[{type:"holding",message:e,payload:t.registers.slice(t.splitAddress*u.bufferFactor)},{type:"coils",message:e,payload:t.coils.slice(0,t.splitAddress*u.bufferFactor)},{type:"input",message:e,payload:t.registers.slice(0,t.splitAddress*u.bufferFactor)},{type:"discrete",message:e,payload:t.coils.slice(t.splitAddress*u.bufferFactor)},{payload:"request",type:"message",message:e}]}t.bufferFactor=u.bufferFactor,t.coilsBufferSize=parseInt(e.coilsBufferSize*u.bufferFactor),t.registersBufferSize=parseInt(e.registersBufferSize*u.bufferFactor),t.coils=Buffer.alloc(t.coilsBufferSize,0),t.registers=Buffer.alloc(t.registersBufferSize,0),t.modbusServer=null,d.setNodeStatusTo("initialized",t),t.vector={},(r=new r({sandbox:{node:t}})).run("node.vector.getCoil = "+e.funcGetCoil),r.run("node.vector.getDiscreteInput = "+e.funcGetDiscreteInput),r.run("node.vector.getInputRegister = "+e.funcGetInputRegister),r.run("node.vector.getHoldingRegister = "+e.funcGetHoldingRegister),r.run("node.vector.setCoil = "+e.funcSetCoil),r.run("node.vector.setRegister = "+e.funcSetRegister),t.startServer=function(){try{if(null===t.modbusServer){try{t.modbusServer=new n.ServerTCP(t.vector,{host:t.serverAddress,port:t.serverPort,debug:t.logEnabled,unitID:t.unitId})}catch(e){t.error(e,{payload:"server net error -> for port 502 on unix, you have to be a super user"})}t.modbusServer.on("socketError",function(e){c(e.message),t.showErrors&&t.warn(e),d.setNodeStatusTo("error",t),t.modbusServer.close(function(){t.startServer()})}),t.modbusServer._server.on("connection",function(e){c("Modbus Flex Server client connection"),e&&c("Modbus Flex Server client to "+JSON.stringify(e.address())+" from "+e.remoteAddress+" "+e.remotePort),d.setNodeStatusTo("active",t)})}t.showStatusActivities||d.setNodeDefaultStatus(t)}catch(e){c(e.message),t.showErrors&&t.warn(e),d.setNodeStatusTo("error",t)}null!=t.modbusServer?(c("Modbus Flex Server listening on modbus://"+t.serverAddress+":"+t.serverPort),d.setNodeStatusTo("initialized",t)):(c("Modbus Flex Server isn't ready"),d.setNodeStatusTo("error",t))},t.startServer(),t.on("input",function(e){u.isValidMemoryMessage(e)?(u.writeToFlexServerMemory(t,e),1!==e.payload.disableMsgOutput&&t.send(o(e))):(t.showErrors&&t.error("Is Not A Valid Memory Write Message To Server",e),e.payload.disableMsgOutput||t.send(o(e)))}),t.on("close",function(){d.setNodeStatusTo("closed",t),t.modbusServer._server&&t.modbusServer._server.close(),t.modbusServer&&t.modbusServer.close(),t.modbusServer=null})})}catch(e){c(e.message)}};
//# sourceMappingURL=maps/modbus-flex-server.js.map
|
const Buffer = require('safe-buffer').Buffer
const async = require('async')
const ethUtil = require('ethereumjs-util')
const BN = ethUtil.BN
const fees = require('ethereum-common')
const exceptions = require('./exceptions.js')
const ERROR = exceptions.ERROR
/**
* runs a CALL operation
* @method runCall
* @param opts
* @param opts.block {Block}
* @param opts.caller {Buffer}
* @param opts.code {Buffer} this is for CALLCODE where the code to load is different than the code from the to account.
* @param opts.data {Buffer}
* @param opts.gasLimit {Buffer | BN.js }
* @param opts.gasPrice {Buffer}
* @param opts.origin {Buffer} []
* @param opts.to {Buffer}
* @param opts.value {Buffer}
*/
module.exports = function (opts, cb) {
var self = this
var stateManager = self.stateManager
var vmResults = {}
var toAccount
var toAddress = opts.to
var createdAddress
var txValue = opts.value || Buffer.from([0])
var caller = opts.caller
var account = stateManager.cache.get(caller)
var block = opts.block
var code = opts.code
var txData = opts.data
var gasLimit = opts.gasLimit || new BN(0xffffff)
gasLimit = new BN(opts.gasLimit) // make sure is a BN
var gasPrice = opts.gasPrice
var gasUsed = new BN(0)
var origin = opts.origin
var isCompiled = opts.compiled
var depth = opts.depth
// opts.suicides is kept for backward compatiblity with pre-EIP6 syntax
var selfdestruct = opts.selfdestruct || opts.suicides
var delegatecall = opts.delegatecall || false
var isStatic = opts.static || false
txValue = new BN(txValue)
stateManager.checkpoint()
// run and parse
subTxValue()
async.series([
loadToAccount,
loadCode,
runCode,
saveCode
], parseCallResult)
function loadToAccount (done) {
// get receiver's account
// toAccount = stateManager.cache.get(toAddress)
if (!toAddress) {
// generate a new contract if no `to`
code = txData
txData = undefined
var newNonce = new BN(account.nonce).subn(1)
createdAddress = toAddress = ethUtil.generateAddress(caller, newNonce.toArray())
stateManager.getAccount(createdAddress, function (err, account) {
toAccount = account
const NONCE_OFFSET = 1
toAccount.nonce = new BN(toAccount.nonce).addn(NONCE_OFFSET).toArrayLike(Buffer)
done(err)
})
} else {
// else load the `to` account
toAccount = stateManager.cache.get(toAddress)
done()
}
}
function subTxValue () {
if (delegatecall) {
return
}
account.balance = new BN(account.balance).sub(txValue)
stateManager.cache.put(caller, account)
}
function addTxValue () {
if (delegatecall) {
return
}
// add the amount sent to the `to` account
toAccount.balance = new BN(toAccount.balance).add(txValue)
stateManager.cache.put(toAddress, toAccount)
stateManager.touched.push(toAddress)
}
function loadCode (cb) {
addTxValue()
// loads the contract's code if the account is a contract
if (code || !(toAccount.isContract() || self._precompiled[toAddress.toString('hex')])) {
cb()
return
}
if (self._precompiled[toAddress.toString('hex')]) {
isCompiled = true
code = self._precompiled[toAddress.toString('hex')]
cb()
return
}
stateManager.getContractCode(toAddress, function (err, c, comp) {
if (err) return cb(err)
isCompiled = comp
code = c
cb()
})
}
function runCode (cb) {
if (!code) {
vmResults.exception = 1
stateManager.commit(cb)
return
}
var runCodeOpts = {
code: code,
data: txData,
gasLimit: gasLimit,
gasPrice: gasPrice,
address: toAddress,
origin: origin,
caller: caller,
value: txValue.toArrayLike(Buffer),
block: block,
depth: depth,
selfdestruct: selfdestruct,
populateCache: false,
static: isStatic
}
// run Code through vm
var codeRunner = isCompiled ? self.runJIT : self.runCode
codeRunner.call(self, runCodeOpts, parseRunResult)
function parseRunResult (err, results) {
toAccount = self.stateManager.cache.get(toAddress)
vmResults = results
if (createdAddress) {
// fee for size of the return value
var totalGas = results.gasUsed
if (!results.runState.vmError) {
var returnFee = results.return.length * fees.createDataGas.v
// avoid BN assertion failure when returnFee is greater than 0x4000000
if (returnFee > gasLimit.toNumber()) {
returnFee = gasLimit.toNumber() + 1
}
totalGas = totalGas.addn(returnFee)
}
// if not enough gas
if (totalGas.lte(gasLimit) && results.return.length <= 24576) {
results.gasUsed = totalGas
} else {
results.return = Buffer.alloc(0)
// since Homestead
results.exception = 0
err = results.exceptionError = ERROR.OUT_OF_GAS
results.gasUsed = gasLimit
}
}
gasUsed = results.gasUsed
if (err) {
results.logs = []
stateManager.revert(cb)
} else {
stateManager.commit(cb)
}
}
}
function saveCode (cb) {
// store code for a new contract
if (createdAddress && !vmResults.runState.vmError && vmResults.return && vmResults.return.toString() !== '') {
stateManager.putContractCode(createdAddress, vmResults.return, cb)
} else {
cb()
}
}
function parseCallResult (err) {
if (err) return cb(err)
var results = {
gasUsed: gasUsed,
createdAddress: createdAddress,
vm: vmResults
}
cb(null, results)
}
}
|
/*************************************************************
*
* MathJax/jax/output/HTML-CSS/fonts/STIX/General/BoldItalic/BasicLatin.js
*
* Copyright (c) 2009-2017 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
MathJax.Hub.Insert(
MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['STIXGeneral-bold-italic'],
{
0x20: [0,0,250,0,0], // SPACE
0x21: [684,13,389,67,370], // EXCLAMATION MARK
0x22: [685,-398,555,136,536], // QUOTATION MARK
0x23: [700,0,500,-32,532], // NUMBER SIGN
0x24: [733,100,500,-20,497], // DOLLAR SIGN
0x25: [706,29,757,80,707], // PERCENT SIGN
0x26: [682,19,849,76,771], // AMPERSAND
0x27: [685,-398,278,128,268], // APOSTROPHE
0x28: [685,179,333,28,344], // LEFT PARENTHESIS
0x29: [685,179,333,-44,271], // RIGHT PARENTHESIS
0x2A: [685,-252,500,101,492], // ASTERISK
0x2B: [506,0,570,33,537], // PLUS SIGN
0x2C: [134,182,250,-60,144], // COMMA
0x2D: [282,-166,333,2,271], // HYPHEN-MINUS
0x2E: [135,13,250,-9,139], // FULL STOP
0x2F: [685,18,278,-64,342], // SOLIDUS
0x30: [683,14,500,17,477], // DIGIT ZERO
0x31: [683,0,500,5,419], // DIGIT ONE
0x32: [683,0,500,-27,446], // DIGIT TWO
0x33: [683,13,500,-14,450], // DIGIT THREE
0x34: [683,0,500,-15,503], // DIGIT FOUR
0x35: [669,13,500,-11,486], // DIGIT FIVE
0x36: [679,15,500,23,509], // DIGIT SIX
0x37: [669,0,500,52,525], // DIGIT SEVEN
0x38: [683,13,500,3,476], // DIGIT EIGHT
0x39: [683,10,500,-12,475], // DIGIT NINE
0x3A: [459,13,333,23,264], // COLON
0x3B: [459,183,333,-25,264], // SEMICOLON
0x3C: [518,12,570,31,539], // LESS-THAN SIGN
0x3D: [399,-107,570,33,537], // EQUALS SIGN
0x3E: [518,12,570,31,539], // GREATER-THAN SIGN
0x3F: [684,13,500,79,470], // QUESTION MARK
0x40: [685,18,939,118,825], // COMMERCIAL AT
0x41: [683,0,667,-68,593], // LATIN CAPITAL LETTER A
0x42: [669,0,667,-25,624], // LATIN CAPITAL LETTER B
0x43: [685,18,667,32,677], // LATIN CAPITAL LETTER C
0x44: [669,0,722,-46,685], // LATIN CAPITAL LETTER D
0x45: [669,0,667,-27,653], // LATIN CAPITAL LETTER E
0x46: [669,0,667,-13,660], // LATIN CAPITAL LETTER F
0x47: [685,18,722,21,705], // LATIN CAPITAL LETTER G
0x48: [669,0,778,-24,799], // LATIN CAPITAL LETTER H
0x49: [669,0,389,-32,406], // LATIN CAPITAL LETTER I
0x4A: [669,99,500,-46,524], // LATIN CAPITAL LETTER J
0x4B: [669,0,667,-21,702], // LATIN CAPITAL LETTER K
0x4C: [669,0,611,-22,590], // LATIN CAPITAL LETTER L
0x4D: [669,12,889,-29,917], // LATIN CAPITAL LETTER M
0x4E: [669,15,722,-27,748], // LATIN CAPITAL LETTER N
0x4F: [685,18,722,27,691], // LATIN CAPITAL LETTER O
0x50: [669,0,611,-28,613], // LATIN CAPITAL LETTER P
0x51: [685,208,722,27,691], // LATIN CAPITAL LETTER Q
0x52: [669,0,667,-28,623], // LATIN CAPITAL LETTER R
0x53: [685,18,556,2,526], // LATIN CAPITAL LETTER S
0x54: [669,0,611,49,650], // LATIN CAPITAL LETTER T
0x55: [669,18,722,67,744], // LATIN CAPITAL LETTER U
0x56: [669,18,667,66,715], // LATIN CAPITAL LETTER V
0x57: [669,18,889,64,940], // LATIN CAPITAL LETTER W
0x58: [669,0,667,-24,694], // LATIN CAPITAL LETTER X
0x59: [669,0,611,71,659], // LATIN CAPITAL LETTER Y
0x5A: [669,0,611,-12,589], // LATIN CAPITAL LETTER Z
0x5B: [674,159,333,-37,362], // LEFT SQUARE BRACKET
0x5C: [685,18,278,-1,279], // REVERSE SOLIDUS
0x5D: [674,157,333,-56,343], // RIGHT SQUARE BRACKET
0x5E: [669,-304,570,67,503], // CIRCUMFLEX ACCENT
0x5F: [-75,125,500,0,500], // LOW LINE
0x60: [697,-516,333,85,297], // GRAVE ACCENT
0x61: [462,14,500,-21,456], // LATIN SMALL LETTER A
0x62: [699,13,500,-14,444], // LATIN SMALL LETTER B
0x63: [462,13,444,-5,392], // LATIN SMALL LETTER C
0x64: [699,13,500,-21,517], // LATIN SMALL LETTER D
0x65: [462,13,444,5,398], // LATIN SMALL LETTER E
0x66: [698,205,333,-169,446], // LATIN SMALL LETTER F
0x67: [462,203,500,-52,477], // LATIN SMALL LETTER G
0x68: [699,9,556,-13,498], // LATIN SMALL LETTER H
0x69: [684,9,278,2,262], // LATIN SMALL LETTER I
0x6A: [685,207,278,-189,279], // LATIN SMALL LETTER J
0x6B: [699,8,500,-23,483], // LATIN SMALL LETTER K
0x6C: [699,9,278,2,290], // LATIN SMALL LETTER L
0x6D: [462,9,778,-14,723], // LATIN SMALL LETTER M
0x6E: [462,9,556,-6,494], // LATIN SMALL LETTER N
0x6F: [462,13,500,-3,441], // LATIN SMALL LETTER O
0x70: [462,205,500,-120,446], // LATIN SMALL LETTER P
0x71: [462,205,500,1,471], // LATIN SMALL LETTER Q
0x72: [462,0,389,-21,389], // LATIN SMALL LETTER R
0x73: [462,13,389,-19,333], // LATIN SMALL LETTER S
0x74: [594,9,278,-11,281], // LATIN SMALL LETTER T
0x75: [462,9,556,15,493], // LATIN SMALL LETTER U
0x76: [462,13,444,15,401], // LATIN SMALL LETTER V
0x77: [462,13,667,15,614], // LATIN SMALL LETTER W
0x78: [462,13,500,-45,469], // LATIN SMALL LETTER X
0x79: [462,205,444,-94,392], // LATIN SMALL LETTER Y
0x7A: [449,78,389,-43,368], // LATIN SMALL LETTER Z
0x7B: [686,187,348,4,436], // LEFT CURLY BRACKET
0x7C: [685,18,220,66,154], // VERTICAL LINE
0x7D: [686,187,348,-129,303], // RIGHT CURLY BRACKET
0x7E: [331,-175,570,54,516] // TILDE
}
);
MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir + "/General/BoldItalic/BasicLatin.js");
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
var BitmapText = require('./BitmapText');
var GameObjectFactory = require('../../GameObjectFactory');
/**
* Creates a new Bitmap Text Game Object and adds it to the Scene.
*
* Note: This method will only be available if the Bitmap Text Game Object has been built into Phaser.
*
* @method Phaser.GameObjects.GameObjectFactory#bitmapText
* @since 3.0.0
*
* @param {number} x - The x position of the Game Object.
* @param {number} y - The y position of the Game Object.
* @param {string} font - [description]
* @param {string|string[]} [text] - [description]
* @param {number} [size] - [description]
*
* @return {Phaser.GameObjects.BitmapText} The Game Object that was created.
*/
GameObjectFactory.register('bitmapText', function (x, y, font, text, size)
{
return this.displayList.add(new BitmapText(this.scene, x, y, font, text, size));
});
// When registering a factory function 'this' refers to the GameObjectFactory context.
//
// There are several properties available to use:
//
// this.scene - a reference to the Scene that owns the GameObjectFactory
// this.displayList - a reference to the Display List the Scene owns
// this.updateList - a reference to the Update List the Scene owns
|
import React, { useState, useEffect, useMemo } from 'react';
import PropTypes from 'prop-types';
import { IntlProvider } from 'react-intl';
import { setRTL } from '@fluentui/react';
import { APP_LOCALES, importMessages } from '../../i18n/i18n';
import { polyfillDisplayNames } from './polyfillDisplayNames';
const LocaleContext = React.createContext();
function LocaleProvider(props) {
const { locale: initialLocale } = props;
const [locale, setLocale] = useState(initialLocale);
const [appLanguages, setAppLanguages] = useState([]);
const [messages, setMessages] = useState(null);
useEffect(() => {
async function loadMessages(locale) {
const messages = await importMessages(locale);
setMessages(messages.default);
}
async function getAppLanguages(locale) {
await polyfillDisplayNames(locale);
const languages = APP_LOCALES.map((appLocale) => {
const displayNames = new Intl.DisplayNames(appLocale, {
type: 'language',
});
return { key: appLocale, text: displayNames.of(appLocale) };
});
setAppLanguages(languages);
}
setRTL(getIsRTL(locale));
getAppLanguages(locale);
loadMessages(locale);
}, [locale]);
const context = useMemo(() => {
return {
locale,
appLanguages,
setLocale,
};
}, [locale, appLanguages, setLocale]);
return (
messages && (
<IntlProvider locale={locale} messages={messages}>
<LocaleContext.Provider value={context} {...props} />
</IntlProvider>
)
);
}
LocaleProvider.propTypes = {
/**
* Initial locale
*/
locale: PropTypes.string.isRequired,
};
function useLocale() {
const context = React.useContext(LocaleContext);
if (!context) {
throw new Error(`useLocale must be used within a LocaleProvider`);
}
return context;
}
function getIsRTL(locale) {
const lang = locale.slice(0, 2);
const isRTL = lang === 'he' || lang === 'ar';
return isRTL;
}
export { LocaleProvider, useLocale };
|
function KeyboardInputManager() {
this.events = {};
if (window.navigator.msPointerEnabled) {
//Internet Explorer 10 style
this.eventTouchstart = "MSPointerDown";
this.eventTouchmove = "MSPointerMove";
this.eventTouchend = "MSPointerUp";
} else {
this.eventTouchstart = "touchstart";
this.eventTouchmove = "touchmove";
this.eventTouchend = "touchend";
}
this.listen();
}
KeyboardInputManager.prototype.on = function (event, callback) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(callback);
};
KeyboardInputManager.prototype.emit = function (event, data) {
var callbacks = this.events[event];
if (callbacks) {
callbacks.forEach(function (callback) {
callback(data);
});
}
};
KeyboardInputManager.prototype.listen = function () {
var self = this;
var map = {
38: 0, // Up
39: 1, // Right
40: 2, // Down
37: 3, // Left
75: 0, // Vim up
76: 1, // Vim right
74: 2, // Vim down
72: 3, // Vim left
87: 0, // W up
68: 1, // D
83: 2, // S
65: 3, // A
89: 0,
72: 2,
71: 3,
74: 1
};
// Respond to direction keys
document.addEventListener("keydown", function (event) {
var modifiers = event.altKey || event.ctrlKey || event.metaKey ||
event.shiftKey;
var mapped = map[event.which];
if (!modifiers) {
if (mapped !== undefined) {
event.preventDefault();
self.emit("move", mapped);
}
}
// R key restarts the game
if (!modifiers && event.which === 82) {
self.restart.call(self, event);
}
});
// Respond to button presses
this.bindButtonPress(".retry-button", this.restart);
this.bindButtonPress(".restart-button", this.restart);
this.bindButtonPress(".keep-playing-button", this.keepPlaying);
// Respond to swipe events
var touchStartClientX, touchStartClientY;
var gameContainer = document.getElementsByClassName("game-container")[0];
gameContainer.addEventListener(this.eventTouchstart, function (event) {
if ((!window.navigator.msPointerEnabled && event.touches.length > 1) ||
event.targetTouches.length > 1) {
return; // Ignore if touching with more than 1 finger
}
if (window.navigator.msPointerEnabled) {
touchStartClientX = event.pageX;
touchStartClientY = event.pageY;
} else {
touchStartClientX = event.touches[0].clientX;
touchStartClientY = event.touches[0].clientY;
}
event.preventDefault();
});
gameContainer.addEventListener(this.eventTouchmove, function (event) {
event.preventDefault();
});
gameContainer.addEventListener(this.eventTouchend, function (event) {
if ((!window.navigator.msPointerEnabled && event.touches.length > 0) ||
event.targetTouches.length > 0) {
return; // Ignore if still touching with one or more fingers
}
var touchEndClientX, touchEndClientY;
if (window.navigator.msPointerEnabled) {
touchEndClientX = event.pageX;
touchEndClientY = event.pageY;
} else {
touchEndClientX = event.changedTouches[0].clientX;
touchEndClientY = event.changedTouches[0].clientY;
}
var dx = touchEndClientX - touchStartClientX;
var absDx = Math.abs(dx);
var dy = touchEndClientY - touchStartClientY;
var absDy = Math.abs(dy);
if (Math.max(absDx, absDy) > 10) {
// (right : left) : (down : up)
self.emit("move", absDx > absDy ? (dx > 0 ? 1 : 3) : (dy > 0 ? 2 : 0));
}
});
};
KeyboardInputManager.prototype.restart = function (event) {
event.preventDefault();
this.emit("restart");
};
KeyboardInputManager.prototype.keepPlaying = function (event) {
event.preventDefault();
this.emit("keepPlaying");
};
KeyboardInputManager.prototype.bindButtonPress = function (selector, fn) {
var button = document.querySelector(selector);
button.addEventListener("click", fn.bind(this));
button.addEventListener(this.eventTouchend, fn.bind(this));
};
|
import { animationstart, fastdom, getStyle, on, toMs } from '../util/index';
import Accordion from './accordion';
import Alert from './alert';
import Cover from './cover';
import Drop from './drop';
import Dropdown from './dropdown';
import FormCustom from './form-custom';
import Gif from './gif';
import Grid from './grid';
import HeightMatch from './height-match';
import HeightViewport from './height-viewport';
import Hover from './hover';
import Icon from './icon';
import Margin from './margin';
import Modal from './modal';
import Nav from './nav';
import Navbar from './navbar';
import Offcanvas from './offcanvas';
import Responsive from './responsive';
import Scroll from './scroll';
import Scrollspy from './scrollspy';
import ScrollspyNav from './scrollspy-nav';
import Sticky from './sticky';
import Svg from './svg';
import Switcher from './switcher';
import Tab from './tab';
import Toggle from './toggle';
import Leader from './leader';
export default function (UIkit) {
var scroll = 0, started = 0;
on(window, 'load resize', UIkit.update);
on(window, 'scroll', e => {
e.dir = scroll < window.pageYOffset ? 'down' : 'up';
scroll = window.pageYOffset;
UIkit.update(e);
fastdom.flush();
});
on(document, animationstart, ({target}) => {
if ((getStyle(target, 'animationName') || '').match(/^uk-.*(left|right)/)) {
started++;
document.body.style.overflowX = 'hidden';
setTimeout(() => {
if (!--started) {
document.body.style.overflowX = '';
}
}, toMs(getStyle(target, 'animationDuration')) + 100);
}
}, true);
// core components
UIkit.use(Toggle);
UIkit.use(Accordion);
UIkit.use(Alert);
UIkit.use(Cover);
UIkit.use(Drop);
UIkit.use(Dropdown);
UIkit.use(FormCustom);
UIkit.use(HeightMatch);
UIkit.use(HeightViewport);
UIkit.use(Hover);
UIkit.use(Margin);
UIkit.use(Gif);
UIkit.use(Grid);
UIkit.use(Leader);
UIkit.use(Modal);
UIkit.use(Nav);
UIkit.use(Navbar);
UIkit.use(Offcanvas);
UIkit.use(Responsive);
UIkit.use(Scroll);
UIkit.use(Scrollspy);
UIkit.use(ScrollspyNav);
UIkit.use(Sticky);
UIkit.use(Svg);
UIkit.use(Icon);
UIkit.use(Switcher);
UIkit.use(Tab);
}
|
window.zEmbed || function (e, t) {
var n, o, d, i, s, a = [], r = document.createElement("iframe");
window.zEmbed = function () {
a.push(arguments)
}, window.zE = window.zE || window.zEmbed, r.src = "javascript:false", r.title = "", r.role = "presentation", (r.frameElement || r).style.cssText = "display: none", d = document.getElementsByTagName("script"), d = d[d.length - 1], d.parentNode.insertBefore(r, d), i = r.contentWindow, s = i.document;
try {
o = s
} catch (e) {
n = document.domain, r.src = 'javascript:var d=document.open();d.domain="' + n + '";void(0);', o = s
}
o.open()._l = function () {
var e = this.createElement("script");
n && (this.domain = n), e.id = "js-iframe-async", e.src = "https://assets.zendesk.com/embeddable_framework/main.js", this.t = +new Date, this.zendeskHost = "prx.zendesk.com", this.zEQueue = a, this.body.appendChild(e)
}, o.write('<body onload="document._l();">'), o.close()
}();
window.zESettings = {
webWidget: {
// https://developer.zendesk.com/embeddables/docs/widget/api
// is possible to set positioning and offset to top right but cannot configure button padding
color: {
theme: '#0089bd'
}
}
};
|
(window.webpackJsonpFileIcons=window.webpackJsonpFileIcons||[]).push([[224],{320:function(q){q.exports={viewBox:"0 0 1024 1024",font:"file-icons",code:"e925",ref:"apple",path:"M925 798q-11 27-25 51.5T870 897q-22 31-39.5 52.5T799 983q-21 19-44 29t-47 11q-17 0-38.5-5t-45.5-15q-25-10-47.5-15t-43.5-5q-21 0-44.5 5t-48.5 15q-25 10-45 15t-36 6q-23 1-46-9.5T266 983q-15-13-33.5-35.5T192 894q-24-34-43.5-72.5T114 738q-17-48-25-94.5T81 552q0-51 11-95.5t33-81.5q18-30 41-53.5t53-40.5q29-18 60.5-26.5T345 245q18 0 42.5 6t54.5 17q30 11 49.5 17t27.5 6q7 0 28.5-7t57.5-20q35-13 64-18t53-3q64 5 112.5 30.5T916 345q-58 35-86.5 84T801 541q1 49 18.5 90t52.5 73q16 15 34 26.5t37 20.5q-4 12-8.5 24t-9.5 23M728 20q0 39-14 75t-42 69q-34 39-74.5 60.5T513 242q0-5-.5-9.5t-.5-9.5q0-37 15.5-75T571 78q15-17 33-30.5T644 23q22-10 42.5-16T727 0q0 5 .5 10t.5 10z"}}}]);
|
/* eslint-disable */
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {htmlEscapeJsonString} from '../server/htmlescape'
import flush from 'styled-jsx/server'
export default class Document extends Component {
static childContextTypes = {
_documentProps: PropTypes.any,
_devOnlyInvalidateCacheQueryString: PropTypes.string,
}
static getInitialProps ({ renderPage }) {
const { html, head } = renderPage()
const styles = flush()
return { html, head, styles }
}
getChildContext () {
return {
_documentProps: this.props,
// In dev we invalidate the cache by appending a timestamp to the resource URL.
// This is a workaround to fix https://github.com/zeit/next.js/issues/5860
// TODO: remove this workaround when https://bugs.webkit.org/show_bug.cgi?id=187726 is fixed.
_devOnlyInvalidateCacheQueryString: process.env.NODE_ENV !== 'production' ? '?ts=' + Date.now() : ''
}
}
render () {
return <html amp={this.props.amphtml ? '' : null}>
<Head />
<body>
<Main />
<NextScript />
</body>
</html>
}
}
export class Head extends Component {
static contextTypes = {
_documentProps: PropTypes.any,
_devOnlyInvalidateCacheQueryString: PropTypes.string,
}
static propTypes = {
nonce: PropTypes.string,
crossOrigin: PropTypes.string
}
getCssLinks () {
const { assetPrefix, files } = this.context._documentProps
if(!files || files.length === 0) {
return null
}
return files.map((file) => {
// Only render .css files here
if(!/\.css$/.exec(file)) {
return null
}
return <link
key={file}
nonce={this.props.nonce}
rel='stylesheet'
href={`${assetPrefix}/_next/${file}`}
crossOrigin={this.props.crossOrigin || process.crossOrigin}
/>
})
}
getPreloadDynamicChunks () {
const { dynamicImports, assetPrefix } = this.context._documentProps
const { _devOnlyInvalidateCacheQueryString } = this.context
return dynamicImports.map((bundle) => {
return <link
rel='preload'
key={bundle.file}
href={`${assetPrefix}/_next/${bundle.file}${_devOnlyInvalidateCacheQueryString}`}
as='script'
nonce={this.props.nonce}
crossOrigin={this.props.crossOrigin || process.crossOrigin}
/>
})
}
getPreloadMainLinks () {
const { assetPrefix, files } = this.context._documentProps
if (!files || files.length === 0) {
return null
}
const { _devOnlyInvalidateCacheQueryString } = this.context
return files.map((file) => {
// Only render .js files here
if(!/\.js$/.exec(file)) {
return null
}
return <link
key={file}
nonce={this.props.nonce}
rel='preload'
href={`${assetPrefix}/_next/${file}${_devOnlyInvalidateCacheQueryString}`}
as='script'
crossOrigin={this.props.crossOrigin || process.crossOrigin}
/>
})
}
render () {
const { asPath, ampEnabled, head, styles, amphtml, assetPrefix, __NEXT_DATA__ } = this.context._documentProps
const { _devOnlyInvalidateCacheQueryString } = this.context
const { page, buildId } = __NEXT_DATA__
let children = this.props.children
// show a warning if Head contains <title> (only in development)
if (process.env.NODE_ENV !== 'production') {
children = React.Children.map(children, (child) => {
if (child && child.type === 'title') {
console.warn("Warning: <title> should not be used in _document.js's <Head>. https://err.sh/next.js/no-document-title")
}
return child
})
if (this.props.crossOrigin) console.warn('Warning: `Head` attribute `crossOrigin` is deprecated. https://err.sh/next.js/doc-crossorigin-deprecated')
}
return <head {...this.props}>
{children}
{head}
{amphtml && <>
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1"/>
<link rel="canonical" href={asPath === '/amp' ? '/' : asPath.replace(/\/amp$/, '')} />
{/* https://www.ampproject.org/docs/fundamentals/optimize_amp#optimize-the-amp-runtime-loading */}
<link rel="preload" as="script" href="https://cdn.ampproject.org/v0.js" />
{/* Add custom styles before AMP styles to prevent accidental overrides */}
{styles && <style amp-custom="" dangerouslySetInnerHTML={{__html: styles.map((style) => style.props.dangerouslySetInnerHTML.__html)}} />}
<style amp-boilerplate="" dangerouslySetInnerHTML={{__html: `body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}`}}></style>
<noscript><style amp-boilerplate="" dangerouslySetInnerHTML={{__html: `body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}`}}></style></noscript>
<script async src="https://cdn.ampproject.org/v0.js"></script>
</>}
{!amphtml && <>
{ampEnabled && <link rel="amphtml" href={asPath === '/' ? '/amp' : (asPath.replace(/\/$/, '') + '/amp')} />}
{page !== '/_error' && <link rel='preload' href={`${assetPrefix}/_next/static/${buildId}/pages${getPagePathname(page)}${_devOnlyInvalidateCacheQueryString}`} as='script' nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} />}
<link rel='preload' href={`${assetPrefix}/_next/static/${buildId}/pages/_app.js${_devOnlyInvalidateCacheQueryString}`} as='script' nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} />
{this.getPreloadDynamicChunks()}
{this.getPreloadMainLinks()}
{this.getCssLinks()}
{styles || null}
</>}
</head>
}
}
export class Main extends Component {
static contextTypes = {
_documentProps: PropTypes.any,
_devOnlyInvalidateCacheQueryString: PropTypes.string,
}
render () {
const { html } = this.context._documentProps
return (
<div id='__next' dangerouslySetInnerHTML={{ __html: html }} />
)
}
}
export class NextScript extends Component {
static contextTypes = {
_documentProps: PropTypes.any,
_devOnlyInvalidateCacheQueryString: PropTypes.string,
}
static propTypes = {
nonce: PropTypes.string,
crossOrigin: PropTypes.string
}
getDynamicChunks () {
const { dynamicImports, assetPrefix } = this.context._documentProps
const { _devOnlyInvalidateCacheQueryString } = this.context
return dynamicImports.map((bundle) => {
return <script
async
key={bundle.file}
src={`${assetPrefix}/_next/${bundle.file}${_devOnlyInvalidateCacheQueryString}`}
nonce={this.props.nonce}
crossOrigin={this.props.crossOrigin || process.crossOrigin}
/>
})
}
getScripts () {
const { assetPrefix, files } = this.context._documentProps
if (!files || files.length === 0) {
return null
}
const { _devOnlyInvalidateCacheQueryString } = this.context
return files.map((file) => {
// Only render .js files here
if(!/\.js$/.exec(file)) {
return null
}
return <script
key={file}
src={`${assetPrefix}/_next/${file}${_devOnlyInvalidateCacheQueryString}`}
nonce={this.props.nonce}
async
crossOrigin={this.props.crossOrigin || process.crossOrigin}
/>
})
}
static getInlineScriptSource (documentProps) {
const {__NEXT_DATA__} = documentProps
try {
const data = JSON.stringify(__NEXT_DATA__)
return htmlEscapeJsonString(data)
} catch(err) {
if(err.message.indexOf('circular structure')) {
throw new Error(`Circular structure in "getInitialProps" result of page "${__NEXT_DATA__.page}". https://err.sh/zeit/next.js/circular-structure`)
}
throw err
}
}
render () {
const { staticMarkup, assetPrefix, amphtml, devFiles, __NEXT_DATA__ } = this.context._documentProps
const { _devOnlyInvalidateCacheQueryString } = this.context
if(amphtml) {
return null
}
const { page, buildId } = __NEXT_DATA__
if (process.env.NODE_ENV !== 'production') {
if (this.props.crossOrigin) console.warn('Warning: `NextScript` attribute `crossOrigin` is deprecated. https://err.sh/next.js/doc-crossorigin-deprecated')
}
return <>
{devFiles ? devFiles.map((file) => <script key={file} src={`${assetPrefix}/_next/${file}${_devOnlyInvalidateCacheQueryString}`} nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} />) : null}
{staticMarkup ? null : <script id="__NEXT_DATA__" type="application/json" nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} dangerouslySetInnerHTML={{
__html: NextScript.getInlineScriptSource(this.context._documentProps)
}} />}
{page !== '/_error' && <script async id={`__NEXT_PAGE__${page}`} src={`${assetPrefix}/_next/static/${buildId}/pages${getPagePathname(page)}${_devOnlyInvalidateCacheQueryString}`} nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} />}
<script async id={`__NEXT_PAGE__/_app`} src={`${assetPrefix}/_next/static/${buildId}/pages/_app.js${_devOnlyInvalidateCacheQueryString}`} nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} />
{staticMarkup ? null : this.getDynamicChunks()}
{staticMarkup ? null : this.getScripts()}
</>
}
}
function getPagePathname (page) {
if (page === '/') {
return '/index.js'
}
return `${page}.js`
}
|
import React from 'react';
import {Table, Tag, Tooltip} from 'antd';
import indexStyles from "../../pages/home/homeIndex.less";
import 'remixicon/fonts/remixicon.css';
class ServiceInvokeList extends React.Component {
render() {
const {serviceInvokes, onShowDetail, onQuerySchedule} = this.props;
const columns = [
{ title: '微服务名', dataIndex: 'serviceName', key: 'serviceName', width: '26%', className: indexStyles.serviceNameDiv,
render: (text, record, index) => <Tooltip title={text}><span>{text}</span></Tooltip>
},
{ title: '请求方式', dataIndex: 'requestType', key: 'requestType', width: '18%', className: indexStyles.serviceNameDiv,
render: (text, record, index) => <Tooltip title={text}><span>{text}</span></Tooltip>
},
{ title: '调用次数', dataIndex: 'count', key: 'count', width: '18%', align: "center" },
{ title: '耗时(ms)', dataIndex: 'duration', key: 'duration', width: '18%', align: "center" },
{ title: '可用性(%)', dataIndex: 'available', key: 'available', width: '20%', align: "center",
render: (text, record, index) => text == "100" ?
<Tag style={{background: "green"}}>{text}</Tag> : <Tag style={{background: "red"}}>{text}</Tag>
}
];
return (
<div className={indexStyles.tableCDiv}>
<div className={indexStyles.tableCTitleDiv}>
<div className={indexStyles.tableCTitleFont}>服务调用</div>
<div className={indexStyles.tableCTitleTool}>
<div onClick={() => onShowDetail("zipkin")} className={indexStyles.fontWeightHover}>
<Tooltip title={"查看详情"}>
<i className="ri-article-line" style={{fontSize: "19px", marginRight: "15px"}}></i>
</Tooltip>
</div>
</div>
</div>
<div className={indexStyles.tableCContentDiv}>
<Table
bordered
tableLayout={"fixed"}
size={"small"}
columns={columns}
dataSource={serviceInvokes}
pagination={false}
rowKey={record => record.id}
/>
</div>
</div>
);
};
}
export default ServiceInvokeList;
|
// Error: :7:18: Unexpected token no substitution template
class A {}
class ImproperSuper extends A {
method() {
return super ``;
}
}
|
const needle = require("needle");
const dotenv = require("dotenv");
const hash = require('hash.js')
const prompt = require('prompt');
const NodeCache = require("node-cache");
const jwtCache = new NodeCache({useClones: false});
const persistence_storage = require('node-persist');
const jwt = require('jwt-simple');
const CryptoJS = require("crypto-js");
const base64 = require('base-64');
const crypto = require("crypto");
let onLoad = true;
dotenv.config();
var getOptions = {
headers: {
'accept' : 'application/json, text/plain, */*',
'origin' : 'https://selfregistration.cowin.gov.in',
'referer' : 'https://selfregistration.cowin.gov.in/',
'user-agent' : 'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36',
'content-type' : 'application/json',
'pragma' : 'no-cache',
'cache-control' : 'no-cache',
'sec-ch-ua' : '" Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"',
'sec-ch-ua-mobile': '?0',
'sec-fetch-site' : 'cross-site',
'sec-fetch-mode' : 'cors',
'sec-fetch-dest' : 'empty',
'accept-language' : 'en-IN,en;q=0.9,ta-IN;q=0.8,ta;q=0.7,en-GB;q=0.6,en-US;q=0.5.'
}
}
// var postOptions = {headers: Object.assign({}, getOptions.headers, {accept: '*/*'})};
var postOptions = {
headers: Object.assign({}, getOptions.headers, {accept: 'application/json, text/plain, */*'})
};
jwtCache.on("set", function (key, value) {
// In Memory to Persistence
console.log(`Saving ${key} to persistence_storage : ${value}`);
const expires_at = jwtCache.getTtl(key);
const expires_in = Math.floor(expires_at / 1000) - Math.floor(new Date().getTime() / 1000);
persistence_storage.setItem(key, {
value: value,
ttl : expires_in
}, {ttl: expires_in * 1000 /*in millis*/});
});
jwtCache.on("flush", function () {
persistence_storage.forEach(function (datum) {
const expires_in = Math.floor(datum.ttl / 1000) - Math.floor(new Date().getTime() / 1000);
jwtCache.set(datum.key, datum.value.value, expires_in);
console.log("Flush : " + JSON.stringify(jwtCache.stats));
});
});
const baseUrl = 'https://cdn-api.co-vin.in/api/v2';
const mobile_number = Number(process.env['mobile']);
const message = base64.decode('YjVjYWIxNjctNzk3Ny00ZGYxLTgwMjctYTYzYWExNDRmMDRl');
const secretKey = base64.decode('Q29XSU5AJCMmKighQCVeJg==');
const secret_seed = CryptoJS.AES.encrypt(message, secretKey).toString();
persistence_storage.init({
logging: false,
dir : './.cache/'
}).then(value => {
jwtCache.flushAll();
onLoad = false;
}).then(value => {
console.log("Then : " + JSON.stringify(jwtCache.stats));
console.log(jwtCache.stats);
jwtCache.keys().forEach(function (_keyString) {
console.log(_keyString);
});
});
if (jwtCache.has('jwt_' + mobile_number)) {
const cachedToken = jwtCache.get('jwt_' + mobile_number);
let decodedToken = jwt.decode(cachedToken, '', 'HS256');
const expirySeconds = decodedToken['exp'] - Math.floor(new Date().getTime() / 1000);
console.log(JSON.stringify(decodedToken, null, 4));
console.log(`expires in ${expirySeconds} seconds`);
}
var schema = {
properties: {
otp: {
description: 'Enter OTP (6 digits)', // Prompt displayed to the user. If not supplied name will be used.
pattern : /^[0-9]{1,6}$/,
message : 'Verify OTP (6 digits)',
required : true
}
}
};
if (!jwtCache.has('jwt_' + mobile_number)) {
let data = {
"secret": secret_seed,
"mobile": mobile_number
};
console.log(data);
let options = {
headers: Object.assign({}, getOptions.headers, {'If-None-Match': `W/"${crypto.randomBytes(5).toString('hex')}-${crypto.randomBytes(27).toString('hex')}`})
};
needle.post(`${baseUrl}/auth/generateMobileOTP`, data, options, function (err, resp) {
console.log(resp.body); // this little guy won't be a Gzipped binary blob
const txnId = resp.body.txnId;
prompt.start();
prompt.get(schema, function (err, result) {
let opthash = hash.sha256().update(result.otp).digest('hex')
let data = {
"otp" : opthash,
"txnId": txnId
};
let options = {
headers: Object.assign({}, getOptions.headers, {'If-None-Match': `W/"${crypto.randomBytes(5).toString('hex')}-${crypto.randomBytes(27).toString('hex')}`})
};
needle.post(`${baseUrl}/auth/validateMobileOtp`, data, options, function (err, resp) {
const responseBody = resp.body;
const JWT = responseBody.token;
let decodedToken = jwt.decode(JWT, '', 'HS256');
const expirySeconds = decodedToken['exp'] - Math.floor(new Date().getTime() / 1000);
console.log(`Getting JWT for ${mobile_number} through OTP end point. Expiry - ${expirySeconds} seconds`);
jwtCache.set('jwt_' + mobile_number, JWT, expirySeconds);
prompt.stop();
});
});
});
} else {
console.log('using ' + jwtCache.get('jwt_' + mobile_number));
console.log('TTL ' + jwtCache.getTtl('jwt_' + mobile_number));
}
|
// const planets = [];
// module.exports = planets;
const { parse } = require('csv-parse');
const fs = require('fs');
const path = require('path');
const results = [];
function isHabitable(planet) {
return planet['koi_disposition'] === "CONFIRMED" && planet['koi_insol'] <= 1.11 && planet['koi_insol'] >= 0.36 && planet['koi_prad'] < 1.6;
}
function loadHabitablePlanets() {
//if I don't wrap the file-parsing code inside a promise, it will keep running asynchronously in the background
//but our code execution doesn't stop. It will send empty planets array outside without any data, because file has not been parsed yet.
//So by using Promise, we 'wait' for our 'csv' file to be parsed, and our 'results' array to be filled with correct data (habitable planets).
//after everything is finished, client can work with data.
//now if we require('planets.models.js'), this current code will execute and we will get the full array(data) to work on.
//otherwise(without promise) no data is there to work upon.
//wrapped inside Promise
return new Promise( (resolve, reject) => {
fs.createReadStream(path.join(__dirname,'..','..','data','KeplerData.csv'))
.pipe(parse({
comment: '#',
columns: true,
}))
.on('data', data => {
if (isHabitable(data))
results.push(data);
})
.on('error', err => reject(err)) //on error, reject promise.
.on('end', () => { //on end, resolve promise.
resolve();
});
})
}
function getAllPlanets() {
return results;
}
module.exports = {
loadHabitablePlanets,
//planets: results,
getAllPlanets,
};
|
var matrix3x3_8cpp =
[
[ "obrot_X", "matrix3x3_8cpp.html#a1b1c578053436e25b1247606cb35d497", null ],
[ "obrot_Y", "matrix3x3_8cpp.html#aa4993b78f26871256a063dc3922305fb", null ],
[ "obrot_Z", "matrix3x3_8cpp.html#a50ead2c60333991d53845ac2422aa6d5", null ]
];
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("language","pt-br",{button:"Configure o Idioma",remove:"Remover Idioma"});
|
$(document).ready(function(){
//Select2 para clientes y contactos dentro de un nuevo proyecto
$("#tipoContrato").select2();
$('#estadoProyecto').select2();
$('#tipoProyecto').select2();
$('#contactoDirecto').select2({
ajax: {
url: Routing.generate('buscarContacto'),
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data, params) {
var select2Data = $.map(data.data, function (obj) {
obj.id = obj.abogadoid;
obj.text = obj.nombre;
return obj;
});
return {
results: select2Data
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: formatRepoCont,
templateSelection: formatRepoSelectionCont,
formatInputTooShort: function () {
return "Ingrese un caracter para la busqueda";
}
});
$('#idcliente').select2({
ajax: {
url: Routing.generate('buscarCliente'),
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data, params) {
var select2Data = $.map(data.data, function (obj) {
obj.id = obj.clienteid;
obj.text = obj.nombre;
return obj;
});
return {
results: select2Data
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: formatRepoC,
templateSelection: formatRepoSelectionC,
formatInputTooShort: function () {
return "Ingrese un caracter para la busqueda";
},
language: {
noResults: function() {
return "<a href='#' id='addNewCliente'>Agregar Nuevo Cliente</a>";
}
}
});
$('#encargadoProyecto').select2({
ajax: {
url: Routing.generate('buscarEncargadoProyecto'),
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data, params) {
var select2Data = $.map(data.data, function (obj) {
obj.id = obj.estadoId;
obj.text = obj.nombre;
return obj;
});
return {
results: select2Data
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: formatRepoENP,
templateSelection: formatRepoSelectionENP,
formatInputTooShort: function () {
return "Ingrese un caracter para la busqueda";
}
});
//Click dentro de agregar los nuevos dentro de los select2
$(document).on("click","#addNewContacto",function() {
var url = Routing.generate('nuevocontacto');
window.open(url, "_self");
});
$(document).on("click","#addNewCliente",function() {
var url = Routing.generate('nuevocliente');
window.open(url, "_self");
});
//Inicializacion de fechas
$('#fechaInicio').Zebra_DatePicker({
format: 'd-m-Y',
direction: -1,
pair: $('#fechaFin')
});
$('#fechaFin').Zebra_DatePicker({
format: 'd-m-Y',
direction: true
});
//Terminacion de inicializacion de los select2 que sirven para el ingreso de datos generales de una empresa
//Insercion de datos generales de un proyecto
$(document).on("click","#guardarDatosGeneralesProyecto",function() {
var num = 0;
$('.requerido').each(function () {
var x = $(this).val();
if (x == "" || x == null) {
num = num + 1;
}
});
if (num == 0) {
var dataImagen = $("#imagenMapa").attr("src");
if (dataImagen=="")
{
//Solicitar permiso de guardar porque no se ha elegido una imagen del mapa de la ubicacion del proyecto
swal({
title: "Advertencia",
text: "No has capturado la imagen del mapa, ¿Quieres guardar los registros del proyecto sin una imagen del mapa de su ubicación?",
type: "warning",
showCancelButton: true,
cancelButtonText: "No",
confirmButtonText: "Si",
confirmButtonColor: "#00A59D",
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm) {
guardarDatosGenerales();
} else {
}
});
}else{
guardarDatosGenerales();
}
}else{
swal("Error!", "No debes dejar datos requeridos vacios", "error");
}
});
function guardarDatosGenerales(){
var idPrincipal = $("#idProyecto").val();
if (idPrincipal==0 ){
var nombreProyecto,idcliente, contactoDirecto,direccionProyecto, estadoProyecto, tipoProyecto, fechaInicio,
fechaFin, encargadoProyecto, observacionesProyecto,longitud,latitud,tipoContrato,dataImagen;
dataImagen = $("#imagenMapa").attr("src");
tipoContrato=$("#tipoContrato").val();
longitud= $("#longitud").val();
latitud= $("#latitude").val();
nombreProyecto = $("#nombreProyecto").val();
idcliente = $("#idcliente").val();
contactoDirecto = $("#contactoDirecto").val();
direccionProyecto = $("#direccionProyecto").val();
estadoProyecto = $("#estadoProyecto").val();
tipoProyecto = $("#tipoProyecto").val();
fechaInicio = $("#fechaInicio").val();
fechaFin = $("#fechaFin").val();
encargadoProyecto = $("#encargadoProyecto").val();
observacionesProyecto = $("#observacionesProyecto").val();
$.ajax({
type: 'POST',
async: false,
dataType: 'json',
data: {nombreProyecto:nombreProyecto,i:0},
url: Routing.generate('validarNombreProyecto'),
success: function (data)
{
if (data.estado==true){
$.ajax({
type: 'POST',
async: false,
dataType: 'json',
data: {nombreProyecto: nombreProyecto, idcliente: idcliente, contactoDirecto: contactoDirecto, direccionProyecto: direccionProyecto, estadoProyecto: estadoProyecto,
tipoProyecto: tipoProyecto, fechaInicio: fechaInicio, fechaFin: fechaFin, encargadoProyecto: encargadoProyecto, observacionesProyecto: observacionesProyecto,
longitud:longitud,latitud:latitud,tipoContrato:tipoContrato,dataImagen:dataImagen},
url: Routing.generate('insertarDatosGeneralesProyecto'),
success: function (data)
{
if (data.estado == true) {
$("#idProyecto").val(data.idProyecto);
swal("Exito!", "Datos ingresados con exito", "success");
}
},
error: function (xhr, status)
{
}
});
}else{
swal("Error!", "Nombre de proyecto ya existe, intenta con otro", "error");
$("#nombreProyecto").val("");
$("#nombreProyecto").hover();
}
},
error: function (xhr, status)
{
}
});
}else{
//Edicion de los datos generales de la empresa
var nombreProyecto,idcliente, contactoDirecto,direccionProyecto, estadoProyecto, tipoProyecto, fechaInicio,
fechaFin, encargadoProyecto, observacionesProyecto,longitud,latitud,tipoContrato,dataImagen,idProyecto;
dataImagen = $("#imagenMapa").attr("src");
tipoContrato=$("#tipoContrato").val();
longitud= $("#longitud").val();
latitud= $("#latitude").val();
nombreProyecto = $("#nombreProyecto").val();
idcliente = $("#idcliente").val();
contactoDirecto = $("#contactoDirecto").val();
direccionProyecto = $("#direccionProyecto").val();
estadoProyecto = $("#estadoProyecto").val();
tipoProyecto = $("#tipoProyecto").val();
fechaInicio = $("#fechaInicio").val();
fechaFin = $("#fechaFin").val();
encargadoProyecto = $("#encargadoProyecto").val();
observacionesProyecto = $("#observacionesProyecto").val();
$.ajax({
type: 'POST',
async: false,
dataType: 'json',
data: {nombreProyecto:nombreProyecto,i:1},
url: Routing.generate('validarNombreProyecto'),
success: function (data)
{
if (data.estado==true){
$.ajax({
type: 'POST',
async: false,
dataType: 'json',
data: {nombreProyecto: nombreProyecto, idcliente: idcliente, contactoDirecto: contactoDirecto, direccionProyecto: direccionProyecto, estadoProyecto: estadoProyecto,
tipoProyecto: tipoProyecto, fechaInicio: fechaInicio, fechaFin: fechaFin, encargadoProyecto: encargadoProyecto, observacionesProyecto: observacionesProyecto,
longitud:longitud,latitud:latitud,tipoContrato:tipoContrato,dataImagen:dataImagen,idProyecto:idPrincipal},
url: Routing.generate('modificarDatosGeneralesProyecto'),
success: function (data)
{
if (data.estado == true) {
$("#idProyecto").val(data.idProyecto);
swal("Exito!", "Datos modificados con exito", "success");
}
},
error: function (xhr, status)
{
}
});
}else{
swal("Error!", "Nombre de proyecto ya existe, intenta con otro", "error");
$("#nombreProyecto").hover();
}
},
error: function (xhr, status)
{
}
});
}
}
//Al dar click en nuevo proyecto
$(document).on("click","#nuevoProyecto",function() {
var z= $("#tipoProyectoSeleccionado").val();
var url=Routing.generate('nuevoProyecto',{parametro:z});
window.open(url, "_self");
});
//Permisos en las tabs
$(document).on("click","#datosMaquinaria",function() {
var idProyecto= $("#idProyecto").val();
if (idProyecto==0){
$("#datosGeneralesProyecto").click();
swal("Alerta!", "Primero tienes que igresar los datos generales del proyecto.", "warning");
}
});
$(document).on("click","#datosRecursosHumanos",function() {
var idProyecto= $("#idProyecto").val();
if (idProyecto==0){
$("#datosGeneralesProyecto").click();
swal("Alerta!", "Primero tienes que igresar los datos generales del proyecto.", "warning");
}
});
$(document).on("click","#datosReportesDiarios",function() {
var idProyecto= $("#idProyecto").val();
if (idProyecto==0){
$("#datosGeneralesProyecto").click();
swal("Alerta!", "Primero tienes que igresar los datos generales del proyecto.", "warning");
}
});
// Click en cancelar insercion datos generales del proyecto
//Fin document ready
});
//Contacto
function formatRepoCont (data) {
if(data.nombre){
var markup = "<div class='select2-result-repository clearfix'>" +
"<div class='select2-result-repository__meta'>" +
"<div class='select2-result-repository__title'>" + data.nombre+ "</div>" +
"</div></div>";
} else {
var markup = "Seleccione un contacto";
}
return markup;
}
function formatRepoSelectionCont (data) {
if(data.nombre){
return data.nombre;
} else {
return "Seleccione un contacto";
}
}
//Cliente
function formatRepoC (data) {
if(data.nombre){
var markup = "<div class='select2-result-repository clearfix'>" +
"<div class='select2-result-repository__meta'>" +
"<div class='select2-result-repository__title'>" + data.nombre+ "</div>" +
"</div></div>";
} else {
var markup = "Seleccione un cliente";
}
return markup;
}
function formatRepoSelectionC (data) {
if(data.nombre){
return data.nombre;
} else {
return "Seleccione un cliente";
}
}
//Encargado de proyecto
function formatRepoENP (data) {
if(data.nombre){
var markup = "<div class='select2-result-repository clearfix'>" +
"<div class='select2-result-repository__meta'>" +
"<div class='select2-result-repository__title'>" + data.nombre+ "</div>" +
"</div></div>";
} else {
var markup = "Encargado proyecto";
}
return markup;
}
function formatRepoSelectionENP (data) {
if(data.nombre){
return data.nombre;
} else {
return "Encargado proyecto";
}
}
|
var PayPal="PayPal",Email="Email",MalaysianRinggit="RM",USD="USD";
function Cart(){
var me = this;
/* member variables */
me.nextId = 1;
me.Version = '2.2.2';
me.Shelf = null;
me.items = {};
me.isLoaded = false;
me.invoice = null;
me.pageIsReady = false;
me.quantity = 0;
me.total = 0;
me.taxRate = 0;
me.taxCost = 0;
me.shippingFlatRate = 0;
me.shippingTotalRate = 0;
me.shippingQuantityRate = 0;
me.shippingRate = 0;
me.shippingCost = 0;
me.currency = RM;
me.checkoutTo = PayPal;
me.email = "";
me.merchantId = "";
me.successUrl = null;
me.cancelUrl = null;
me.cookieDuration = 30; // default duration in days
me.storagePrefix = "sc_";
me.MAX_COOKIE_SIZE = 4000;
me.cartHeaders = ['product_code','product_name','Quantity','Total'];
me.events = {};
me.sandbox = false;
me.paypalHTTPMethod = "GET";
/*
cart headers:
you can set these to which ever order you would like, and the cart will display the appropriate headers
and item info. any field you have for the items in the cart can be used, and 'Total' will automatically
be price*quantity.
there are keywords that can be used:
1) "_input" - the field will be a text input with the value set to the given field. when the user
changes the value, it will update the cart. this can be useful for quantity. (ie "Quantity_input")
2) "increment" - a link with "+" that will increase the item quantity by 1
3) "decrement" - a link with "-" that will decrease the item quantity by 1
4) "remove" - a link that will remove the item from the cart
5) "_image" or "Image" - the field will be an img tag with the src set to the value. You can simply use "Image" if
you set a field in the items called "Image". If you have a field named something else, like "Thumb", you can add
the "_image" to create the image tag (ie "Thumb_image").
6) "_noHeader" - this will skip the header for that field (ie "increment_noHeader")
*/
/******************************************************
function for setting options
******************************************************/
me.options = function( values ){
me.each(values, function( value , x , name ){
me[name]=value;
});
};
/******************************************************
add/remove items to cart
******************************************************/
me.add = function ( values ) {
var me=this;
/* load cart values if not already loaded */
if( !me.pageIsReady ) {
me.initializeView();
me.update();
}
if( !me.isLoaded ) {
me.load();
me.update();
}
var newItem = new CartItem();
/* check to ensure arguments have been passed in */
if( !arguments || arguments.length === 0 ){
error( 'No values passed for item.');
return null;
}
var argumentArray = arguments;
if( values && typeof( values ) !== 'string' && typeof( values ) !== 'number' ){
argumentArray = values;
}
newItem.parseValuesFromArray( argumentArray );
newItem.checkQuantityAndPrice();
if( me.trigger('beforeAdd', [newItem] ) === false ){
return false;
}
var isNew = true;
/* if the item already exists, update the quantity */
if( me.hasItem(newItem) ) {
var foundItem=me.hasItem(newItem);
foundItem.quantity= parseInt(foundItem.quantity,10) + parseInt(newItem.quantity,10);
newItem = foundItem;
isNew = false;
} else {
me.items[newItem.id] = newItem;
}
me.update();
me.trigger('afterAdd', [newItem,isNew] );
return newItem;
};
me.remove = function( id ){
var tempArray = {};
me.each(function(item){
if( item.id !== id ){
tempArray[item.id] = item;
}
});
this.items = tempArray;
};
me.empty = function () {
me.items = {};
me.update();
};
/******************************************************
item accessor functions
******************************************************/
me.find = function (criteria) {
if( !criteria ){
return null;
}
var results = [];
me.each(function(item,x,next){
fits = true;
me.each( criteria , function(value,j,name){
if( !item[name] || item[name] != value ){
fits = false;
}
});
if( fits ){
results.push( item );
}
});
return (results.length === 0 ) ? null : results;
};
me.each = function( array , callback ){
var next,
x=0,
result;
if( typeof array === 'function' ){
var cb = array
items = me.items;
} else if( typeof callback === 'function' ){
var cb = callback,
items = array;
} else {
return;
}
for( next in items ){
if( typeof items[next] !== "function" ){
result = cb.call( me , items[next] , x , next );
if( result === false ){
return;
}
x++;
}
}
};
me.chunk = function(str, n) {
if (typeof n==='undefined'){
n=2;
}
var result = str.match(RegExp('.{1,'+n+'}','g'));
return result || [];
};
/******************************************************
checkout management
******************************************************/
me.checkout = function() {
if( me.quantity === 0 ){
error("Cart is empty");
return;
}
switch( me.checkoutTo ){
case PayPal:
me.paypalCheckout();
break;
case GoogleCheckout:
me.googleCheckout();
break;
case Email:
me.emailCheckout();
break;
default:
me.customCheckout();
break;
}
};
me.paypalCheckout = function() {
var form = document.createElement("form"),
counter=1,
current,
item,
descriptionString;
form.style.display = "none";
form.method = me.paypalHTTPMethod =="GET" || me.paypalHTTPMethod == "POST" ? me.paypalHTTPMethod : "GET";
form.action = me.sandbox ? "https://www.sandbox.paypal.com/cgi-bin/webscr" : "https://www.paypal.com/cgi-bin/webscr";
form.acceptCharset = "utf-8";
// setup hidden fields
form.appendChild(me.createHiddenElement("cmd", "_cart"));
form.appendChild(me.createHiddenElement("rm", me.paypalHTTPMethod == "POST" ? "2" : "0" ));
form.appendChild(me.createHiddenElement("upload", "1"));
form.appendChild(me.createHiddenElement("business", me.email ));
form.appendChild(me.createHiddenElement("currency_code", me.currency));
form.appendChild(me.createHiddenElement("charset", "utf-8"));
if (me.invoice) {
form.appendChild(me.createHiddenElement("invoice", me.invoice));
}
if( me.taxRate ){
form.appendChild(me.createHiddenElement("tax_cart", parseFloat(me.taxCost).toFixed(2)));
}
if( me.shipping() !== 0){
form.appendChild(me.createHiddenElement("handling_cart", me.shippingCost ));
}
if( me.successUrl ){
form.appendChild(me.createHiddenElement("return", me.successUrl ));
}
if( me.cancelUrl ){
form.appendChild(me.createHiddenElement("cancel_return", me.cancelUrl ));
}
me.each(function(item,iter){
counter = iter+1;
form.appendChild( me.createHiddenElement( "item_name_" + counter, item.name ) );
form.appendChild( me.createHiddenElement( "quantity_" + counter, item.quantity ) );
form.appendChild( me.createHiddenElement( "amount_" + counter, item.price ) );
form.appendChild( me.createHiddenElement( "item_number_" + counter, counter ) );
var option_count = 0;
me.each( item , function( value, x , field ){
if( field !== "id" && field !== "price" && field !== "quantity" && field !== "name" && field !== "shipping" && option_count < 10) {
form.appendChild( me.createHiddenElement( "on" + option_count + "_" + counter, field ) );
form.appendChild( me.createHiddenElement( "os" + option_count + "_" + counter, value ) );
option_count++;
}
});
form.appendChild( me.createHiddenElement( "option_index_" + counter, option_count) );
});
document.body.appendChild( form );
form.submit();
document.body.removeChild( form );
};
me.googleCheckout = function() {
var me = this;
if( me.currency !== USD && me.currency !== GBP ){
error( "Google Checkout only allows the USD and GBP for currency.");
return;
} else if( me.merchantId === "" || me.merchantId === null || !me.merchantId ){
error( "No merchant Id for google checkout supplied.");
return;
}
var form = document.createElement("form"),
counter=1,
current,
item,
descriptionString;
form.style.display = "none";
form.method = "POST";
form.action = "https://checkout.google.com/api/checkout/v2/checkoutForm/Merchant/" +
me.merchantId;
form.acceptCharset = "utf-8";
me.each(function(item,iter){
counter = iter+1;
form.appendChild( me.createHiddenElement( "item_name_" + counter, item.name ) );
form.appendChild( me.createHiddenElement( "item_quantity_" + counter, item.quantity ) );
form.appendChild( me.createHiddenElement( "item_price_" + counter, item.price ) );
form.appendChild( me.createHiddenElement( "item_currency_" + counter, me.currency ) );
form.appendChild( me.createHiddenElement( "item_tax_rate_" + counter, me.taxRate ) );
form.appendChild( me.createHiddenElement( "_charset_" , "" ) );
descriptionString = "";
me.each( item , function( value , x , field ){
if( field !== "id" &&
field !== "quantity" &&
field !== "price" ) {
descriptionString = descriptionString + ", " + field + ": " + value;
}
});
descriptionString = descriptionString.substring( 1 );
form.appendChild( me.createHiddenElement( "item_description_" + counter, descriptionString) );
});
// hack for adding shipping
if( me.shipping() !== 0){
form.appendChild(me.createHiddenElement("ship_method_name_1", "Shipping"));
form.appendChild(me.createHiddenElement("ship_method_price_1", parseFloat(me.shippingCost).toFixed(2)));
form.appendChild(me.createHiddenElement("ship_method_currency_1", me.currency));
}
document.body.appendChild( form );
form.submit();
document.body.removeChild( form );
};
me.emailCheckout = function() {
return;
};
me.customCheckout = function() {
return;
};
/******************************************************
data storage and retrival
******************************************************/
/* load cart from cookie */
me.load = function () {
var me = this,
id;
/* initialize variables and items array */
me.items = {};
me.total = 0.00;
me.quantity = 0;
/* retrieve item data from cookie */
if( readCookie(simpleCart.storagePrefix + 'simpleCart_' + "chunks") ){
var chunkCount = 1*readCookie(simpleCart.storagePrefix + 'simpleCart_' + "chunks"),
dataArray = [],
dataString = "",
data = "",
info,
newItem,
y=0;
if(chunkCount>0) {
for( y=0;y<chunkCount;y++){
dataArray.push( readCookie( simpleCart.storagePrefix + 'simpleCart_' + (1 + y ) ) );
}
dataString = unescape( dataArray.join("") );
data = dataString.split("++");
}
for(var x=0, xlen=data.length;x<xlen;x++){
info = data[x].split('||');
newItem = new CartItem();
if( newItem.parseValuesFromArray( info ) ){
newItem.checkQuantityAndPrice();
/* store the new item in the cart */
me.items[newItem.id] = newItem;
}
}
}
me.isLoaded = true;
};
/* save cart to cookie */
me.save = function () {
var dataString = "",
dataArray = [],
chunkCount = 0;
chunkCount = 1*readCookie(simpleCart.storagePrefix + 'simpleCart_' + "chunks");
for( var j=0;j<chunkCount;j++){
eraseCookie(simpleCart.storagePrefix + 'simpleCart_'+ j);
}
eraseCookie(simpleCart.storagePrefix + 'simpleCart_' + "chunks");
me.each(function(item){
dataString = dataString + "++" + item.print();
});
dataArray = simpleCart.chunk( dataString.substring(2) , simpleCart.MAX_COOKIE_SIZE );
for( var x=0,xlen = dataArray.length;x<xlen;x++){
createCookie(simpleCart.storagePrefix + 'simpleCart_' + (1 + x ), dataArray[x], me.cookieDuration );
}
createCookie( simpleCart.storagePrefix + 'simpleCart_' + "chunks", "" + dataArray.length , me.cookieDuration );
};
/******************************************************
view management
******************************************************/
me.initializeView = function() {
var me = this;
me.totalOutlets = getElementsByClassName('simpleCart_total');
me.quantityOutlets = getElementsByClassName('simpleCart_quantity');
me.cartDivs = getElementsByClassName('simpleCart_items');
me.taxCostOutlets = getElementsByClassName('simpleCart_taxCost');
me.taxRateOutlets = getElementsByClassName('simpleCart_taxRate');
me.shippingCostOutlets = getElementsByClassName('simpleCart_shippingCost');
me.finalTotalOutlets = getElementsByClassName('simpleCart_finalTotal');
me.addEventToArray( getElementsByClassName('simpleCart_checkout') , simpleCart.checkout , "click");
me.addEventToArray( getElementsByClassName('simpleCart_empty') , simpleCart.empty , "click" );
me.Shelf = new Shelf();
me.Shelf.readPage();
me.pageIsReady = true;
};
me.updateView = function() {
me.updateViewTotals();
if( me.cartDivs && me.cartDivs.length > 0 ){
me.updateCartView();
}
};
me.updateViewTotals = function() {
var outlets = [ ["quantity" , "none" ] ,
["total" , "currency" ] ,
["shippingCost" , "currency" ] ,
["taxCost" , "currency" ] ,
["taxRate" , "percentage" ] ,
["finalTotal" , "currency" ] ];
for( var x=0,xlen=outlets.length; x<xlen;x++){
var arrayName = outlets[x][0] + "Outlets",
outputString,
element;
for( var y = 0,ylen = me[ arrayName ].length; y<ylen; y++ ){
switch( outlets[x][1] ){
case "none":
outputString = "" + me[outlets[x][0]];
break;
case "currency":
outputString = me.valueToCurrencyString( me[outlets[x][0]] );
break;
case "percentage":
outputString = me.valueToPercentageString( me[outlets[x][0]] );
break;
default:
outputString = "" + me[outlets[x][0]];
break;
}
me[arrayName][y].innerHTML = "" + outputString;
}
}
};
me.updateCartView = function() {
var newRows = [],
y,newRow,current,header,newCell,info,outputValue,option,headerInfo;
/* create headers row */
newRow = document.createElement('div');
for(var y=0,ylen = me.cartHeaders.length; y<ylen; y++ ){
newCell = document.createElement('div');
headerInfo = me.cartHeaders[y].split("_");
newCell.innerHTML = me.print( headerInfo[0] );
newCell.className = "item" + headerInfo[0];
for(var z=1,zlen=headerInfo.length;z<zlen;z++){
if( headerInfo[z].toLowerCase() == "noheader" ){
newCell.style.display = "none";
}
}
newRow.appendChild( newCell );
}
newRow.className = "cartHeaders";
newRows[0] = newRow;
/* create a row for each item in the cart */
me.each(function(item, x){
newRow = document.createElement('div');
for(var y=0,ylen = me.cartHeaders.length; y<ylen; y++ ){
newCell = document.createElement('div');
info = me.cartHeaders[y].split("_");
outputValue = me.createCartRow( info , item , outputValue );
newCell.innerHTML = outputValue;
newCell.className = "item" + info[0];
newRow.appendChild( newCell );
}
newRow.className = "itemContainer";
newRows[x+1] = newRow;
});
for( var x=0,xlen=me.cartDivs.length; x<xlen; x++){
/* delete current rows in div */
var div = me.cartDivs[x];
if( div.childNodes && div.appendChild ){
while( div.childNodes[0] ){
div.removeChild( div.childNodes[0] );
}
for(var j=0, jLen = newRows.length; j<jLen; j++){
div.appendChild( newRows[j] );
}
}
}
};
me.createCartRow = function( info , item , outputValue ){
switch( info[0].toLowerCase() ){
case "total":
outputValue = me.valueToCurrencyString(parseFloat(item.price)*parseInt(item.quantity,10) );
break;
case "increment":
outputValue = me.valueToLink( "+" , "javascript:;" , "onclick=\"simpleCart.items[\'" + item.id + "\'].increment();\"" );
break;
case "decrement":
outputValue = me.valueToLink( "-" , "javascript:;" , "onclick=\"simpleCart.items[\'" + item.id + "\'].decrement();\"" );
break;
case "remove":
outputValue = me.valueToLink( "Remove" , "javascript:;" , "onclick=\"simpleCart.items[\'" + item.id + "\'].remove();\"" );
break;
case "price":
outputValue = me.valueToCurrencyString( item[ info[0].toLowerCase() ] ? item[info[0].toLowerCase()] : " " );
break;
default:
outputValue = item[ info[0].toLowerCase() ] ?
typeof item[info[0].toLowerCase()] === 'function' ?
item[info[0].toLowerCase()].call(item) :
item[info[0].toLowerCase()] :
" ";
break;
}
for( var y=1,ylen=info.length;y<ylen;y++){
option = info[y].toLowerCase();
switch( option ){
case "image":
case "img":
outputValue = me.valueToImageString( outputValue );
break;
case "input":
outputValue = me.valueToTextInput( outputValue , "onchange=\"simpleCart.items[\'" + item.id + "\'].set(\'" + info[0].toLowerCase() + "\' , this.value);\"" );
break;
case "div":
case "span":
case "h1":
case "h2":
case "h3":
case "h4":
case "p":
outputValue = me.valueToElement( option , outputValue , "" );
break;
case "noheader":
break;
default:
error( "unkown header option: " + option );
break;
}
}
return outputValue;
};
me.addEventToArray = function ( array , functionCall , theEvent ) {
var outlet,
element;
for(var x=0,xlen=array.length; x<xlen; x++ ){
element = array[x];
if( element.addEventListener ) {
element.addEventListener(theEvent, functionCall , false );
} else if( element.attachEvent ) {
element.attachEvent( "on" + theEvent, functionCall );
}
}
};
me.createHiddenElement = function ( name , value ){
var element = document.createElement("input");
element.type = "hidden";
element.name = name;
element.value = value;
return element;
};
/******************************************************
Event Management
******************************************************/
// bind a callback to a simpleCart event
me.bind = function( name , callback ){
if( typeof callback !== 'function' ){
return me;
}
if (me.events[name] === true ){
callback.apply( me );
} else if( typeof me.events[name] !== 'undefined' ){
me.events[name].push( callback );
} else {
me.events[name] = [ callback ];
}
return me;
};
// trigger event
me.trigger = function( name , options ){
var returnval = true;
if( typeof me.events[name] !== 'undefined' && typeof me.events[name][0] === 'function'){
for( var x=0,xlen=me.events[name].length; x<xlen; x++ ){
returnval = me.events[name][x].apply( me , (options ? options : [] ) );
}
}
if( returnval === false ){
return false;
} else {
return true;
}
};
// shortcut for ready function
me.ready = function( callback ){
if( !callback ){
me.trigger( 'ready' );
me.events['ready'] = true;
} else {
me.bind( 'ready' , callback );
}
return me;
};
/******************************************************
Currency management
******************************************************/
me.currencySymbol = function() {
switch(me.currency){
case CHF:
return "CHF ";
case CZK:
return "CZK ";
case DKK:
return "DKK ";
case HUF:
return "HUF ";
case NOK:
return "NOK ";
case PLN:
return "PLN ";
case SEK:
return "SEK ";
case JPY:
return "¥";
case EUR:
return "€";
case GBP:
return "£";
case CHF:
return "CHF ";
case THB:
return "฿";
case USD:
case CAD:
case AUD:
case NZD:
case HKD:
case SGD:
return "$";
default:
return "";
}
};
me.currencyStringForPaypalCheckout = function( value ){
if( me.currencySymbol() == "$" ){
return "$" + parseFloat( value ).toFixed(2);
} else {
return "" + parseFloat(value ).toFixed(2);
}
};
/******************************************************
Formatting
******************************************************/
me.valueToCurrencyString = function( value ) {
var val = parseFloat( value );
if( isNaN(val))
val = 0;
return val.toCurrency( me.currencySymbol() );
};
me.valueToPercentageString = function( value ){
return parseFloat( 100*value ) + "%";
};
me.valueToImageString = function( value ){
if( value.match(/<\s*img.*src\=/) ){
return value;
} else {
return "<img src=\"" + value + "\" />";
}
};
me.valueToTextInput = function( value , html ){
return "<input type=\"text\" value=\"" + value + "\" " + html + " />";
};
me.valueToLink = function( value, link, html){
return "<a href=\"" + link + "\" " + html + " >" + value + "</a>";
};
me.valueToElement = function( type , value , html ){
return "<" + type + " " + html + " > " + value + "</" + type + ">";
};
/******************************************************
Duplicate management
******************************************************/
me.hasItem = function ( item ) {
var current,
matches,
field,
match=false;
me.each(function(testItem){
matches = true;
me.each( item , function( value , x , field ){
if( field !== "quantity" && field !== "id" && item[field] !== testItem[field] ){
matches = false;
}
});
if( matches ){
match = testItem;
}
});
return match;
};
/******************************************************
Language managment
******************************************************/
me.ln = {
"en_us": {
quantity: "Quantity"
, price: "Price"
, total: "Total"
, decrement: "Decrement"
, increment: "Increment"
, remove: "Remove"
, tax: "Tax"
, shipping: "Shipping"
, image: "Image"
}
};
me.language = "en_us";
me.print = function( input ) {
var me = this;
return me.ln[me.language] && me.ln[me.language][input.toLowerCase()] ? me.ln[me.language][input.toLowerCase()] : input;
};
/******************************************************
Cart Update managment
******************************************************/
me.update = function() {
if( !simpleCart.isLoaded ){
simpleCart.load();
}
if( !simpleCart.pageIsReady ){
simpleCart.initializeView();
}
me.updateTotals();
me.updateView();
me.save();
};
me.updateTotals = function() {
me.total = 0 ;
me.quantity = 0;
me.each(function(item){
if( item.quantity < 1 ){
item.remove();
} else if( item.quantity !== null && item.quantity !== "undefined" ){
me.quantity = parseInt(me.quantity,10) + parseInt(item.quantity,10);
}
if( item.price ){
me.total = parseFloat(me.total) + parseInt(item.quantity,10)*parseFloat(item.price);
}
});
me.shippingCost = me.shipping();
me.taxCost = parseFloat(me.total)*me.taxRate;
me.finalTotal = me.shippingCost + me.taxCost + me.total;
};
me.shipping = function(){
if( parseInt(me.quantity,10)===0 )
return 0;
var shipping = parseFloat(me.shippingFlatRate) +
parseFloat(me.shippingTotalRate)*parseFloat(me.total) +
parseFloat(me.shippingQuantityRate)*parseInt(me.quantity,10),
next;
me.each(function(nextItem){
if( nextItem.shipping ){
if( typeof nextItem.shipping == 'function' ){
shipping += parseFloat(nextItem.shipping());
} else {
shipping += parseFloat(nextItem.shipping);
}
}
});
return shipping;
}
me.initialize = function() {
me.initializeView();
me.load();
me.update();
me.ready();
};
}
/********************************************************************************************************
* Cart Item Object
********************************************************************************************************/
function CartItem() {
while( simpleCart.items["c" + simpleCart.nextId] )
simpleCart.nextId++;
this.id = "c" + simpleCart.nextId;
}
CartItem.prototype = {
set : function ( field , value ){
field = field.toLowerCase();
if( typeof( this[field] ) !== "function" && field !== "id" ){
value = "" + value;
if( field == "quantity"){
value = value.replace( /[^(\d|\.)]*/gi , "" );
value = value.replace(/,*/gi, "");
value = parseInt(value,10);
} else if( field == "price" ){
value = value.replace( /[^(\d|\.)]*/gi, "");
value = value.replace(/,*/gi , "");
value = parseFloat( value );
}
if( typeof(value) == "number" && isNaN( value ) ){
error( "Improperly formatted input.");
} else {
if( typeof( value ) === "string" ){
if( value.match(/\~|\=/) ){
error("Special character ~ or = not allowed: " + value);
}
value = value.replace(/\~|\=/g, "");
}
this[field] = value;
this.checkQuantityAndPrice();
}
} else {
error( "Cannot change " + field + ", this is a reserved field.");
}
simpleCart.update();
},
increment : function(){
this.quantity = parseInt(this.quantity,10) + 1;
simpleCart.update();
},
decrement : function(){
if( parseInt(this.quantity,10) < 2 ){
this.remove();
} else {
this.quantity = parseInt(this.quantity,10) - 1;
simpleCart.update();
}
},
print : function () {
var returnString = '',
field;
simpleCart.each(this ,function(item,x,name){
returnString+= escape(name) + "=" + escape(item) + "||";
});
return returnString.substring(0,returnString.length-2);
},
checkQuantityAndPrice : function() {
if( !this.quantity || this.quantity == null || this.quantity == 'undefined'){
this.quantity = 1;
error('No quantity for item.');
} else {
this.quantity = ("" + this.quantity).replace(/,*/gi, "" );
this.quantity = parseInt( ("" + this.quantity).replace( /[^(\d|\.)]*/gi, "") , 10);
if( isNaN(this.quantity) ){
error('Quantity is not a number.');
this.quantity = 1;
}
}
if( !this.price || this.price == null || this.price == 'undefined'){
this.price=0.00;
error('No price for item or price not properly formatted.');
} else {
this.price = ("" + this.price).replace(/,*/gi, "" );
this.price = parseFloat( ("" + this.price).replace( /[^(\d|\.)]*/gi, "") );
if( isNaN(this.price) ){
error('Price is not a number.');
this.price = 0.00;
}
}
},
parseValuesFromArray : function( array ) {
if( array && array.length && array.length > 0) {
for(var x=0, xlen=array.length; x<xlen;x++ ){
/* ensure the pair does not have key delimeters */
array[x] = array[x].replace(/\|\|/g, "| |");
array[x] = array[x].replace(/\+\+/g, "+ +");
if( array[x].match(/\~/) ){
error("Special character ~ not allowed: " + array[x]);
}
array[x] = array[x].replace(/\~/g, "");
/* split the pair and save the unescaped values to the item */
var value = array[x].split('=');
if( value.length>1 ){
if( value.length>2 ){
for(var j=2, jlen=value.length;j<jlen;j++){
value[1] = value[1] + "=" + value[j];
}
}
this[ unescape(value[0]).toLowerCase() ] = unescape(value[1]);
}
}
return true;
} else {
return false;
}
},
remove : function() {
simpleCart.remove(this.id);
simpleCart.update();
}
};
/********************************************************************************************************
* Shelf Object for managing items on shelf that can be added to cart
********************************************************************************************************/
function Shelf(){
this.items = {};
}
Shelf.prototype = {
readPage : function () {
this.items = {};
var newItems = getElementsByClassName( "simpleCart_shelfItem" ),
newItem;
me = this;
for( var x = 0, xlen = newItems.length; x<xlen; x++){
newItem = new ShelfItem();
me.checkChildren( newItems[x] , newItem );
me.items[newItem.id] = newItem;
}
},
checkChildren : function ( item , newItem) {
if( !item.childNodes )
return;
for(var x=0;item.childNodes[x];x++){
var node = item.childNodes[x];
if( node.className && node.className.match(/item_[^ ]+/) ){
var data = /item_[^ ]+/.exec(node.className)[0].split("_");
if( data[1] == "add" || data[1] == "Add" ){
var tempArray = [];
tempArray.push( node );
var addFunction = simpleCart.Shelf.addToCart(newItem.id);
simpleCart.addEventToArray( tempArray , addFunction , "click");
node.id = newItem.id;
} else {
newItem[data[1]] = node;
}
}
if( node.childNodes[0] ){
this.checkChildren( node , newItem );
}
}
},
empty : function () {
this.items = {};
},
addToCart : function ( id ) {
return function(){
if( simpleCart.Shelf.items[id]){
simpleCart.Shelf.items[id].addToCart();
} else {
error( "Shelf item with id of " + id + " does not exist.");
}
};
}
};
/********************************************************************************************************
* Shelf Item Object
********************************************************************************************************/
function ShelfItem(){
this.id = "s" + simpleCart.nextId++;
}
ShelfItem.prototype = {
remove : function () {
simpleCart.Shelf.items[this.id] = null;
},
addToCart : function () {
var outStrings = [],
valueString,
field;
for( field in this ){
if( typeof( this[field] ) !== "function" && field !== "id" ){
valueString = "";
switch(field){
case "price":
if( this[field].value ){
valueString = this[field].value;
} else if( this[field].innerHTML ) {
valueString = this[field].innerHTML;
}
/* remove all characters from price except digits and a period */
valueString = valueString.replace( /[^(\d|\.)]*/gi , "" );
valueString = valueString.replace( /,*/ , "" );
break;
case "image":
valueString = this[field].src;
break;
default:
if( this[field].value ){
valueString = this[field].value;
} else if( this[field].innerHTML ) {
valueString = this[field].innerHTML;
} else if( this[field].src ){
valueString = this[field].src;
} else {
valueString = this[field];
}
break;
}
outStrings.push( field + "=" + valueString );
}
}
simpleCart.add( outStrings );
}
};
/********************************************************************************************************
* Thanks to Peter-Paul Koch for these cookie functions (http://www.quirksmode.org/js/cookies.html)
********************************************************************************************************/
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
value = value.replace(/\=/g, '~');
document.cookie = name + "=" + escape(value) + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) === 0){
var value = unescape(c.substring(nameEQ.length, c.length));
return value.replace(/\~/g, '=');
}
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
var getElementsByClassName = function (className, tag, elm){
if (document.getElementsByClassName) {
getElementsByClassName = function (className, tag, elm) {
elm = elm || document;
var elements = elm.getElementsByClassName(className),
nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
returnElements = [],
current;
for(var i=0, il=elements.length; i<il; i+=1){
current = elements[i];
if(!nodeName || nodeName.test(current.nodeName)) {
returnElements.push(current);
}
}
return returnElements;
};
}
else if (document.evaluate) {
getElementsByClassName = function (className, tag, elm) {
tag = tag || "*";
elm = elm || document;
var classes = className.split(" "),
classesToCheck = "",
xhtmlNamespace = "http://www.w3.org/1999/xhtml",
namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
returnElements = [],
elements,
node;
for(var j=0, jl=classes.length; j<jl; j+=1){
classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
}
try {
elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
}
catch (e) {
elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
}
while ((node = elements.iterateNext())) {
returnElements.push(node);
}
return returnElements;
};
}
else {
getElementsByClassName = function (className, tag, elm) {
tag = tag || "*";
elm = elm || document;
var classes = className.split(" "),
classesToCheck = [],
elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
current,
returnElements = [],
match;
for(var k=0, kl=classes.length; k<kl; k+=1){
classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
}
for(var l=0, ll=elements.length; l<ll; l+=1){
current = elements[l];
match = false;
for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
match = classesToCheck[m].test(current.className);
if (!match) {
break;
}
}
if (match) {
returnElements.push(current);
}
}
return returnElements;
};
}
return getElementsByClassName(className, tag, elm);
};
/********************************************************************************************************
* Helpers
********************************************************************************************************/
String.prototype.reverse=function(){return this.split("").reverse().join("");};
Number.prototype.withCommas=function(){var x=6,y=parseFloat(this).toFixed(2).toString().reverse();while(x<y.length){y=y.substring(0,x)+","+y.substring(x);x+=4;}return y.reverse();};
Number.prototype.toCurrency=function(){return(arguments[0]?arguments[0]:"$")+this.withCommas();};
/********************************************************************************************************
* error management
********************************************************************************************************/
function error( message ){
try{
console.log( message );
}catch(err){
// alert( message );
}
}
var simpleCart = new Cart();
if( typeof jQuery !== 'undefined' ) $(document).ready(function(){simpleCart.initialize();});
else if( typeof Prototype !== 'undefined') Event.observe( window, 'load', function(){simpleCart.initialize();});
else window.onload = simpleCart.initialize;
|
/**
* limit the number of angular components per file
*
* The number of AngularJS components in one file should be limited.
* The default limit is one.
*
* ### Options
*
* - The acceptable number of components. (Default: 1)
*
* @styleguideReference {johnpapa} `y001` Define 1 component per file
* @version 0.11.0
* @category bestPractice
*/
'use strict';
var angularRule = require('./utils/angular-rule');
module.exports = angularRule(function(context) {
var limit = context.options[0] || 1;
var count = 0;
var msg = 'There may be at most {{limit}} AngularJS {{component}} per file, but found {{number}}';
function checkLimit(callee) {
count++;
if (count > limit) {
context.report(callee, msg, {
limit: limit,
component: limit === 1 ? 'component' : 'components',
number: count
});
}
}
return {
'angular:animation': checkLimit,
'angular:config': checkLimit,
'angular:controller': checkLimit,
'angular:directive': checkLimit,
'angular:factory': checkLimit,
'angular:filter': checkLimit,
'angular:provider': checkLimit,
'angular:run': checkLimit,
'angular:service': checkLimit,
'angular:component': checkLimit
};
});
module.exports.schema = [{
type: 'integer'
}];
|
import React from 'react'
import { connect } from 'react-redux'
import Spinner from 'react-spinkit'
const styles = {
page: {
display: 'flex',
justifyContent: 'space-around',
alignItems: 'center',
},
container: {
border: '1px solid black',
backgroundColor: 'lightYellow',
padding: '1rem',
width: '15rem',
height: '18rem',
display: 'flex',
justifyContent: 'space-around',
flexDirection: 'column',
},
loading: {
height: '5rem',
},
}
const Loading = ({ label, show }) => (
<div style={styles.loading}>
<p>
{label} = <strong>{show.toString()}</strong>
</p>
{show && <Spinner name="line-scale" color="black" />}
</div>
)
const App = ({ submit, loading }) => (
<div style={styles.page}>
<button onClick={submit}>Submit Async</button>
<div style={styles.container}>
<Loading label="loading.global" show={loading.global > 0} />
<Loading label="loading.models.form" show={loading.model > 0} />
<Loading label="loading.effects.form.submit" show={loading.effect > 0} />
</div>
</div>
)
const mapState = (state) => ({
count: state.count,
loading: {
global: state.loading.global,
model: state.loading.models.count,
effect: state.loading.effects.count.submit,
},
})
const mapDispatch = (dispatch) => ({
submit: dispatch.count.submit,
})
export default connect(mapState, mapDispatch)(App)
|
import React from 'react';
import { css, ClassNames } from '@emotion/core';
import {
FacebookShareButton,
LinkedinShareButton,
TwitterShareButton,
RedditShareButton,
} from 'react-share';
import {
FaRedditAlien,
FaFacebookF,
FaLinkedinIn,
FaTwitter,
FaShare,
} from 'react-icons/fa';
import { red } from '../utils/colors';
const ShareButtons = () => {
const shareUrl = `https://isearthstillwarming.com`;
const title = `IsEarthStillWarming.com`;
const fullTitle = `IsEarthStillWarming.com: Global warming information and data`;
const share = () => window.navigator.share({
url: shareUrl,
text: `Global warming information and data`,
title,
});
if (
typeof window !== `undefined`
&& window.navigator
&& window.navigator.share
) {
return (
<div
css={css`
display: flex;
@media (max-width: 700px) {
justify-content: center;
}
justify-content: flex-end;
margin-top: 1.5rem;
margin-bottom: -1.5rem;
`}
>
<button
type="button"
css={css`
font-size: 0.8rem;
height: 1.75rem;
padding: 0 0.5rem;
border-radius: 4px;
border: none;
color: ${red};
border: 1px solid ${red};
font-weight: bold;
box-sizing: content-box;
cursor: pointer;
display: inline-flex;
justify-content: center;
align-items: center;
background-color: white;
:hover {
opacity: 0.8;
}
svg {
margin-right: 0.4rem;
}
`}
onClick={share}
>
<FaShare />
Share
</button>
</div>
);
}
return (
<ClassNames>
{({ css: style }) => (
<div
css={css`
margin-bottom: -1rem;
margin-top: 1rem;
display: flex;
align-items: center;
justify-content: flex-end;
.SocialMediaShareButton {
cursor: pointer;
:hover {
opacity: 0.9;
}
margin: 0 0.3rem;
color: white;
height: 1.6rem;
width: 1.6rem;
font-size: 0.9rem;
display: flex;
justify-content: center;
align-items: center;
border-radius: 50%;
overflow: hidden;
}
`}
>
<span
css={css`
padding-right: 0.4rem;
`}
>
Share:
</span>
<FacebookShareButton
className={style`
background-color: #3B579D;
`}
url={shareUrl}
quote={fullTitle}
>
<FaFacebookF />
</FacebookShareButton>
<TwitterShareButton
className={style`
background-color: #2CAAE1;
`}
url={shareUrl}
title={fullTitle}
>
<FaTwitter />
</TwitterShareButton>
<RedditShareButton
className={style`
background-color: #FF4500 !important;
`}
title={fullTitle}
url={shareUrl}
>
<FaRedditAlien />
</RedditShareButton>
<LinkedinShareButton
className={style`
background-color: #007BB6;
`}
url={shareUrl}
>
<FaLinkedinIn />
</LinkedinShareButton>
</div>
)}
</ClassNames>
);
};
export default ShareButtons;
|
const spawn = require('cross-spawn')
const path = require('path')
const currentVersion = require('./package.json').version
const plat = process.platform === 'win32' ? 'win' :
process.platform === 'darwin' ? 'macos' :
'linux'
const platBinary = `upm-${plat}.original${process.platform == 'win32' ? '.exe' : ''}`
// just do version
if (process.argv.indexOf('--proxy-version') != -1) {
console.log(currentVersion)
process.exit(0)
return
}
// patch in the flag to ignore TLS errors
let incomingEnv = process.env
incomingEnv['NODE_TLS_REJECT_UNAUTHORIZED'] = '0'
// run
const res = spawn.sync(`${path.join(path.dirname(process.execPath), platBinary)}`,
process.argv.slice(2),
{stdio: 'inherit', env: incomingEnv})
process.exit(res.status)
|
const Kafka = require('no-kafka');
const brain = require('brain.js');
const data = require('./data.json');
const producer = new Kafka.Producer();
const network = new brain.recurrent.LSTM();
var cond = '';
const trainingData = data.map(item => ({
input: item.text,
output: item.category
}));
network.train(trainingData, {
iterations: 1000,
log: true
});
// Create an instance of the Kafka consumer
const consumer = new Kafka.SimpleConsumer({"connectionString":"127.0.0.1:9092"})
var data2 = function (messageSet) {
messageSet.forEach(function (m) {
var value = JSON.parse(m.message.value);
cond = value.str;
console.log(cond);
sendProduction(cond);
//value.map(data => console.log(data.nome));
//console.log(JSON.stringify(value.idade));
//console.log(value.idade);
//valueSum = valueSum + value;
// console.log(valueSum);
})};
// Subscribe to the Kafka topic
return consumer.init().then(function () {
return consumer.subscribe('ia', data2);
});
function sendProduction(cond){
const output = network.run(cond);
producer.init().then(function(){
return producer.send({
topic: 'ia',
partition: 0,
message: {
value: output
}
});
})
.then(function (result) {
console.log('Result: '+JSON.stringify(result))
});
}
//testar direcionamento das url's por exemplo http://127.0.0.1:9092/test
//enviar e receber atraves do kafka, via python e javascript
//criar um projeto de exemplo.
//kafka-topics.sh --create --zookeeper zookeeper:2181 --replication-factor 1 --partitions 1 --topic ia
//sudo kafka-console-consumer --zookeeper zookeeper:2181 --topic testing --from-beginning
//sudo kafka-console-producer --broker-list localhost:9092 --topic testing
|
var Stage = {
}
|
import React, { useState, useEffect } from "react";
import { axiosWithAuth } from "./axiosAuth";
import "./post.css";
import '../index.css'
class Post extends React.Component {
state = {
recipe: {
name: "",
category: "1",
img: "",
ingredients: "",
instructions: ""
},
isFetching: false
};
handleChange = e => {
this.setState({
recipe: {
...this.state.recipe,
[e.target.name]: e.target.value
}
});
};
post = e => {
e.preventDefault();
this.setState({
value: e.target.value,
isFetching: true
});
//axios goes here
console.log("first", this.state.recipe);
axiosWithAuth()
.post("https://bwchefhub.herokuapp.com/api/recipes", this.state.recipe)
.then(res => {
console.log(res.data);
// this.setState({ recipe: [...res.data, res.data.payload] });
this.props.history.push("/profile");
})
.catch(err => console.log(err));
};
render() {
return (
<div className="main account2">
<h1>Enter all the details for your recipe</h1>
<form className="formStyle" onSubmit={this.post}>
<input
type="text"
name="name"
placeholder="Recipe Name"
value={this.state.recipe.name}
onChange={this.handleChange}
/>
<select
name="category"
onChange={this.handleChange}
value={this.state.recipe.category}
>
<option value="1">Breakfast</option>
<option value="2">Lunch</option>
<option selected value="3">
Dinner
</option>
<option value="4">Snack</option>
</select>
<input
type="text"
name="img"
placeholder="Image Link"
value={this.state.recipe.img}
onChange={this.handleChange}
/>
<input
className="area"
type="textarea"
cols={40}
rows={10}
name="ingredients"
placeholder="Ingredients"
value={this.state.recipe.ingredients}
onChange={this.handleChange}
/>
<input
className="area"
type="textarea"
name="instructions"
placeholder="Instructions"
value={this.state.recipe.instructions}
onChange={this.handleChange}
/>
<div className='button-container'>
<button className='add-button'> Post </button>
<br />
<button className="add-button" onClick={()=>this.props.history.goBack()}> Cancel </button>
</div>
</form>
</div>
);
}
}
export default Post;
|
import logo from "../images/logo.png";
import {
HeaderWrapper,
LogoLink,
RedirectToPath,
HeaderAccountLink,
} from "../styles";
import HeaderShoppingCart from "../containers/HeaderShoppingCart";
const Header = () => (
<HeaderWrapper>
<LogoLink to="/">
<img src={logo} alt="logo" />
</LogoLink>
<HeaderAccountLink>
<RedirectToPath to="/account">Account</RedirectToPath>
<HeaderShoppingCart />
</HeaderAccountLink>
</HeaderWrapper>
);
export default Header;
|
"use strict";
const {
MdsEntry,
MdsCollection,
} = require("../lib/mds");
const {
str2ab,
coerceToBase64Url,
jsObjectToB64,
} = require("../lib/utils");
const chai = require("chai");
const crypto = require("crypto");
const h = require("fido2-helpers");
const fs = require("fs");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
var assert = chai.assert;
describe("MdsCollection", function() {
it("is a function", function() {
assert.isFunction(MdsCollection);
});
it("is a class", function() {
var mdsCollection = new MdsCollection("test");
assert.isObject(mdsCollection);
assert.isFunction(mdsCollection.addToc);
assert.isFunction(mdsCollection.addEntry);
assert.isFunction(mdsCollection.validate);
assert.isFunction(mdsCollection.findEntry);
assert.strictEqual(mdsCollection.name, "test");
});
it("throws if no name specified in constructor", function() {
assert.throws(function() {
new MdsCollection();
}, Error, "expected 'collectionName' to be non-empty string, got: undefined");
});
it("throws if name is empty string", function() {
assert.throws(function() {
new MdsCollection("");
}, Error, "expected 'collectionName' to be non-empty string, got: ");
});
describe("addToc", function() {
var mc;
beforeEach(function() {
mc = new MdsCollection("test");
});
it("returns a promise", async function() {
var p = mc.addToc();
assert.instanceOf(p, Promise);
try {
await p;
} catch (e) {
// empty
}
});
it("rejects if no jwk provided", function() {
return assert.isRejected(mc.addToc(undefined), Error, "expected MDS TOC to be non-empty string");
});
it("rejects if TOC is empty string", function() {
// bad toc
var toc = "";
return assert.isRejected(mc.addToc(toc), Error, "expected MDS TOC to be non-empty string");
});
it("rejects if TOC is junk string", function() {
// bad toc
var toc = "sL39APyTmisrjh11vghaqNfuruLQmCfR0c1ryKtaQ81jkEhNa5u9xLTnkibvXC9YpzBLFwWEZ3k9CR_sxzm_pWYbBOtKxeZu9z2GT8b6QW4iQvRlyumCT3oENx_8401r";
return assert.isRejected(mc.addToc(toc), Error, "could not parse and validate MDS TOC: Unexpected token � in JSON at position 0");
});
it("rejects if TOC header is missing alg", function() {
var jwtHeader = {
// alg: "foo",
typ: "JWT",
x5c: [
"sL39APyTmisrjh11vghaqNfuruLQmCfR0c1ryKtaQ81jkEhNa5u9xLTnkibvXC9YpzBLFwWEZ3k9CR_sxzm_pWYbBOtKxeZu9z2GT8b6QW4iQvRlyumCT3oENx_8401r",
"sL39APyTmisrjh11vghaqNfuruLQmCfR0c1ryKtaQ81jkEhNa5u9xLTnkibvXC9YpzBLFwWEZ3k9CR_sxzm_pWYbBOtKxeZu9z2GT8b6QW4iQvRlyumCT3oENx_8401r",
],
};
jwtHeader = coerceToBase64Url(str2ab(JSON.stringify(jwtHeader)), "JWT header");
var jwtBody = "sL39APyTmisrjh11vghaqNfuruLQmCfR0c1ryKtaQ81jkEhNa5u9xLTnkibvXC9YpzBLFwWEZ3k9CR_sxzm_pWYbBOtKxeZu9z2GT8b6QW4iQvRlyumCT3oENx_8401r";
var jwtSig = "sL39APyTmisrjh11vghaqNfuruLQmCfR0c1ryKtaQ81jkEhNa5u9xLTnkibvXC9YpzBLFwWEZ3k9CR_sxzm_pWYbBOtKxeZu9z2GT8b6QW4iQvRlyumCT3oENx_8401r";
var toc = jwtHeader + "." + jwtBody + "." + jwtSig;
return assert.isRejected(mc.addToc(toc), Error, "could not parse and validate MDS TOC: Algorithm not allowed: undefined");
});
it("rejects if TOC header is missing typ", function() {
var jwtHeader = {
alg: "foo",
// typ: "JWT",
x5c: [
"sL39APyTmisrjh11vghaqNfuruLQmCfR0c1ryKtaQ81jkEhNa5u9xLTnkibvXC9YpzBLFwWEZ3k9CR_sxzm_pWYbBOtKxeZu9z2GT8b6QW4iQvRlyumCT3oENx_8401r",
"sL39APyTmisrjh11vghaqNfuruLQmCfR0c1ryKtaQ81jkEhNa5u9xLTnkibvXC9YpzBLFwWEZ3k9CR_sxzm_pWYbBOtKxeZu9z2GT8b6QW4iQvRlyumCT3oENx_8401r",
],
};
jwtHeader = coerceToBase64Url(str2ab(JSON.stringify(jwtHeader)), "JWT header");
var jwtBody = "sL39APyTmisrjh11vghaqNfuruLQmCfR0c1ryKtaQ81jkEhNa5u9xLTnkibvXC9YpzBLFwWEZ3k9CR_sxzm_pWYbBOtKxeZu9z2GT8b6QW4iQvRlyumCT3oENx_8401r";
var jwtSig = "sL39APyTmisrjh11vghaqNfuruLQmCfR0c1ryKtaQ81jkEhNa5u9xLTnkibvXC9YpzBLFwWEZ3k9CR_sxzm_pWYbBOtKxeZu9z2GT8b6QW4iQvRlyumCT3oENx_8401r";
var toc = jwtHeader + "." + jwtBody + "." + jwtSig;
return assert.isRejected(mc.addToc(toc), Error, "could not parse and validate MDS TOC: no key found");
});
it("rejects if TOC header x5c only has one entry", function() {
var jwtHeader = {
alg: "foo",
typ: "JWT",
x5c: [
"sL39APyTmisrjh11vghaqNfuruLQmCfR0c1ryKtaQ81jkEhNa5u9xLTnkibvXC9YpzBLFwWEZ3k9CR_sxzm_pWYbBOtKxeZu9z2GT8b6QW4iQvRlyumCT3oENx_8401r",
// "sL39APyTmisrjh11vghaqNfuruLQmCfR0c1ryKtaQ81jkEhNa5u9xLTnkibvXC9YpzBLFwWEZ3k9CR_sxzm_pWYbBOtKxeZu9z2GT8b6QW4iQvRlyumCT3oENx_8401r"
],
};
jwtHeader = coerceToBase64Url(str2ab(JSON.stringify(jwtHeader)), "JWT header");
var jwtBody = "sL39APyTmisrjh11vghaqNfuruLQmCfR0c1ryKtaQ81jkEhNa5u9xLTnkibvXC9YpzBLFwWEZ3k9CR_sxzm_pWYbBOtKxeZu9z2GT8b6QW4iQvRlyumCT3oENx_8401r";
var jwtSig = "sL39APyTmisrjh11vghaqNfuruLQmCfR0c1ryKtaQ81jkEhNa5u9xLTnkibvXC9YpzBLFwWEZ3k9CR_sxzm_pWYbBOtKxeZu9z2GT8b6QW4iQvRlyumCT3oENx_8401r";
var toc = jwtHeader + "." + jwtBody + "." + jwtSig;
return assert.isRejected(mc.addToc(toc), Error, "could not parse and validate MDS TOC: no key found");
});
it("rejects if TOC header x5c is missing", function() {
var jwtHeader = {
alg: "foo",
typ: "JWT",
// x5c: [
// "sL39APyTmisrjh11vghaqNfuruLQmCfR0c1ryKtaQ81jkEhNa5u9xLTnkibvXC9YpzBLFwWEZ3k9CR_sxzm_pWYbBOtKxeZu9z2GT8b6QW4iQvRlyumCT3oENx_8401r",
// "sL39APyTmisrjh11vghaqNfuruLQmCfR0c1ryKtaQ81jkEhNa5u9xLTnkibvXC9YpzBLFwWEZ3k9CR_sxzm_pWYbBOtKxeZu9z2GT8b6QW4iQvRlyumCT3oENx_8401r"
// ]
};
jwtHeader = coerceToBase64Url(str2ab(JSON.stringify(jwtHeader)), "JWT header");
var jwtBody = "sL39APyTmisrjh11vghaqNfuruLQmCfR0c1ryKtaQ81jkEhNa5u9xLTnkibvXC9YpzBLFwWEZ3k9CR_sxzm_pWYbBOtKxeZu9z2GT8b6QW4iQvRlyumCT3oENx_8401r";
var jwtSig = "sL39APyTmisrjh11vghaqNfuruLQmCfR0c1ryKtaQ81jkEhNa5u9xLTnkibvXC9YpzBLFwWEZ3k9CR_sxzm_pWYbBOtKxeZu9z2GT8b6QW4iQvRlyumCT3oENx_8401r";
var toc = jwtHeader + "." + jwtBody + "." + jwtSig;
return assert.isRejected(mc.addToc(toc), Error, "could not parse and validate MDS TOC: no key found");
});
it("parses MDS1 TOC", async function() {
var toc = await mc.addToc(
h.mds.mds1TocJwt,
h.mds.mdsRootCert,
[
h.mds.mdsRootCrl,
h.mds.ca1Crl,
]
);
assert.isObject(toc);
assert.isString(toc.nextUpdate);
assert.strictEqual(toc.nextUpdate, "2018-06-18");
assert.isNumber(toc.no);
assert.strictEqual(toc.no, 62);
assert.isArray(toc.entries);
assert.strictEqual(toc.entries.length, 66);
assert.isString(toc.raw);
assert.strictEqual(toc.raw, h.mds.mds1TocJwt);
});
it("parses MDS2 TOC", async function() {
var toc = await mc.addToc(
h.mds.mds2TocJwt,
h.mds.mdsRootCert,
[
h.mds.mdsRootCrl,
h.mds.ca1Crl,
]
);
assert.isObject(toc);
assert.isString(toc.nextUpdate);
assert.strictEqual(toc.nextUpdate, "2018-06-18");
assert.isString(toc.legalHeader);
assert.isNumber(toc.no);
assert.strictEqual(toc.no, 2);
assert.isArray(toc.entries);
assert.strictEqual(toc.entries.length, 7);
assert.isString(toc.raw);
});
it("works with array of root certs", function() {
return mc.addToc(
h.mds.mds1TocJwt,
[
h.mds.mdsRootCert,
],
[
h.mds.mdsRootCrl,
h.mds.ca1Crl,
]
);
});
it("MDS1 works with default root cert", function() {
return mc.addToc(h.mds.mds1TocJwt);
});
it("MDS2 works with default root cert", function() {
return mc.addToc(h.mds.mds2TocJwt);
});
it("works with no CRLs", function() {
return mc.addToc(
h.mds.mds1TocJwt,
h.mds.mdsRootCert
);
});
it("parses MDS2 TOC", function() {
return mc.addToc(h.mds.mds2TocJwt);
});
it("throws on bad signature", function() {
var tocParts = h.mds.mds2TocJwt.split(".");
tocParts[2] = tocParts[2].toUpperCase(); // mess up the signature
var toc = tocParts.join(".");
return assert.isRejected(mc.addToc(toc), Error, "could not parse and validate MDS TOC: no key found");
});
it("throws on bad cert chain", function() {
return assert.isRejected(mc.addToc(h.mds.mds2TocJwt, [h.certs.yubicoRoot]), Error, "No valid certificate paths found");
});
});
describe("getToc", function() {
var mc;
beforeEach(function() {
mc = new MdsCollection("test");
});
it("starts as null", function() {
var toc = mc.getToc();
assert.isNull(mc.toc);
assert.isNull(toc);
});
it("returns correct object for MDS1", async function() {
assert.isNull(mc.toc);
await mc.addToc(h.mds.mds1TocJwt);
var toc = mc.getToc();
assert.isObject(toc);
assert.isString(toc.nextUpdate);
assert.strictEqual(toc.nextUpdate, "2018-06-18");
assert.isNumber(toc.no);
assert.strictEqual(toc.no, 62);
assert.isArray(toc.entries);
assert.strictEqual(toc.entries.length, 66);
assert.isString(toc.raw);
assert.strictEqual(toc.raw, h.mds.mds1TocJwt);
});
it("returns correct object for MDS2", async function() {
assert.isNull(mc.toc);
await mc.addToc(h.mds.mds2TocJwt);
var toc = mc.getToc();
assert.isObject(toc);
assert.isString(toc.nextUpdate);
assert.strictEqual(toc.nextUpdate, "2018-06-18");
assert.isString(toc.legalHeader);
assert.isNumber(toc.no);
assert.strictEqual(toc.no, 2);
assert.isArray(toc.entries);
assert.strictEqual(toc.entries.length, 7);
assert.isString(toc.raw);
assert.strictEqual(toc.raw, h.mds.mds2TocJwt);
});
});
describe("addEntry", function() {
var mc;
beforeEach(function() {
mc = new MdsCollection("test");
});
it("throws on invalid jwk", function() {
assert.throws(function() {
mc.addEntry();
}, Error, "expected MDS entry to be non-empty string");
});
it("creates new MDS1 entry");
it("creates new MDS1 UAF entry", function() {
assert.strictEqual(mc.unvalidatedEntryList.size, 0);
mc.addEntry(h.mds.mds1UafEntry);
assert.strictEqual(mc.unvalidatedEntryList.size, 1);
});
it("creates new MDS1 U2F entry", function() {
assert.strictEqual(mc.unvalidatedEntryList.size, 0);
mc.addEntry(h.mds.mds1U2fEntry);
assert.strictEqual(mc.unvalidatedEntryList.size, 1);
assert.isTrue(mc.unvalidatedEntryList.has("923881fe2f214ee465484371aeb72e97f5a58e0a"));
});
it("creates new MDS2 UAF entry", function() {
assert.strictEqual(mc.unvalidatedEntryList.size, 0);
mc.addEntry(h.mds.mds2UafEntry);
assert.strictEqual(mc.unvalidatedEntryList.size, 1);
assert.isTrue(mc.unvalidatedEntryList.has("4e4e#4005"));
});
it("has raw");
it("has correct ID");
});
describe("validate", function() {
var mc;
beforeEach(function() {
mc = new MdsCollection("test");
});
it("throws if no TOC", function() {
mc.addEntry(h.mds.mds2UafEntry);
assert.throws(function() {
mc.validate();
}, Error, "add MDS TOC before attempting to validate MDS collection");
});
it("throws if entry hash doesn't match TOC hash");
it("throws if no entries", async function() {
await mc.addToc(h.mds.mds2TocJwt);
assert.throws(function() {
mc.validate();
}, Error, "add MDS entries before attempting to validate MDS collection");
});
it("adds MDS1 U2F entry", async function() {
await mc.addToc(h.mds.mds1TocJwt);
mc.addEntry(h.mds.mds1U2fEntry);
mc.validate();
assert.strictEqual(mc.entryList.size, 1);
assert.isTrue(mc.entryList.has("923881fe2f214ee465484371aeb72e97f5a58e0a"), "added entry 4e4e#4005");
var entry = mc.entryList.get("923881fe2f214ee465484371aeb72e97f5a58e0a");
assert.strictEqual(entry.protocolFamily, "u2f");
assert.strictEqual(entry.authenticationAlgorithm, "ALG_SIGN_SECP256R1_ECDSA_SHA256_RAW");
assert.strictEqual(entry.publicKeyAlgAndEncoding, "ALG_KEY_ECC_X962_RAW");
assert.deepEqual(entry.attestationTypes, ["basic-full"]);
assert.deepEqual(entry.userVerificationDetails, [[{ userVerification: ["fingerprint"] }]]);
assert.strictEqual(entry.isSecondFactorOnly, true);
assert.deepEqual(entry.statusReports, [
{
status: "FIDO_CERTIFIED",
url: "",
certificate: "",
effectiveDate: "2017-11-28",
},
]);
});
it("adds MDS1 UAF entry", async function() {
await mc.addToc(h.mds.mds1TocJwt);
mc.addEntry(h.mds.mds1UafEntry);
mc.validate();
assert.strictEqual(mc.entryList.size, 1);
assert.isTrue(mc.entryList.has("0013#0001"), "added entry 4e4e#4005");
var entry = mc.entryList.get("0013#0001");
assert.strictEqual(entry.protocolFamily, "uaf");
assert.strictEqual(entry.hash, "06LZxJ5mNuNZj48IZLV816bfp3A7GVtO2O-EeQ1pkTY=");
assert.strictEqual(entry.aaid, "0013#0001");
assert.strictEqual(entry.timeOfLastStatusChange, "2015-05-20");
});
it("adds MDS1 FIDO2 entry");
it("adds MDS2 U2F entry");
it("adds MDS2 FIDO2 entry");
it("adds MDS2 UAF entry", async function() {
await mc.addToc(h.mds.mds2TocJwt);
mc.addEntry(h.mds.mds2UafEntry);
mc.validate();
assert.strictEqual(mc.entryList.size, 1);
assert.isTrue(mc.entryList.has("4e4e#4005"), "added entry 4e4e#4005");
var entry = mc.entryList.get("4e4e#4005");
// check that TOC data was copied to new entry:
// url
assert.strictEqual(entry.url, "https://mds2.fidoalliance.org/metadata/4e4e%234005");
// timeOfLastStatusChange
assert.strictEqual(entry.timeOfLastStatusChange, "2018-05-19");
// hash
assert.strictEqual(entry.hash, "iuRviMMnBrXnVrjI0TiacTzKqdG8VXTA6PUy4r7Sxhk=");
// id
assert.strictEqual(entry.aaid, "4e4e#4005");
assert.isUndefined(entry.aaguid);
assert.isUndefined(entry.attestationCertificateKeyIdentifiers);
// statusReports
assert.isArray(entry.statusReports);
assert.strictEqual(entry.statusReports.length, 1);
// check the entry data was copied to new entry:
// assertionScheme
assert.strictEqual(entry.assertionScheme, "UAFV1TLV");
// attachmentHint
assert.isArray(entry.attachmentHint);
assert.strictEqual(entry.attachmentHint.length, 1);
assert.isTrue(entry.attachmentHint.includes("internal"));
// attestationRootCertificates
assert.isArray(entry.attestationRootCertificates);
assert.strictEqual(entry.attestationRootCertificates.length, 0);
// attestationTypes
assert.isArray(entry.attestationTypes);
assert.strictEqual(entry.attestationTypes.length, 1);
assert.isTrue(entry.attestationTypes.includes("basic-surrogate"));
// authenticationAlgorithm
assert.strictEqual(entry.authenticationAlgorithm, "ALG_SIGN_RSA_EMSA_PKCS1_SHA256_RAW");
// authenticatorVersion
assert.strictEqual(entry.authenticatorVersion, 256);
// description
assert.strictEqual(entry.description, "Touch ID, Face ID, or Passcode");
// icon
assert.isString(entry.icon);
// isSecondFactorOnly
assert.isFalse(entry.isSecondFactorOnly);
// keyProtection
assert.isArray(entry.keyProtection);
assert.strictEqual(entry.keyProtection.length, 2);
assert.isTrue(entry.keyProtection.includes("hardware"));
assert.isTrue(entry.keyProtection.includes("tee"));
// legalHeader
assert.isString(entry.legalHeader);
// matcherProtection
assert.isArray(entry.matcherProtection);
assert.strictEqual(entry.matcherProtection.length, 1);
assert.isTrue(entry.matcherProtection.includes("hardware"));
// protocolFamily
assert.strictEqual(entry.protocolFamily, "uaf");
// publicKeyAlgAndEncoding
assert.strictEqual(entry.publicKeyAlgAndEncoding, "ALG_KEY_RSA_2048_RAW");
// tcDisplay
assert.isArray(entry.tcDisplay);
assert.strictEqual(entry.tcDisplay.length, 1);
assert.isTrue(entry.tcDisplay.includes("any"));
assert.strictEqual(entry.tcDisplayContentType, "text/plain");
assert.deepEqual(entry.upv, [
{
major: 1,
minor: 1,
}, {
major: 1,
minor: 0,
},
]);
assert.isArray(entry.userVerificationDetails);
assert.strictEqual(entry.userVerificationDetails.length, 2);
assert.isArray(entry.userVerificationDetails[0]);
assert.deepEqual(
entry.userVerificationDetails[0],
[
{
type: "code",
userVerification: ["passcode"],
base: 10,
blockSlowdown: 60,
maxRetries: 5,
minLength: 4,
},
]
);
assert.isArray(entry.userVerificationDetails[1]);
assert.deepEqual(
entry.userVerificationDetails[1],
[
{
type: "biometric",
userVerification: ["fingerprint"],
blockSlowdown: 0,
maxReferenceDataSets: 5,
maxRetries: 5,
},
]
);
// raw
assert.isString(entry.raw);
// collection
assert.instanceOf(entry.collection, MdsCollection);
});
it("adds MDS3 UAF entry", async function() {
await mc.addToc(fs.readFileSync("./test/mdsV3.jwt", "utf8"));
mc.addEntry("ewogICAgICAiYWFpZCI6ICI0ZTRlIzQwMDUiLAogICAgICAibWV0YWRhdGFTdGF0ZW1lbnQiOiB7CiAgICAgICAgImxlZ2FsSGVhZGVyIjogImh0dHBzOi8vZmlkb2FsbGlhbmNlLm9yZy9tZXRhZGF0YS9tZXRhZGF0YS1zdGF0ZW1lbnQtbGVnYWwtaGVhZGVyLyIsCiAgICAgICAgImFhaWQiOiAiNGU0ZSM0MDA1IiwKICAgICAgICAiZGVzY3JpcHRpb24iOiAiVG91Y2ggSUQsIEZhY2UgSUQsIG9yIFBhc3Njb2RlIiwKICAgICAgICAiYXV0aGVudGljYXRvclZlcnNpb24iOiAyNTYsCiAgICAgICAgInByb3RvY29sRmFtaWx5IjogInVhZiIsCiAgICAgICAgInNjaGVtYSI6IDMsCiAgICAgICAgInVwdiI6IFsKICAgICAgICAgIHsKICAgICAgICAgICAgIm1ham9yIjogMSwKICAgICAgICAgICAgIm1pbm9yIjogMAogICAgICAgICAgfSwKICAgICAgICAgIHsKICAgICAgICAgICAgIm1ham9yIjogMSwKICAgICAgICAgICAgIm1pbm9yIjogMQogICAgICAgICAgfQogICAgICAgIF0sCiAgICAgICAgImF1dGhlbnRpY2F0aW9uQWxnb3JpdGhtcyI6IFsKICAgICAgICAgICJyc2FfZW1zYV9wa2NzMV9zaGEyNTZfcmF3IgogICAgICAgIF0sCiAgICAgICAgInB1YmxpY0tleUFsZ0FuZEVuY29kaW5ncyI6IFsKICAgICAgICAgICJyc2FfMjA0OF9yYXciCiAgICAgICAgXSwKICAgICAgICAiYXR0ZXN0YXRpb25UeXBlcyI6IFsKICAgICAgICAgICJiYXNpY19zdXJyb2dhdGUiCiAgICAgICAgXSwKICAgICAgICAidXNlclZlcmlmaWNhdGlvbkRldGFpbHMiOiBbCiAgICAgICAgICBbCiAgICAgICAgICAgIHsKICAgICAgICAgICAgICAidXNlclZlcmlmaWNhdGlvbk1ldGhvZCI6ICJwYXNzY29kZV9pbnRlcm5hbCIsCiAgICAgICAgICAgICAgImNhRGVzYyI6IHsKICAgICAgICAgICAgICAgICJiYXNlIjogMTAsCiAgICAgICAgICAgICAgICAibWluTGVuZ3RoIjogNCwKICAgICAgICAgICAgICAgICJtYXhSZXRyaWVzIjogNSwKICAgICAgICAgICAgICAgICJibG9ja1Nsb3dkb3duIjogNjAKICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICAgIF0sCiAgICAgICAgICBbCiAgICAgICAgICAgIHsKICAgICAgICAgICAgICAidXNlclZlcmlmaWNhdGlvbk1ldGhvZCI6ICJmaW5nZXJwcmludF9pbnRlcm5hbCIsCiAgICAgICAgICAgICAgImJhRGVzYyI6IHsKICAgICAgICAgICAgICAgICJzZWxmQXR0ZXN0ZWRGUlIiOiAwLAogICAgICAgICAgICAgICAgInNlbGZBdHRlc3RlZEZBUiI6IDAsCiAgICAgICAgICAgICAgICAibWF4VGVtcGxhdGVzIjogMCwKICAgICAgICAgICAgICAgICJtYXhSZXRyaWVzIjogNSwKICAgICAgICAgICAgICAgICJibG9ja1Nsb3dkb3duIjogMAogICAgICAgICAgICAgIH0KICAgICAgICAgICAgfQogICAgICAgICAgXQogICAgICAgIF0sCiAgICAgICAgImtleVByb3RlY3Rpb24iOiBbCiAgICAgICAgICAiaGFyZHdhcmUiLAogICAgICAgICAgInRlZSIKICAgICAgICBdLAogICAgICAgICJtYXRjaGVyUHJvdGVjdGlvbiI6IFsKICAgICAgICAgICJ0ZWUiCiAgICAgICAgXSwKICAgICAgICAiYXR0YWNobWVudEhpbnQiOiBbCiAgICAgICAgICAiaW50ZXJuYWwiCiAgICAgICAgXSwKICAgICAgICAidGNEaXNwbGF5IjogWwogICAgICAgICAgImFueSIKICAgICAgICBdLAogICAgICAgICJ0Y0Rpc3BsYXlDb250ZW50VHlwZSI6ICJ0ZXh0L3BsYWluIiwKICAgICAgICAiYXR0ZXN0YXRpb25Sb290Q2VydGlmaWNhdGVzIjogW10sCiAgICAgICAgImljb24iOiAiZGF0YTppbWFnZS9wbmc7YmFzZTY0LGlWQk9SdzBLR2dvQUFBQU5TVWhFVWdBQUFFZ0FBQUJJQ0FZQUFBQlY3Yk5IQUFBQUFYTlNSMElBcnM0YzZRQUFBQnhwUkU5VUFBQUFBZ0FBQUFBQUFBQWtBQUFBS0FBQUFDUUFBQUFrQUFBRkpidUoyRWtBQUFUeFNVUkJWSGdCN0pZeGJpTkhFRVVGSjE0WUM1akpBZ3NuSHNPT0hQRUFDMmh5QitJTk5LRXpNblNtdWNCaWVRUHlCbUxnbkx5QmVBUFNKMWplZ0g2ZjZocVV5OVBhWGcwSk8rQUFYOTFkVlYzOS81L21RRGZINC9IbWlyd0hWM08rY0VHdUJsME55djk4U2o0dDF4dDB2VUhYRzNUUlg4R2c1amNEbjU5L3JMNERIOEFNYkJ4V3pGdndHM2cvOEpoaEdrcytWTG1hMXhKSDlBVEloR01oWkY3ejJ2TnkvRXZpdzl6OVNzYUlyTUcrMEpRKzg3UjM4cFhIRHROWTRtS3VwcFFvb2taZ0hveFpzLzRFcHVEMkJTaXZPdFdiYWJwOW85THpjL3hMNHNQY0xXQ0lrQXBzd1djZ29iZDkyNGlycm5ZWXh6cHlNdm9PTE1CZjRGODFjWS9XSlVia2FvWnQ3bVBqWWhJQS9nUjNMbnpEV21iTXdBcnNnZDJNdmxINURXaEJad2h6bWZVNytOWDM3cHZueEpmRUwyWVF4TitERDBhWXVRVEpsQzNvTTZJMGRtRC9IRlN1OXp1Yjk0MGxSdVJxTG1JUTVMODFvaElDOVBZbHJOU0UwanJkckZwbk1YNWpaOFl4Sjc0a2ZoR0RqQ0NrWnlCbnpJN2NBa3pCTGFoc240MHBybStPdmwxUElHZmNpdHdQdGkrT0pVYmthaTVpRUdUSFlOc2o2RE14aWUyK0pWSE1TMnYyNlRaT2djeU5adWxGOVBiTmlTK0puOTBnU09vL1k1SDFBbVRNQXhoNUE3UUdOWmlCRnN6QkJxelNXckVKcVB3K3pZbmRneDA0QnZ3VWEwdU15TldjMVNDSXlweEkrSkZZWmFTWmowQURaRVNzZldtOXAzNEphdXVsa2JWdWxGNkE3ZDM0dk9ZNThTWHhZWnNkRXdpK2RTUkZWcVFiVnlJeExUZ0FFL1BhY2U5N002L0FrK3RiKzNOTGpNalZuTk9ncFNNb2M3cnZnZVpnNi9MUm1EVTU0Y0hoTWNYVTY1aUJqT3JNWVA0cDFXMytWd1pCNnZ0RVRFSWt5SnZUc0k2M1JqVUwwUHRmdFJlbnVmcUJLWGdDZldiTmlaKytiNHc2VHpXMTljbmRqcEw0V1c0UVpHYUpWSjg1VVpDTStjZkgyb1JvbERDRGo5dWNuTXhhZzloM1M4eWJ0TFE5SlVia2FzNWxrTWlKY0dPa05FOHhFeUx6YXN0clpEMUtkU3ZHUGJCYVB4NklLNjkrbmJITWE3QURzWGFjZW5mMU9mRWw4Y0VHUVhDY1NENmFlTllpNTRuSG0xV1JYNFlhWDUrYnl5enRxNUlKSSthTDBFYzFadEl2cWlzeElsY3piRE9IUTJZRzlHMnc2ejFtN2dWR2MxUXZFYjdtTmZOVzR2WFE2eUgwMjdQdWJsdE9mRW44SEFiTmpReWp6UEhpb3psNis5RU0xU3pBSFRpOStXZlpKK0ZWaWl1dnVyaDNROHhlVEJQeUcrdFRZa1N1WnJCQlJrSkV3VGFRN0FRVGx4Z3ZVSUx2UWZlbW1jdmdHV2dUYXV1dmtaanFvMUU2MDB4YU1QZG50TnFYRTE4U0g3WlpwNmNIWXRHY3h1V1dnZmlqaVZJTjh3blloeG92VlB1clZEdGlydjArNzAxYWg5emJFaU55TldjeENFTFJnRlppOUpDYkJjS0w1OHp6MzU2OVhuaWN6MjB2KzZhaDcwWTVZakxRMzdJbUo3NGtQc2dnaUx3QksrQ0ZkQVlRYjBMdWliWDlIQ1JrRy9McW81cDFnaGRxWjJpUDlZajlUd2FTOS9GTmlSRzVtcUVHZllTTUVkZm96Um1IM0pmTVVYNXNOOFJHWXZkZ0YzcDVreFloZCtwQmJKM2kvNmxCRzBjdW1uTndPZDJFVGp4ekNUdzYrTDBWOFNWUTd6blFlZ1NpRVZ0bm9zeTFmcWM0NjdIRmNyZWpKRDcwQmttRWlEMDRzaUoyTUhLTTBSeUpOekVhdlRsdHlGbGRvLzZxRGZsNWluZG1wTHpWcjdVdU1TSlhNOVNnUHlCUWlhUWU1ZzN3NWtoZ2Mwbys1NWVzVGJSR2IwN00rYnF1ai9hRUhyWDZFL1A3OXlsV3F6WW52aVEreUNDUnNBY2k4MEJjTjJmaThsNUFOS2NOZS9XVGVRQzdFQitySDdHK24xUVZhazlucTdiRWlGek4zd0FBQVAvL1g5TGxQd0FBQlBOSlJFRlU3VnE3amlOVkZCd2tKQkNzdEIwUUVleTJJR1NEenBhTURzbldNY2wyU0xDU0hSQnNOdjRBeERnaVFuTC93WFJBUGkzeEFUYjhnUDBIMjM4d1ZMVlBtZG9yejROeDBHM0pWNm81OTlZNTUvcFV6WjFaYVRVWHQ3ZTNGMC9GQmRhM0wvTUNXQU8zaGcva21lZkNmbVk1MXEyQUxITFZQYmtzYW5YM2xuMUFrZlJVY1ZkdGZCUGM3S242MlBka2M5aU1ZZDdaUUJKQjhUbUg0OExlaDA3Tm9kRE83dGdidCt2ZWZ3Tm91TzVmSExoM0cxeHFYSTYrZkVpRFdodWNBcTZBL21VY0VQR1FPVFNCZ2lZQTd5WG1RQlZSQmpIbUFlY204WmswV2Z5TTNKQUdOVEhNQnJIa01GellaMEFiT1EzTHdYdnpFUG1kN3BKOEdiMnF2eS9XVVZ2YkhVMXdNK05hY2tNYTlCN0RYSElJTFp4TElCWHY1bFFIOHBYMTh5WGRaNDV5ZVh5V3pvd1pVQ1Q5ejRZMDZETVR4b0diWkRnT3ZRVDBjbWlPQzZJWkU5M0JpRFB2bVFLWHdCV3dBYnhIKzBYVWU3Ni9LK2w1UFpoQkpxakdVT21yb1pBcGE3aXdaNDNFTWRLY1lwZTkveXZxU21BRmVQK1dYZUQ4WHBubVhEbVlRUmp1eTJSb0NhQ1lYanhpRHF5VHVvL01RVzRDVUZScjRHdXNnRXoyWWI4RTlCbjRON2czaURYaTFzSE5qQ3NHTXlpRzJkZ3dGUDZXUEJmMkhMU3pQSVhRdkY0MFlnbHNBUW04S3k2c1p4bjFxL2lNM1B1RDQ3MjZLeHZhSUE2L0Fkd1lEdGpha0JyMmlnSzRrR09mK01mRU5lcjdWN203NGIrdnlUMTlUWEM5aVVNYjlGeWpZcWk3ak9ITG1saGRuWWpxRFFhWHN3WXhBOTRBUzhETjY1alRQWXJnK0NwVlY1SVBic0g5b0FiRk1EOWhJSDZITmFUSEpmaTlLT3hUYy9hdmluZWxDL1VsUUlOMVozdWdwclY4eVR6TzVBcnV4MkJRYlFOS3lBMjRrZ055WWM5WHdhR1ZaNno2NUM1ZjRkeEVEZVBFY2dYT2J0SytqelhSbzN0bndmV1IrekVZVkdKSURYaU5mY25CdEhDZUFKM1Y3TTBCbHdHcGNicXJZWjczSVBJTzhWdmRIVG52bndkWE1uSU5iaENId1BDL0FEbjNXamlYZ0E5UGdYd0pGV3NRYWM0YWtQQkRzV1l0RitwdXJOWmZtSDlHRmJYUEdMbEdZZEJ1bEY1RUFSRUxZR3RpSkh3RnJtQXRZbW9PalpzQ2VVVDFNSmJSVTJFdmZrR09DMXhyZk5tVDltVTBCbUhJZjJ4UUNXSHN4V3RtbkduaTJtcVo3NDJ6bXBubEcvSTQ1OGExVnJzMXZoU3ZPQ2FEU2h1VXhtd0F2b3BNdzJJL0FUcEFCdTdOQWNkK3IyV3VyN04rOVhVSE9PWStGNjg0R29NNEVBYjhEYmdDQ2cwWVBNVzNnQVF5dWpsMTVGeTQxK2R4ejc3ZjdoWDNON2wwamNvZ0h3NkNDNEEvS3VzUUx5R01LeUJuUFNKclBOZS9JbkJ1VUlZem9ibzJldWZHdlNLWHJ0RVpoSUZmQVZzYlhLSVkrV3FtRW9GOWxkVE5tUVBuWm53SWJtSzFUWERyNEJZOEgxcWpNNGhEWXVoVStBYmNKZEMvanFpWmhUZ2FSeXdsRVB1NTVlcW9yNDFqYng3bmEvVWRpcU0wS0FUOURBSDhmZlRHQjhjNUF4cEF4cVRtRkVtdWpKN09lSm96Qi9panVqZmRQMGY3MFJxa0FSVXBKRVM1ME5RYzFtd0JtZGUvRHB3WHhqWFlzKzVQUnQxL1Z4eTlRUkR4QXZnZDZBQUpWNXhLR0hJVXZiYWFUWENGY2V6amkvcFJmUS9GMFJ0RUFSQ1VBemVBak9FK2x6anNhVUpuZWY0eUo1Y0JhK04veGY0TDlUMG1ub1JCRWdKeHI0SHZkV2JFZVFiSU9FWTNwNDBjdWVrM0wxNSs0cjJQMlorVVFTNElncjhDL2dnRFpOQUdaNzJjdjdDL0J0NEN6NzMzLyt4UDFpQ0poSGorR1AwQWZBZDhHdmhhK1dQallBWWQ4OEduMG52VS81V2Npc2hqNWp3YjlNQ2YvNXdOT2h2MDlEOFE0NC9tK1FXZFg5QnhMK2hmVXdUWXlSQ2FyWjhBQUFBQVNVVk9SSzVDWUlJPSIKICAgICAgfSwKICAgICAgInN0YXR1c1JlcG9ydHMiOiBbCiAgICAgICAgewogICAgICAgICAgInN0YXR1cyI6ICJOT1RfRklET19DRVJUSUZJRUQiLAogICAgICAgICAgImVmZmVjdGl2ZURhdGUiOiAiMjAxOC0wNS0xOSIKICAgICAgICB9CiAgICAgIF0sCiAgICAgICJ0aW1lT2ZMYXN0U3RhdHVzQ2hhbmdlIjogIjIwMTgtMDUtMTkiCiAgICB9");
mc.validate();
assert.isTrue(mc.entryList.has("4e4e#4005"), "added entry 4e4e#4005");
var entry = mc.entryList.get("4e4e#4005");
// check that TOC data was copied to new entry:
// schema
assert.strictEqual(entry.schema, 3);
// timeOfLastStatusChange
assert.strictEqual(entry.timeOfLastStatusChange, "2018-05-19");
// hash
assert.isUndefined(entry.hash);
let tocHash = crypto.createHash("sha256");
tocHash.update(jsObjectToB64(entry.raw));
tocHash = tocHash.digest().toString("base64");
assert.strictEqual(tocHash, "KuTk5OTMPHkbY7bREv6ocsu8J739llB9u6ya1JPnqW4=");
// id
assert.strictEqual(entry.aaid, "4e4e#4005");
assert.isUndefined(entry.aaguid);
assert.isUndefined(entry.attestationCertificateKeyIdentifiers);
// statusReports
assert.isArray(entry.statusReports);
assert.strictEqual(entry.statusReports.length, 1);
// check the entry data was copied to new entry:
// description
assert.strictEqual(entry.description, "Touch ID, Face ID, or Passcode");
// authenticatorVersion
assert.strictEqual(entry.authenticatorVersion, 256);
// protocolFamily
assert.strictEqual(entry.protocolFamily, "uaf");
assert.deepEqual(entry.upv, [
{
major: 1,
minor: 0,
},
{
major: 1,
minor: 1,
},
]);
// authenticationAlgorithms
assert.deepEqual(entry.authenticationAlgorithms, [ "rsa_emsa_pkcs1_sha256_raw" ]);
// publicKeyAlgAndEncoding
assert.deepEqual(entry.publicKeyAlgAndEncodings, [ "rsa_2048_raw" ]);
// attestationTypes
assert.deepEqual(entry.attestationTypes, [ "basic_surrogate" ]);
// userVerificationDetails
assert.strictEqual(entry.userVerificationDetails.length, 2);
assert.deepEqual(
entry.userVerificationDetails[0],
[
{
base: 10,
blockSlowdown: 60,
maxRetries: 5,
minLength: 4,
type: "code",
userVerification: "passcode",
},
]
);
assert.deepEqual(
entry.userVerificationDetails[1],
[
{
blockSlowdown: 0,
maxRetries: 5,
maxTemplates: 0,
selfAttestedFAR: 0,
selfAttestedFRR: 0,
type: "biometric",
userVerification: "fingerprint",
},
]
);
// keyProtection
assert.deepEqual(entry.keyProtection, [ "hardware", "tee" ]);
// matcherProtection
assert.deepEqual(entry.matcherProtection, [ "tee" ]);
// attachmentHint
assert.deepEqual(entry.attachmentHint, [ "internal" ]);
// tcDisplay
assert.deepEqual(entry.tcDisplay, [ "any" ]);
// tcDisplayContentType
assert.strictEqual(entry.tcDisplayContentType, "text/plain");
// attestationRootCertificates
assert.deepEqual(entry.attestationRootCertificates, []);
// icon
assert.isString(entry.icon);
// raw
assert.isString(entry.raw);
// collection
assert.instanceOf(entry.collection, MdsCollection);
});
it("adds MDS3 FIDO2 entry", async function() {
await mc.addToc(fs.readFileSync("./test/mdsV3.jwt", "utf8"));
mc.addEntry("ewogICAgICAiYWFndWlkIjogImM1ZWY1NWZmLWFkOWEtNGI5Zi1iNTgwLWFkZWJhZmUwMjZkMCIsCiAgICAgICJtZXRhZGF0YVN0YXRlbWVudCI6IHsKICAgICAgICAibGVnYWxIZWFkZXIiOiAiaHR0cHM6Ly9maWRvYWxsaWFuY2Uub3JnL21ldGFkYXRhL21ldGFkYXRhLXN0YXRlbWVudC1sZWdhbC1oZWFkZXIvIiwKICAgICAgICAiYWFndWlkIjogImM1ZWY1NWZmLWFkOWEtNGI5Zi1iNTgwLWFkZWJhZmUwMjZkMCIsCiAgICAgICAgImRlc2NyaXB0aW9uIjogIll1YmlLZXkgNUNpIiwKICAgICAgICAiYXV0aGVudGljYXRvclZlcnNpb24iOiA1MDIwMCwKICAgICAgICAicHJvdG9jb2xGYW1pbHkiOiAiZmlkbzIiLAogICAgICAgICJzY2hlbWEiOiAzLAogICAgICAgICJ1cHYiOiBbCiAgICAgICAgICB7CiAgICAgICAgICAgICJtYWpvciI6IDEsCiAgICAgICAgICAgICJtaW5vciI6IDAKICAgICAgICAgIH0KICAgICAgICBdLAogICAgICAgICJhdXRoZW50aWNhdGlvbkFsZ29yaXRobXMiOiBbCiAgICAgICAgICAiZWQyNTUxOV9lZGRzYV9zaGE1MTJfcmF3IiwKICAgICAgICAgICJzZWNwMjU2cjFfZWNkc2Ffc2hhMjU2X3JhdyIKICAgICAgICBdLAogICAgICAgICJwdWJsaWNLZXlBbGdBbmRFbmNvZGluZ3MiOiBbCiAgICAgICAgICAiY29zZSIKICAgICAgICBdLAogICAgICAgICJhdHRlc3RhdGlvblR5cGVzIjogWwogICAgICAgICAgImJhc2ljX2Z1bGwiCiAgICAgICAgXSwKICAgICAgICAidXNlclZlcmlmaWNhdGlvbkRldGFpbHMiOiBbCiAgICAgICAgICBbCiAgICAgICAgICAgIHsKICAgICAgICAgICAgICAidXNlclZlcmlmaWNhdGlvbk1ldGhvZCI6ICJwcmVzZW5jZV9pbnRlcm5hbCIKICAgICAgICAgICAgfSwKICAgICAgICAgICAgewogICAgICAgICAgICAgICJ1c2VyVmVyaWZpY2F0aW9uTWV0aG9kIjogInBhc3Njb2RlX2ludGVybmFsIiwKICAgICAgICAgICAgICAiY2FEZXNjIjogewogICAgICAgICAgICAgICAgImJhc2UiOiA2NCwKICAgICAgICAgICAgICAgICJtaW5MZW5ndGgiOiA0LAogICAgICAgICAgICAgICAgIm1heFJldHJpZXMiOiA4LAogICAgICAgICAgICAgICAgImJsb2NrU2xvd2Rvd24iOiAwCiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9LAogICAgICAgICAgICB7CiAgICAgICAgICAgICAgInVzZXJWZXJpZmljYXRpb25NZXRob2QiOiAibm9uZSIKICAgICAgICAgICAgfQogICAgICAgICAgXQogICAgICAgIF0sCiAgICAgICAgImtleVByb3RlY3Rpb24iOiBbCiAgICAgICAgICAiaGFyZHdhcmUiLAogICAgICAgICAgInNlY3VyZV9lbGVtZW50IgogICAgICAgIF0sCiAgICAgICAgIm1hdGNoZXJQcm90ZWN0aW9uIjogWwogICAgICAgICAgIm9uX2NoaXAiCiAgICAgICAgXSwKICAgICAgICAiY3J5cHRvU3RyZW5ndGgiOiAxMjgsCiAgICAgICAgImF0dGFjaG1lbnRIaW50IjogWwogICAgICAgICAgImV4dGVybmFsIiwKICAgICAgICAgICJ3aXJlZCIKICAgICAgICBdLAogICAgICAgICJ0Y0Rpc3BsYXkiOiBbXSwKICAgICAgICAiYXR0ZXN0YXRpb25Sb290Q2VydGlmaWNhdGVzIjogWwogICAgICAgICAgIk1JSURIakNDQWdhZ0F3SUJBZ0lFRzBCVDl6QU5CZ2txaGtpRzl3MEJBUXNGQURBdU1Td3dLZ1lEVlFRREV5TlpkV0pwWTI4Z1ZUSkdJRkp2YjNRZ1EwRWdVMlZ5YVdGc0lEUTFOekl3TURZek1UQWdGdzB4TkRBNE1ERXdNREF3TURCYUdBOHlNRFV3TURrd05EQXdNREF3TUZvd0xqRXNNQ29HQTFVRUF4TWpXWFZpYVdOdklGVXlSaUJTYjI5MElFTkJJRk5sY21saGJDQTBOVGN5TURBMk16RXdnZ0VpTUEwR0NTcUdTSWIzRFFFQkFRVUFBNElCRHdBd2dnRUtBb0lCQVFDL2p3WXVoQlZscWFpWVdFTXNyV0Zpc2dKK1B0TTkxZVNycEk0VEs3VTUzbXdDSWF3U0RIeTh2VW1rNU4yS0FqOWFidlQ5TlA1U01TMWhRaTN1c3hvWUdvblhRZ2ZPNlpYeVVBOWErS0FrcWRGbkJubHl1Z1NlQ09lcDhFZFpGZnNhUkZ0TWprd3o1R2N6MlB5NHZJWXZDZE1IUHR3YXowYlZ1em5ldWVJRXo2VG5RakU2M1JkdDJ6YnduZWJ3VEc1WnliZVdTd2J6eStCSjM0WkhjVWhQQVk4OXlKUVh1RTBJek1aRmNFQmJQTlJiV0VDUktnanEvL3FUOW5tRE9GVmxTUkN0MndpcVBTemx1d24rditzdVFFQnNValRHTUVkMjV0S1hYVGtOVzIxd0lXYnhlU3lVb1RYd0x2R1M2eGx3UVNnTnBrMnFYWXdmOGlYZzdWV1pBZ01CQUFHalFqQkFNQjBHQTFVZERnUVdCQlFnSXZ6MGJOR0poamdwVG9rc3lLcFA5eHY5b0RBUEJnTlZIUk1FQ0RBR0FRSC9BZ0VBTUE0R0ExVWREd0VCL3dRRUF3SUJCakFOQmdrcWhraUc5dzBCQVFzRkFBT0NBUUVBanZqdU9NRFNhK0pYRkNMeUJLc3ljWHRCVlpzSjRVZTNMYmFFc1BZNE1ZTi9oSVE1Wk01cDdFamZjbk1HNEN0WWtOc2ZOSGMwQWhCTGRxNDVyblQ4N3EvNk8zdlVFdE5NYWZiaFU2a3RoWDdZKzlYRk45TnBtWXhyK2VrVlk1eE94aThoOUpESWdvTVA0VkIxdVMwYXVuTDFJR3FyTm9vTDltbUZuTDJrTFZWZWU2L1ZSNkM1K0tTVENNQ1dwcE11SklaSUkydjlvNGRrb1o4WTdRUmpRbExmWXpkM3FHdEtidzd4YUYxVXNHLzV4VWIvQnR3YjJYMmc0SW5waUIveXQvM0NwUVhwaVdYL0s0bUJ2VUtpR24wNVpzcWVZMWd4NGcweExCcWNVOXBzbXlQeksrVnNndzJqZVJRNUpsS0R5cUUwaGViZkMxdHZGdTBDQ3JKRmN3PT0iCiAgICAgICAgXSwKICAgICAgICAiaWNvbiI6ICJkYXRhOmltYWdlL3BuZztiYXNlNjQsaVZCT1J3MEtHZ29BQUFBTlNVaEVVZ0FBQUNBQUFBQWZDQVlBQUFDR1ZzK01BQUFBQVhOU1IwSUFyczRjNlFBQUFBUm5RVTFCQUFDeGp3djhZUVVBQUFBSmNFaFpjd0FBSFlZQUFCMkdBVjJpRTRFQUFBYk5TVVJCVkZoSHBWZDdUTlYxRkQvM2Q1OXdlUVNJZ1M5QVFBWGNGTEFRWmk5ZnBlVnoxdFkvV1RacjVXeHBjN1c1a25MYTVqSTNaODVzclMybk0yc2p0V3daUzdJVUg0SDR4Q25FUXg0REFaRjc0Vjd1czg4NXY5L2xJbkJ2VkovQjRQdjludS81bnUvNW52TTU1NmZ6QS9RdjBIYi9JclgzVkZLUG80NWNubTRpblVJV1l3TEZSbVpRVXV3akZHL04xaVJIaDFFWjBOUlZSdWRxdDFCZCsyblNLeVMvT2h5czArbGszZS8za1E5cXZENFpVdGE0VlZTVXVZMGVpcHlpVGhBZm9jb09SVmdEdXV3M3FLUmlBZDNyYmNFdGpUallJb2Y2V2FIc0NtelZQV0NNeCtjZ2g4dExxV01LYU1Xc1VqTHFvMlJ0SklRMG9Pem1lcnBRdTRlc1pnc09Oa0d4SDdkMGtkdlRUMTdzNE9NVTdWSThaaGpnR2FNK0FxOWlFTnU4UGlmMXVkejA3TXd2S1dmOEdsVm9DRVkwNFBDNVdkVGFYWUZiUjh2TnZMNSszS2dmYjV4Tk15YTlSYW1KaXluYU1sR1RWdEZscjZiYTl1K3BxbkVYNHVNdVJSZ2pTWUVock43dXRGRmU2bHFhbDdOZmt3NWltQUdIeW5QcGJrOFZtWTB4c3RucHRsRkNWQ1l0elR1Qk44M1FwTUxqVHRldmRQelNVbko3ZThta2p4WjM5ZlhiS0RmbGRacWJ2VStUVWdHbkJWRjZmUTJpUEhnNFcxNlVXVXd2emJrMTZzTVpFK1BuMHB2ejdKU2V1QXllczhsY3BDbWFLdW8vcCtxV3IyVWN3SUFIV3J2UDBZRXpoWEF0TEFic3NIaHA3aUdhbXZ5aWpQOHJ5cXJYVVdYOVhvb3d4eUF1Zk5CcnA0M1BPQkZYWmxrZjhNRFJpcWNweW93QXdwdXoyeCtmV3Z6L0R0ZGU5c21zenlndGNSNkMxd2JkekJsNk9scTVXTllZNG9HYXRoSk1ya1RFeDBqQVJTSEFWcys1cllrUU5YYitRZ2ZQTHNRNmdYeUluc3JlUWZtcG03UlZGWWZMODZuMWZpVU9rWXZTaGtVUHh2YnVrem95NksxaWhNMWhvM1h6VzZFdlNmWEErZHBpV0dhV2QrZG9Yekx6bUd3S1lGTENBc1JBbFBCQWhNbENGWFU3dEJVVlByOEhnVmNKSFdxK0YwMHBscitETVRkclA0enZ4WTExa05NaHhUK1NlVEdnK2Q0VjVMUUppdHlVR0pOQjhWRlpzamdZQlpNL0lJL1hDVGtqMHF5RE9wRjJBVlExN0NJalVwL0RuVDFVa0w1RjVnZGorc1Mxd2cxZ0UzZ2lnbTYwZkNYelNuUFhieUFQYklYditJRHBFMTZUaGFISVM5c2t5aGxtTUU1RjNjZnFBS2hxMkMwRTVQSDFnWWFYYUxQRGtaRzBIREpPbktXSHA1MUkwejVTT3V4OGUxV0F1WnpkSFFyVGtwOFRtalhvSStsYTB3R1pzenVicWJPM2lmUTZBL1c3dlZTWXNWM21SMEpLd2tLYzRXSGlCa21SOEkzQ0NnSTg3b09MNHF6VDVQK1JVSkJlakVPZ0FQSzhoWVB6YXRNK2VJVHAySU85eVRRbWVyb21QUnh4MXF4QWNzaWxlL3ViU2VFYmNXUUdZRUNnaGNMWTJIeUtqb2dqSDI1aE1wanBVdjFPdWdsaTRlaDJlUncwTzMyYkpqa3l1Q2dOemcwdnpsWU1TaVNzMHVvbzRNRzdoTU9qQ0VhWDF5RkUwblN2akJ6dVRuRXBLODZaOElvcUZBSXVidzhrZzlBckVhUkVXU1pJK2pINFhicDZnOUU5RW5KVDNvYVJ6RE4rTVVKQlFESG41NmE4b1VtRUJ1c094QnMvTjUrdEpFYlBrQUZEajhVR3ZPcy9JV3ZjU2dsR0JodlM3L0ZUWWZwV0dZZERZOGZQQXhXU0EzNXNUQzRwNCtMbTRBYXFJb1BlUXRmdWZLNkpoMFpoeGxic1VYT1NtWE5pZkQ1WlRBa3lEb2ZiYmNjbHhuQThXTkFxeENiUk55a2hYeFFwYUR3NjdmWFVZYnNpRzBLaHR2Mm9lSXZoOHJoUU1ZT2NFQXFYRy9lSSt6bmdPYzV5eHI4cTgySUFNMWMvRkxGT3BscXU1ZUZRWHJNWnpHY1ZDalliTFdHNUk0QlQxZXVScmxieHROT3RNaXREREVoTFhJSXluQUF2dU9FV0UzWDNOZEFmdDk0VmdhRzQyWElRdDBaWDZQZUNFL3FRRmU5cks2SHg3WVU1MEt2SDdmVzRmUytxN0tLQkp4c2dnQlg1cFNBR2gxaklyVmg1elE2dzNSZmFhaEJYbS9hQ2JDWlRqQ1VGVVR5V1pxVzlwNjJNakpQWFZxT3JQZ01PNE52NzRHa2Yrb3dmdE5WQkRRbmpGSnFIU3cxN3BYdmhXVzVLWnFlL1E0OU4vVVNUQ0FWV29RWEZJSEJIWFhlM0ZQclVEc3VHRG10Ri9oSEtUSHBla3hoaUFPUEkrU0pxNlM2SEY0STlZV3prQkpUbzQ2aVVNeldwOFBpci9SaWR1THhLWXNTa3NWOHZMbE9RdmhHWDJZbFIwT0JoQmpDK3UvZ0VjdlkwQXBLN1lrNDFOeGpQU1FuV0ZIVEY2NlVyamdldkI4Q3U1YStsMnZZU1JQdHVWRG83M2hoZE1TSG5VWDd0VGpzVlpHeEFsL1dwdGlPSUVRMWduTDI5bVg2L3RSMXRtbGtZajhXNFgrQ1NqV2NVREdZMU5wUy9DN2hTS3FpTUxNL2wyUW1TV1o3M0RkeitnaW84QkNFTllQUTQ2cW5rendYVWJxdkJreGpVUXNXZlpGZ2J1bzNyQWYrd043ak9POTAreW54NFBpM0wrMG5ZTDFTY2hEVWdBUDRnUFYvN0lkMXErMUhTaG11R2tJcVdSUGd5eE1GcVA4SGZqVG5qWHdZNWJRZmJKY3Q2T0l6S2dNSG90Ri9IZTFlZ3NheEhTcUc2d2ZkbVE1eDhOeVRGRnFCY3AyaVNvd0hSM3lrNSszNmhGN3ZYQUFBQUFFbEZUa1N1UW1DQyIsCiAgICAgICAgImF1dGhlbnRpY2F0b3JHZXRJbmZvIjogewogICAgICAgICAgInZlcnNpb25zIjogWwogICAgICAgICAgICAiVTJGX1YyIiwKICAgICAgICAgICAgIkZJRE9fMl8wIiwKICAgICAgICAgICAgIkZJRE9fMl8xX1BSRSIKICAgICAgICAgIF0sCiAgICAgICAgICAiZXh0ZW5zaW9ucyI6IFsKICAgICAgICAgICAgImNyZWRQcm90ZWN0IiwKICAgICAgICAgICAgImhtYWMtc2VjcmV0IgogICAgICAgICAgXSwKICAgICAgICAgICJhYWd1aWQiOiAiYzVlZjU1ZmZhZDlhNGI5ZmI1ODBhZGViYWZlMDI2ZDAiLAogICAgICAgICAgIm9wdGlvbnMiOiB7CiAgICAgICAgICAgICJwbGF0IjogZmFsc2UsCiAgICAgICAgICAgICJyayI6IHRydWUsCiAgICAgICAgICAgICJjbGllbnRQaW4iOiB0cnVlLAogICAgICAgICAgICAidXAiOiB0cnVlLAogICAgICAgICAgICAiY3JlZGVudGlhbE1nbXRQcmV2aWV3IjogdHJ1ZQogICAgICAgICAgfSwKICAgICAgICAgICJtYXhNc2dTaXplIjogMTIwMCwKICAgICAgICAgICJwaW5VdkF1dGhQcm90b2NvbHMiOiBbCiAgICAgICAgICAgIDIsCiAgICAgICAgICAgIDEKICAgICAgICAgIF0sCiAgICAgICAgICAibWF4Q3JlZGVudGlhbENvdW50SW5MaXN0IjogOCwKICAgICAgICAgICJtYXhDcmVkZW50aWFsSWRMZW5ndGgiOiAxMjgsCiAgICAgICAgICAidHJhbnNwb3J0cyI6IFsKICAgICAgICAgICAgInVzYiIsCiAgICAgICAgICAgICJsaWdodG5pbmciCiAgICAgICAgICBdLAogICAgICAgICAgImFsZ29yaXRobXMiOiBbCiAgICAgICAgICAgIHsKICAgICAgICAgICAgICAidHlwZSI6ICJwdWJsaWMta2V5IiwKICAgICAgICAgICAgICAiYWxnIjogLTcKICAgICAgICAgICAgfSwKICAgICAgICAgICAgewogICAgICAgICAgICAgICJ0eXBlIjogInB1YmxpYy1rZXkiLAogICAgICAgICAgICAgICJhbGciOiAtOAogICAgICAgICAgICB9CiAgICAgICAgICBdLAogICAgICAgICAgIm1pblBJTkxlbmd0aCI6IDQsCiAgICAgICAgICAiZmlybXdhcmVWZXJzaW9uIjogMzI4NzA2CiAgICAgICAgfQogICAgICB9LAogICAgICAic3RhdHVzUmVwb3J0cyI6IFsKICAgICAgICB7CiAgICAgICAgICAic3RhdHVzIjogIkZJRE9fQ0VSVElGSUVEX0wxIiwKICAgICAgICAgICJlZmZlY3RpdmVEYXRlIjogIjIwMjAtMDUtMTIiLAogICAgICAgICAgImNlcnRpZmljYXRpb25EZXNjcmlwdG9yIjogIll1YmlLZXkgNUNpIiwKICAgICAgICAgICJjZXJ0aWZpY2F0ZU51bWJlciI6ICJGSURPMjAwMjAxOTEwMTcwMDMiLAogICAgICAgICAgImNlcnRpZmljYXRpb25Qb2xpY3lWZXJzaW9uIjogIjEuMS4xIiwKICAgICAgICAgICJjZXJ0aWZpY2F0aW9uUmVxdWlyZW1lbnRzVmVyc2lvbiI6ICIxLjMiCiAgICAgICAgfQogICAgICBdLAogICAgICAidGltZU9mTGFzdFN0YXR1c0NoYW5nZSI6ICIyMDIwLTA1LTEyIgogICAgfQ==");
mc.validate();
var entry = mc.findEntry("c5ef55ff-ad9a-4b9f-b580-adebafe026d0");
assert.isDefined(entry, "added entry c5ef55ff-ad9a-4b9f-b580-adebafe026d0");
// check that TOC data was copied to new entry:
// schema
assert.strictEqual(entry.schema, 3);
// timeOfLastStatusChange
assert.strictEqual(entry.timeOfLastStatusChange, "2020-05-12");
// hash
assert.isUndefined(entry.hash);
let tocHash = crypto.createHash("sha256");
tocHash.update(jsObjectToB64(entry.raw));
tocHash = tocHash.digest().toString("base64");
assert.strictEqual(tocHash, "cYyOrPCsXMBUvX03jMqmRZ9PRrW07WPwnVi1Dke9ze8=");
// id
assert.strictEqual(entry.aaguid, "c5ef55ff-ad9a-4b9f-b580-adebafe026d0");
assert.isUndefined(entry.aaid);
assert.isUndefined(entry.attestationCertificateKeyIdentifiers);
// statusReports
assert.isArray(entry.statusReports);
assert.strictEqual(entry.statusReports.length, 1);
// check the entry data was copied to new entry:
// description
assert.strictEqual(entry.description, "YubiKey 5Ci");
// authenticatorVersion
assert.strictEqual(entry.authenticatorVersion, 50200);
// protocolFamily
assert.strictEqual(entry.protocolFamily, "fido2");
assert.deepEqual(entry.upv, [
{
major: 1,
minor: 0,
},
]);
// authenticationAlgorithms
assert.deepEqual(entry.authenticationAlgorithms, [ "ed25519_eddsa_sha512_raw", "secp256r1_ecdsa_sha256_raw" ]);
// publicKeyAlgAndEncoding
assert.deepEqual(entry.publicKeyAlgAndEncodings, [ "cose" ]);
// attestationTypes
assert.deepEqual(entry.attestationTypes, [ "basic_full" ]);
// userVerificationDetails
assert.strictEqual(entry.userVerificationDetails.length, 1);
assert.deepEqual(
entry.userVerificationDetails[0],
[
{
userVerification: "presence",
},
{
userVerification: "passcode",
base: 64,
blockSlowdown: 0,
maxRetries: 8,
minLength: 4,
type: "code",
},
{
userVerification: "none",
},
]
);
// keyProtection
assert.deepEqual(entry.keyProtection, [ "hardware", "secure_element" ]);
// matcherProtection
assert.deepEqual(entry.matcherProtection, [ "on_chip" ]);
// cryptoStrength
assert.strictEqual(entry.cryptoStrength, 128);
// attachmentHint
assert.deepEqual(entry.attachmentHint, [ "external", "wired" ]);
// tcDisplay
assert.deepEqual(entry.tcDisplay, [ ]);
// tcDisplayContentType
assert.isUndefined(entry.tcDisplayContentType);
// attestationRootCertificates
assert.deepEqual(entry.attestationRootCertificates, [ "MIIDHjCCAgagAwIBAgIEG0BT9zANBgkqhkiG9w0BAQsFADAuMSwwKgYDVQQDEyNZdWJpY28gVTJGIFJvb3QgQ0EgU2VyaWFsIDQ1NzIwMDYzMTAgFw0xNDA4MDEwMDAwMDBaGA8yMDUwMDkwNDAwMDAwMFowLjEsMCoGA1UEAxMjWXViaWNvIFUyRiBSb290IENBIFNlcmlhbCA0NTcyMDA2MzEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC/jwYuhBVlqaiYWEMsrWFisgJ+PtM91eSrpI4TK7U53mwCIawSDHy8vUmk5N2KAj9abvT9NP5SMS1hQi3usxoYGonXQgfO6ZXyUA9a+KAkqdFnBnlyugSeCOep8EdZFfsaRFtMjkwz5Gcz2Py4vIYvCdMHPtwaz0bVuzneueIEz6TnQjE63Rdt2zbwnebwTG5ZybeWSwbzy+BJ34ZHcUhPAY89yJQXuE0IzMZFcEBbPNRbWECRKgjq//qT9nmDOFVlSRCt2wiqPSzluwn+v+suQEBsUjTGMEd25tKXXTkNW21wIWbxeSyUoTXwLvGS6xlwQSgNpk2qXYwf8iXg7VWZAgMBAAGjQjBAMB0GA1UdDgQWBBQgIvz0bNGJhjgpToksyKpP9xv9oDAPBgNVHRMECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEAjvjuOMDSa+JXFCLyBKsycXtBVZsJ4Ue3LbaEsPY4MYN/hIQ5ZM5p7EjfcnMG4CtYkNsfNHc0AhBLdq45rnT87q/6O3vUEtNMafbhU6kthX7Y+9XFN9NpmYxr+ekVY5xOxi8h9JDIgoMP4VB1uS0aunL1IGqrNooL9mmFnL2kLVVee6/VR6C5+KSTCMCWppMuJIZII2v9o4dkoZ8Y7QRjQlLfYzd3qGtKbw7xaF1UsG/5xUb/Btwb2X2g4InpiB/yt/3CpQXpiWX/K4mBvUKiGn05ZsqeY1gx4g0xLBqcU9psmyPzK+Vsgw2jeRQ5JlKDyqE0hebfC1tvFu0CCrJFcw==" ]);
// icon
assert.isString(entry.icon);
// authenticatorGetInfo
const { authenticatorGetInfo } = entry;
assert.isDefined(authenticatorGetInfo);
// versions
assert.deepEqual(authenticatorGetInfo.versions, [ "U2F_V2", "FIDO_2_0", "FIDO_2_1_PRE" ]);
// extensions
assert.deepEqual(authenticatorGetInfo.extensions, [ "credProtect", "hmac-secret" ]);
// aaguid
assert.strictEqual(authenticatorGetInfo.aaguid, "c5ef55ffad9a4b9fb580adebafe026d0");
// options
assert.deepEqual(authenticatorGetInfo.options, {
plat: false,
rk: true,
clientPin: true,
up: true,
credentialMgmtPreview: true,
});
// maxMsgSize
assert.strictEqual(authenticatorGetInfo.maxMsgSize, 1200);
// pinUvAuthProtocols
assert.deepEqual(authenticatorGetInfo.pinUvAuthProtocols, [ 2, 1 ]);
// maxCredentialCountInList
assert.strictEqual(authenticatorGetInfo.maxCredentialCountInList, 8);
// maxCredentialIdLength
assert.strictEqual(authenticatorGetInfo.maxCredentialIdLength, 128);
// transports
assert.deepEqual(authenticatorGetInfo.transports, [ "usb", "lightning" ]);
// algorithms
assert.deepEqual(authenticatorGetInfo.algorithms, [
{
type: "public-key",
alg: -7,
},
{
type: "public-key",
alg: -8,
},
]);
// minPINLength
assert.strictEqual(authenticatorGetInfo.minPINLength, 4);
// raw
assert.isString(entry.raw);
// collection
assert.instanceOf(entry.collection, MdsCollection);
});
it("adds MDS3 U2F entry", async function() {
await mc.addToc(fs.readFileSync("./test/mdsV3.jwt", "utf8"));
mc.addEntry("ewogICAgICAiYXR0ZXN0YXRpb25DZXJ0aWZpY2F0ZUtleUlkZW50aWZpZXJzIjogWwogICAgICAgICJiZjdiY2FhMGQwYzYxODdhOGM2YWJiZGQxNmExNTY0MGU3YzdiZGUyIiwKICAgICAgICAiNzUzMzAwZDY1ZGNjNzNhMzlhN2RiMzFlZjMwOGRiOWZhMGI1NjZhZSIsCiAgICAgICAgImI3NTNhMGU0NjBmYjJkYzdjN2M0ODdlMzVmMjRjZjYzYjA2NTM0N2MiLAogICAgICAgICJiNmQ0NGE0YjhkNGIwNDA3ODcyOTY5YjFmNmIyMjYzMDIxYmU2MjdlIiwKICAgICAgICAiNmQ0OTFmMjIzYWY3M2NkZjgxNzg0YTZjMDg5MGY4YTFkNTI3YTEyYyIKICAgICAgXSwKICAgICAgIm1ldGFkYXRhU3RhdGVtZW50IjogewogICAgICAgICJsZWdhbEhlYWRlciI6ICJodHRwczovL2ZpZG9hbGxpYW5jZS5vcmcvbWV0YWRhdGEvbWV0YWRhdGEtc3RhdGVtZW50LWxlZ2FsLWhlYWRlci8iLAogICAgICAgICJhdHRlc3RhdGlvbkNlcnRpZmljYXRlS2V5SWRlbnRpZmllcnMiOiBbCiAgICAgICAgICAiYmY3YmNhYTBkMGM2MTg3YThjNmFiYmRkMTZhMTU2NDBlN2M3YmRlMiIsCiAgICAgICAgICAiNzUzMzAwZDY1ZGNjNzNhMzlhN2RiMzFlZjMwOGRiOWZhMGI1NjZhZSIsCiAgICAgICAgICAiYjc1M2EwZTQ2MGZiMmRjN2M3YzQ4N2UzNWYyNGNmNjNiMDY1MzQ3YyIsCiAgICAgICAgICAiYjZkNDRhNGI4ZDRiMDQwNzg3Mjk2OWIxZjZiMjI2MzAyMWJlNjI3ZSIsCiAgICAgICAgICAiNmQ0OTFmMjIzYWY3M2NkZjgxNzg0YTZjMDg5MGY4YTFkNTI3YTEyYyIKICAgICAgICBdLAogICAgICAgICJkZXNjcmlwdGlvbiI6ICJZdWJpS2V5IDVDaSIsCiAgICAgICAgImF1dGhlbnRpY2F0b3JWZXJzaW9uIjogMiwKICAgICAgICAicHJvdG9jb2xGYW1pbHkiOiAidTJmIiwKICAgICAgICAic2NoZW1hIjogMywKICAgICAgICAidXB2IjogWwogICAgICAgICAgewogICAgICAgICAgICAibWFqb3IiOiAxLAogICAgICAgICAgICAibWlub3IiOiAxCiAgICAgICAgICB9CiAgICAgICAgXSwKICAgICAgICAiYXV0aGVudGljYXRpb25BbGdvcml0aG1zIjogWwogICAgICAgICAgInNlY3AyNTZyMV9lY2RzYV9zaGEyNTZfcmF3IgogICAgICAgIF0sCiAgICAgICAgInB1YmxpY0tleUFsZ0FuZEVuY29kaW5ncyI6IFsKICAgICAgICAgICJlY2NfeDk2Ml9yYXciCiAgICAgICAgXSwKICAgICAgICAiYXR0ZXN0YXRpb25UeXBlcyI6IFsKICAgICAgICAgICJiYXNpY19mdWxsIgogICAgICAgIF0sCiAgICAgICAgInVzZXJWZXJpZmljYXRpb25EZXRhaWxzIjogWwogICAgICAgICAgWwogICAgICAgICAgICB7CiAgICAgICAgICAgICAgInVzZXJWZXJpZmljYXRpb25NZXRob2QiOiAicHJlc2VuY2VfaW50ZXJuYWwiCiAgICAgICAgICAgIH0KICAgICAgICAgIF0KICAgICAgICBdLAogICAgICAgICJrZXlQcm90ZWN0aW9uIjogWwogICAgICAgICAgImhhcmR3YXJlIiwKICAgICAgICAgICJzZWN1cmVfZWxlbWVudCIsCiAgICAgICAgICAicmVtb3RlX2hhbmRsZSIKICAgICAgICBdLAogICAgICAgICJtYXRjaGVyUHJvdGVjdGlvbiI6IFsKICAgICAgICAgICJvbl9jaGlwIgogICAgICAgIF0sCiAgICAgICAgImNyeXB0b1N0cmVuZ3RoIjogMTI4LAogICAgICAgICJhdHRhY2htZW50SGludCI6IFsKICAgICAgICAgICJleHRlcm5hbCIsCiAgICAgICAgICAid2lyZWQiCiAgICAgICAgXSwKICAgICAgICAidGNEaXNwbGF5IjogW10sCiAgICAgICAgImF0dGVzdGF0aW9uUm9vdENlcnRpZmljYXRlcyI6IFsKICAgICAgICAgICJNSUlESGpDQ0FnYWdBd0lCQWdJRUcwQlQ5ekFOQmdrcWhraUc5dzBCQVFzRkFEQXVNU3d3S2dZRFZRUURFeU5aZFdKcFkyOGdWVEpHSUZKdmIzUWdRMEVnVTJWeWFXRnNJRFExTnpJd01EWXpNVEFnRncweE5EQTRNREV3TURBd01EQmFHQTh5TURVd01Ea3dOREF3TURBd01Gb3dMakVzTUNvR0ExVUVBeE1qV1hWaWFXTnZJRlV5UmlCU2IyOTBJRU5CSUZObGNtbGhiQ0EwTlRjeU1EQTJNekV3Z2dFaU1BMEdDU3FHU0liM0RRRUJBUVVBQTRJQkR3QXdnZ0VLQW9JQkFRQy9qd1l1aEJWbHFhaVlXRU1zcldGaXNnSitQdE05MWVTcnBJNFRLN1U1M213Q0lhd1NESHk4dlVtazVOMktBajlhYnZUOU5QNVNNUzFoUWkzdXN4b1lHb25YUWdmTzZaWHlVQTlhK0tBa3FkRm5Cbmx5dWdTZUNPZXA4RWRaRmZzYVJGdE1qa3d6NUdjejJQeTR2SVl2Q2RNSFB0d2F6MGJWdXpuZXVlSUV6NlRuUWpFNjNSZHQyemJ3bmVid1RHNVp5YmVXU3dienkrQkozNFpIY1VoUEFZODl5SlFYdUUwSXpNWkZjRUJiUE5SYldFQ1JLZ2pxLy9xVDlubURPRlZsU1JDdDJ3aXFQU3psdXduK3Yrc3VRRUJzVWpUR01FZDI1dEtYWFRrTlcyMXdJV2J4ZVN5VW9UWHdMdkdTNnhsd1FTZ05wazJxWFl3ZjhpWGc3VldaQWdNQkFBR2pRakJBTUIwR0ExVWREZ1FXQkJRZ0l2ejBiTkdKaGpncFRva3N5S3BQOXh2OW9EQVBCZ05WSFJNRUNEQUdBUUgvQWdFQU1BNEdBMVVkRHdFQi93UUVBd0lCQmpBTkJna3Foa2lHOXcwQkFRc0ZBQU9DQVFFQWp2anVPTURTYStKWEZDTHlCS3N5Y1h0QlZac0o0VWUzTGJhRXNQWTRNWU4vaElRNVpNNXA3RWpmY25NRzRDdFlrTnNmTkhjMEFoQkxkcTQ1cm5UODdxLzZPM3ZVRXROTWFmYmhVNmt0aFg3WSs5WEZOOU5wbVl4citla1ZZNXhPeGk4aDlKRElnb01QNFZCMXVTMGF1bkwxSUdxck5vb0w5bW1Gbkwya0xWVmVlNi9WUjZDNStLU1RDTUNXcHBNdUpJWklJMnY5bzRka29aOFk3UVJqUWxMZll6ZDNxR3RLYnc3eGFGMVVzRy81eFViL0J0d2IyWDJnNElucGlCL3l0LzNDcFFYcGlXWC9LNG1CdlVLaUduMDVac3FlWTFneDRnMHhMQnFjVTlwc215UHpLK1ZzZ3cyamVSUTVKbEtEeXFFMGhlYmZDMXR2RnUwQ0NySkZjdz09IgogICAgICAgIF0sCiAgICAgICAgImljb24iOiAiZGF0YTppbWFnZS9wbmc7YmFzZTY0LGlWQk9SdzBLR2dvQUFBQU5TVWhFVWdBQUFDQUFBQUFmQ0FZQUFBQ0dWcytNQUFBQUFYTlNSMElBcnM0YzZRQUFBQVJuUVUxQkFBQ3hqd3Y4WVFVQUFBQUpjRWhaY3dBQUhZWUFBQjJHQVYyaUU0RUFBQWJOU1VSQlZGaEhwVmQ3VE5WMUZELzNkNTl3ZVFTSWdTOUFRQVhjRkxBUVppOWZwZVZ6MXRZL1dUWnI1V3hwYzdXNWtuTGE1akkzWjg1c3JTMm5NMnNqdFd3WlM3SVVINEg0eENuRVF4NERBWkY3NFY3dXM4ODV2OS9sSW5CdlZKL0I0UHY5bnUvNW51LzVudk01NTZmekEvUXYwSGIvSXJYM1ZGS1BvNDVjbm00aW5VSVdZd0xGUm1aUVV1d2pGRy9OMWlSSGgxRVowTlJWUnVkcXQxQmQrMm5TS3lTL09oeXMwK2xrM2UvM2tROXF2RDRaVXRhNFZWU1V1WTBlaXB5aVRoQWZvY29PUlZnRHV1dzNxS1JpQWQzcmJjRXRqVGpZSW9mNldhSHNDbXpWUFdDTXgrY2doOHRMcVdNS2FNV3NVakxxbzJSdEpJUTBvT3ptZXJwUXU0ZXNaZ3NPTmtHeEg3ZDBrZHZUVDE3czRPTVU3Vkk4WmhqZ0dhTStBcTlpRU51OFBpZjF1ZHowN013dktXZjhHbFZvQ0VZMDRQQzVXZFRhWFlGYlI4dk52TDUrM0tnZmI1eE5NeWE5UmFtSml5bmFNbEdUVnRGbHI2YmE5dStwcW5FWDR1TXVSUmdqU1lFaHJON3V0RkZlNmxxYWw3TmZrdzVpbUFHSHluUHBiazhWbVkweHN0bnB0bEZDVkNZdHpUdUJOODNRcE1MalR0ZXZkUHpTVW5KN2U4bWtqeFozOWZYYktEZmxkWnFidlUrVFVnR25CVkY2ZlEyaVBIZzRXMTZVV1V3dnpiazE2c01aRStQbjBwdno3SlNldUF5ZXM4bGNwQ21hS3VvL3ArcVdyMlVjd0lBSFdydlAwWUV6aFhBdExBYnNzSGhwN2lHYW12eWlqUDhyeXFyWFVXWDlYb293eHlBdWZOQnJwNDNQT0JGWFpsa2Y4TURSaXFjcHlvd0F3cHV6MngrZld2ei9EdGRlOXNtc3p5Z3RjUjZDMXdiZHpCbDZPbHE1V05ZWTRvR2F0aEpNcmtURXgwakFSU0hBVnMrNXJZa1FOWGIrUWdmUExzUTZnWHlJbnNyZVFmbXBtN1JWRllmTDg2bjFmaVVPa1l2U2hrVVB4dmJ1a3pveTZLMWloTTFobzNYelc2RXZTZlhBK2RwaVdHYVdkK2RvWHpMem1Hd0tZRkxDQXNSQWxQQkFoTWxDRlhVN3RCVVZQcjhIZ1ZjSkhXcStGMDBwbHIrRE1UZHJQNHp2eFkxMWtOTWh4VCtTZVRHZytkNFY1TFFKaXR5VUdKTkI4VkZac2pnWUJaTS9JSS9YQ1RrajBxeURPcEYyQVZRMTdDSWpVcC9EblQxVWtMNUY1Z2RqK3NTMXdnMWdFM2dpZ202MGZDWHpTblBYYnlBUGJJWHYrSURwRTE2VGhhSElTOXNreWhsbU1FNUYzY2ZxQUtocTJDMEU1UEgxZ1lhWGFMUERrWkcwSERKT25LV0hwNTFJMHo1U091eDhlMVdBdVp6ZEhRclRrcDhUbWpYb0krbGEwd0dac3p1YnFiTzNpZlE2QS9XN3ZWU1lzVjNtUjBKS3drS2M0V0hpQmttUjhJM0NDZ0k4N29PTDRxelQ1UCtSVUpCZWpFT2dBUEs4aFlQemF0TStlSVRwMklPOXlUUW1lcm9tUFJ4eDFxeEFjc2lsZS91YlNlRWJjV1FHWUVDZ2hjTFkySHlLam9nakgyNWhNcGpwVXYxT3VnbGk0ZWgyZVJ3ME8zMmJKamt5dUNnTnpnMHZ6bFlNU2lTczB1b280TUc3aE1PakNFYVgxeUZFMG5TdmpCenVUbkVwSzg2WjhJb3FGQUl1Ync4a2c5QXJFYVJFV1NaSStqSDRYYnA2ZzlFOUVuSlQzb2FSekROK01VSkJRREhuNTZhOG9VbUVCdXNPeEJzL041K3RKRWJQa0FGRGo4VUd2T3MvSVd2Y1NnbEdCaHZTNy9GVFlmcFdHWWREWThmUEF4V1NBMzVzVEM0cDQrTG00QWFxSW9QZVF0ZnVmSzZKaDBaaHhsYnNVWE9TbVhOaWZENVpUQWt5RG9mYmJjY2x4bkE4V05BcXhDYlJOeWtoWHhRcGFEdzY3ZlhVWWJzaUcwS2h0djJvZUl2aDhyaFFNWU9jRUFxWEcvZUkrem5nT2M1eXhyOHE4MklBTTFjL0ZMRk9wbHF1NWVGUVhyTVp6R2NWQ2pZYkxXRzVJNEJUMWV1UnJsYnh0Tk90TWl0RERFaExYSUl5bkFBdnVPRVdFM1gzTmRBZnQ5NFZnYUc0MlhJUXQwWlg2UGVDRS9xUUZlOXJLNkh4N1lVNTBLdkg3Zlc0ZlMrcTdLS0JKeHNnZ0JYNXBTQUdoMWpJclZoNXpRNnczUmZhYWhCWG0vYUNiQ1pUakNVRlVUeVdacVc5cDYyTWpKUFhWcU9yUGdNTzROdjc0R2tmK293ZnROVkJEUW5qRkpxSFN3MTdwWHZoV1c1S1pxZS9RNDlOL1VTVENBVldvUVhGSUhCSFhYZTNGUHJVRHN1R0RtdEYvaEhLVEhwZWt4aGlBT1BJK1NKcTZTNkhGNEk5WVd6a0JKVG80NmlVTXpXcDhQaXIvUmlkdUx4S1lzU2tzVjh2TGxPUXZoR1gyWWxSME9CaEJqQyt1L2dFY3ZZMEFwSzdZazQxTnhqUFNRbldGSFRGNjZVcmpnZXZCOEN1NWErbDJ2WVNSUHR1VkRvNzNoaGRNU0huVVg3dFRqc1ZaR3hBbC9XcHRpT0lFUTFnbkwyOW1YNi90UjF0bWxrWWo4VzRYK0NTaldjVURHWTFOcFMvQzdoU0txaU1MTS9sMlFtU1daNzNEZHorZ2lvOEJDRU5ZUFE0NnFua3p3WFVicXZCa3hqVVFzV2ZaRmdidW8zckFmK3dON2pPTzkwK3lueDRQaTNMKzBuWUwxU2NoRFVnQVA0Z1BWLzdJZDFxKzFIU2htdUdrSXFXUlBneXhNRnFQOEhmalRualh3WTViUWZiSmN0Nk9JektnTUhvdEYvSGUxZWdzYXhIU3FHNndmZG1RNXg4TnlURkZxQmNwMmlTb3dIUjN5azUrMzZoRjd2WEFBQUFBRWxGVGtTdVFtQ0MiCiAgICAgIH0sCiAgICAgICJzdGF0dXNSZXBvcnRzIjogWwogICAgICAgIHsKICAgICAgICAgICJzdGF0dXMiOiAiRklET19DRVJUSUZJRURfTDEiLAogICAgICAgICAgImVmZmVjdGl2ZURhdGUiOiAiMjAyMC0wNS0xMiIsCiAgICAgICAgICAiY2VydGlmaWNhdGlvbkRlc2NyaXB0b3IiOiAiWXViaUtleSA1Q2kiLAogICAgICAgICAgImNlcnRpZmljYXRlTnVtYmVyIjogIlUyRjExMDAyMDE5MTAxNzAwNyIsCiAgICAgICAgICAiY2VydGlmaWNhdGlvblBvbGljeVZlcnNpb24iOiAiMS4xLjEiLAogICAgICAgICAgImNlcnRpZmljYXRpb25SZXF1aXJlbWVudHNWZXJzaW9uIjogIjEuMyIKICAgICAgICB9CiAgICAgIF0sCiAgICAgICJ0aW1lT2ZMYXN0U3RhdHVzQ2hhbmdlIjogIjIwMjAtMDUtMTIiCiAgICB9");
mc.validate();
var entry = mc.findEntry("bf7bcaa0d0c6187a8c6abbdd16a15640e7c7bde2");
assert.isDefined(entry, "added entry bf7bcaa0d0c6187a8c6abbdd16a15640e7c7bde2");
// check that TOC data was copied to new entry:
// schema
assert.strictEqual(entry.schema, 3);
// timeOfLastStatusChange
assert.strictEqual(entry.timeOfLastStatusChange, "2020-05-12");
// hash
assert.isUndefined(entry.hash);
let tocHash = crypto.createHash("sha256");
tocHash.update(jsObjectToB64(entry.raw));
tocHash = tocHash.digest().toString("base64");
assert.strictEqual(tocHash, "QaFyj/U7FwUCdztfF5Evz7VU2e+paGqlVyVNw1DpVws=");
// id
assert.isUndefined(entry.aaguid);
assert.isUndefined(entry.aaid);
// statusReports
assert.isArray(entry.statusReports);
assert.strictEqual(entry.statusReports.length, 1);
// attestationCertificateKeyIdentifiers
assert.isArray(entry.attestationCertificateKeyIdentifiers);
assert.isTrue(entry.attestationCertificateKeyIdentifiers.includes("bf7bcaa0d0c6187a8c6abbdd16a15640e7c7bde2"), "Identifier bf7bcaa0d0c6187a8c6abbdd16a15640e7c7bde2 found");
// check the entry data was copied to new entry:
// description
assert.strictEqual(entry.description, "YubiKey 5Ci");
// authenticatorVersion
assert.strictEqual(entry.authenticatorVersion, 2);
// protocolFamily
assert.strictEqual(entry.protocolFamily, "u2f");
assert.deepEqual(entry.upv, [
{
major: 1,
minor: 1,
},
]);
// authenticationAlgorithms
assert.deepEqual(entry.authenticationAlgorithms, [ "secp256r1_ecdsa_sha256_raw" ]);
// publicKeyAlgAndEncoding
assert.deepEqual(entry.publicKeyAlgAndEncodings, [ "ecc_x962_raw" ]);
// attestationTypes
assert.deepEqual(entry.attestationTypes, [ "basic_full" ]);
// userVerificationDetails
assert.strictEqual(entry.userVerificationDetails.length, 1);
assert.deepEqual(
entry.userVerificationDetails[0],
[
{
userVerification: "presence",
},
]
);
// keyProtection
assert.deepEqual(entry.keyProtection, [ "hardware", "secure_element", "remote_handle" ]);
// matcherProtection
assert.deepEqual(entry.matcherProtection, [ "on_chip" ]);
// cryptoStrength
assert.strictEqual(entry.cryptoStrength, 128);
// attachmentHint
assert.deepEqual(entry.attachmentHint, [ "external", "wired" ]);
// tcDisplay
assert.deepEqual(entry.tcDisplay, [ ]);
// tcDisplayContentType
assert.isUndefined(entry.tcDisplayContentType);
// attestationRootCertificates
assert.deepEqual(entry.attestationRootCertificates, [ "MIIDHjCCAgagAwIBAgIEG0BT9zANBgkqhkiG9w0BAQsFADAuMSwwKgYDVQQDEyNZdWJpY28gVTJGIFJvb3QgQ0EgU2VyaWFsIDQ1NzIwMDYzMTAgFw0xNDA4MDEwMDAwMDBaGA8yMDUwMDkwNDAwMDAwMFowLjEsMCoGA1UEAxMjWXViaWNvIFUyRiBSb290IENBIFNlcmlhbCA0NTcyMDA2MzEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC/jwYuhBVlqaiYWEMsrWFisgJ+PtM91eSrpI4TK7U53mwCIawSDHy8vUmk5N2KAj9abvT9NP5SMS1hQi3usxoYGonXQgfO6ZXyUA9a+KAkqdFnBnlyugSeCOep8EdZFfsaRFtMjkwz5Gcz2Py4vIYvCdMHPtwaz0bVuzneueIEz6TnQjE63Rdt2zbwnebwTG5ZybeWSwbzy+BJ34ZHcUhPAY89yJQXuE0IzMZFcEBbPNRbWECRKgjq//qT9nmDOFVlSRCt2wiqPSzluwn+v+suQEBsUjTGMEd25tKXXTkNW21wIWbxeSyUoTXwLvGS6xlwQSgNpk2qXYwf8iXg7VWZAgMBAAGjQjBAMB0GA1UdDgQWBBQgIvz0bNGJhjgpToksyKpP9xv9oDAPBgNVHRMECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEAjvjuOMDSa+JXFCLyBKsycXtBVZsJ4Ue3LbaEsPY4MYN/hIQ5ZM5p7EjfcnMG4CtYkNsfNHc0AhBLdq45rnT87q/6O3vUEtNMafbhU6kthX7Y+9XFN9NpmYxr+ekVY5xOxi8h9JDIgoMP4VB1uS0aunL1IGqrNooL9mmFnL2kLVVee6/VR6C5+KSTCMCWppMuJIZII2v9o4dkoZ8Y7QRjQlLfYzd3qGtKbw7xaF1UsG/5xUb/Btwb2X2g4InpiB/yt/3CpQXpiWX/K4mBvUKiGn05ZsqeY1gx4g0xLBqcU9psmyPzK+Vsgw2jeRQ5JlKDyqE0hebfC1tvFu0CCrJFcw==" ]);
// icon
assert.isString(entry.icon);
// raw
assert.isString(entry.raw);
// collection
assert.instanceOf(entry.collection, MdsCollection);
});
});
describe("findEntry", function() {
var mc;
before(async function() {
mc = new MdsCollection("test");
await mc.addToc(h.mds.mds2TocJwt);
mc.addEntry(h.mds.mds2UafEntry);
mc.validate();
});
it("throws if id is bad type", function() {
assert.throws(function() {
mc.findEntry();
}, Error, "expected 'id' to be String, got: undefined");
});
it("returns MdsEntry", function() {
var entry = mc.findEntry("4e4e#4005");
assert.instanceOf(entry, MdsEntry);
assert.strictEqual(entry.aaid, "4e4e#4005");
});
it("returns null on entry not found", function() {
var entry = mc.findEntry("ffff#ffff");
assert.isNull(entry);
});
});
});
|
/*===
SyntaxError
===*/
/* The current number parser is a lenient approximation and will be fixed
* when compliant number parsing is implemented. This test case illustrates
* one leniency example.
*/
try {
print(JSON.parse('1.2.3'));
} catch (e) {
print(e.name);
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const system_components_1 = require("system-components");
exports.Slider = system_components_1.default({
is: "input",
type: "range",
width: 1,
mx: 0,
my: 2,
color: "inherit",
bg: "gray",
borderRadius: 99999
}, {
display: "block",
height: "4px",
cursor: "pointer",
appearance: "none",
"&::-webkit-slider-thumb": {
width: "16px",
height: "16px",
backgroundColor: "currentcolor",
border: "0",
borderRadius: "99999px",
appearance: "none"
}
});
exports.Slider.displayName = 'Slider';
exports.default = exports.Slider;
|
console.log("ddddddddddddddddddddddddddddddd:");
import React from "react";
import ReactDOM from "react-dom";
import LoginInfo from "./modules/login/loginInfo.jsx";
ReactDOM.render(<LoginInfo />, document.getElementById("loginInfo"));
|
'use strict';
module.exports = function(Review) {
Review.beforeRemote('create', function(context, user, next) {
context.args.data.date = Date.now();
context.args.data.publisherId = context.req.accessToken.userId;
next();
});
};
|
import React, {useEffect, useState} from 'react'
import fetch from 'node-fetch'
import CodeBlock from '@theme/CodeBlock'
import styles from './CodeFromRemote.module.css';
const CodeFromRemote = ({url, link, ...props}) => {
const [content, setContent] = useState('')
let {src, lang, title} = props
if (url) {
src = url
.replace('github.com', 'raw.githubusercontent.com')
.replace('/blob/', '/')
}
if (link) {
title= link
}
useEffect(() => {
fetch(src)
.then(body => body.text())
.then((content) => {
// https://github.com/ory/kratos-selfservice-ui-react-native/blob/master/App.tsx#L37-L65
const params = src.match(/^https:\/\/raw.githubusercontent.com\/.+#L([0-9]+)-L([0-9]+)$/) || []
if (params.length === 3) {
const lines = content.split('\n')
lines.splice(0, params[1] - 1)
lines.splice(params[2] - params[1] - 1)
return lines.join('\n')
}
return content
})
.then(setContent)
.catch(console.err)
}, [])
return (
<div className={styles.container}>
<CodeBlock metastring={title && `title="${title}"`} className={lang && `language-${lang}`} children={content}/>
</div>
)
}
export default CodeFromRemote
|
/**
* First we will load all of this project's JavaScript dependencies which
* includes Vue and other libraries. It is a great starting point when
* building robust, powerful web applications using Vue and Laravel.
*/
require('./bootstrap');
window.Vue = require('vue');
/**
* The following block of code may be used to automatically register your
* Vue components. It will recursively scan this directory for the Vue
* components and automatically register them with their "basename".
*
* Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
*/
// const files = require.context('./', true, /\.vue$/i);
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default));
// Vue.component('example-component', require('./components/ExampleComponent.vue').default);
// *
// * Next, we will create a fresh Vue application instance and attach it to
// * the page. Then, you may begin adding components to this application
// * or customize the JavaScript scaffolding to fit your unique needs.
// const app = new Vue({
// el: '#app',
// });
|
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
import { Row, Col, Image, ListGroup, Card, Button } from 'react-bootstrap';
import Rating from '../components/Rating';
const ProductScreen = ({ match }) => {
const [product, setProduct] = useState({});
useEffect(() => {
axios.get(`/api/products/${match.params}`).then(res => {
setProduct(res.data);
}).catch(err => console.log(err));
}, [match]);
return (
<div>
<Link className='btn btn-light my-3' to='/' >Go Back</Link>
<Row>
<Col md={6}>
<Image src={product.image} alt={product.name} fluid />
</Col>
<Col md={3}>
<ListGroup variant='flush'>
<ListGroup.Item><h3>{product.name}</h3></ListGroup.Item>
<ListGroup.Item>
<Rating value={product.rating} text={`${product.numReviews} reviews`} />
</ListGroup.Item>
<ListGroup.Item>Price: ${product.price}</ListGroup.Item>
<ListGroup.Item>Description: {product.description}</ListGroup.Item>
</ListGroup>
</Col>
<Col md={3}>
<ListGroup variant='flush'>
<ListGroup.Item>
<Row>
<Col>Price:</Col>
<Col><strong>{product.price}</strong></Col>
</Row>
</ListGroup.Item>
<ListGroup.Item>
<Row>
<Col>Status:</Col>
<Col>{product.countInStock > 0 ? 'In Stock' : 'Out of Stock'}</Col>
</Row>
</ListGroup.Item>
<ListGroup.Item>
<Button disabled={product.countInStock === 0} className='btn-block' type='button' >Add To Cart</Button>
</ListGroup.Item>
</ListGroup>
</Col>
</Row>
</div>
);
};
export default ProductScreen;
|
export todo from './todo'
export todos from './todos'
|
'use strict';
// ---------------------------------------------------------------------------
const bitfinex = require ('./bitfinex.js');
const { ExchangeError, InvalidAddress, ArgumentsRequired, InsufficientFunds, AuthenticationError, OrderNotFound, InvalidOrder, BadRequest, InvalidNonce, BadSymbol, OnMaintenance, NotSupported, PermissionDenied, ExchangeNotAvailable } = require ('./base/errors');
const Precise = require ('./base/Precise');
// ---------------------------------------------------------------------------
module.exports = class bitfinex2 extends bitfinex {
describe () {
return this.deepExtend (super.describe (), {
'id': 'bitfinex2',
'name': 'Bitfinex',
'countries': [ 'VG' ],
'version': 'v2',
'certified': false,
'pro': false,
// new metainfo interface
'has': {
'CORS': undefined,
'spot': true,
'margin': undefined, // has but unimplemented
'swap': undefined, // has but unimplemented
'future': undefined,
'option': undefined,
'cancelAllOrders': true,
'cancelOrder': true,
'createDepositAddress': true,
'createLimitOrder': true,
'createMarketOrder': true,
'createOrder': true,
'deposit': undefined,
'editOrder': undefined,
'fetchBalance': true,
'fetchClosedOrder': true,
'fetchClosedOrders': true,
'fetchCurrencies': true,
'fetchDepositAddress': true,
'fetchFundingFees': undefined,
'fetchIndexOHLCV': false,
'fetchLedger': true,
'fetchMarkOHLCV': false,
'fetchMyTrades': true,
'fetchOHLCV': true,
'fetchOpenOrder': true,
'fetchOpenOrders': true,
'fetchOrder': true,
'fetchOrderTrades': true,
'fetchStatus': true,
'fetchTickers': true,
'fetchTime': false,
'fetchTradingFee': false,
'fetchTradingFees': true,
'fetchTransactions': true,
'withdraw': true,
},
'timeframes': {
'1m': '1m',
'5m': '5m',
'15m': '15m',
'30m': '30m',
'1h': '1h',
'3h': '3h',
'4h': '4h',
'6h': '6h',
'12h': '12h',
'1d': '1D',
'1w': '7D',
'2w': '14D',
'1M': '1M',
},
// cheapest endpoint is 240 requests per minute => ~ 4 requests per second => ( 1000ms / 4 ) = 250ms between requests on average
'rateLimit': 250,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766244-e328a50c-5ed2-11e7-947b-041416579bb3.jpg',
'api': {
'v1': 'https://api.bitfinex.com',
'public': 'https://api-pub.bitfinex.com',
'private': 'https://api.bitfinex.com',
},
'www': 'https://www.bitfinex.com',
'doc': [
'https://docs.bitfinex.com/v2/docs/',
'https://github.com/bitfinexcom/bitfinex-api-node',
],
'fees': 'https://www.bitfinex.com/fees',
},
'api': {
'v1': {
'get': [
'symbols',
'symbols_details',
],
},
'public': {
'get': {
'conf/{config}': 2.66, // 90 requests a minute
'conf/pub:{action}:{object}': 2.66,
'conf/pub:{action}:{object}:{detail}': 2.66,
'conf/pub:map:{object}': 2.66,
'conf/pub:map:{object}:{detail}': 2.66,
'conf/pub:map:currency:{detail}': 2.66,
'conf/pub:map:currency:sym': 2.66, // maps symbols to their API symbols, BAB > BCH
'conf/pub:map:currency:label': 2.66, // verbose friendly names, BNT > Bancor
'conf/pub:map:currency:unit': 2.66, // maps symbols to unit of measure where applicable
'conf/pub:map:currency:undl': 2.66, // maps derivatives symbols to their underlying currency
'conf/pub:map:currency:pool': 2.66, // maps symbols to underlying network/protocol they operate on
'conf/pub:map:currency:explorer': 2.66, // maps symbols to their recognised block explorer URLs
'conf/pub:map:currency:tx:fee': 2.66, // maps currencies to their withdrawal fees https://github.com/ccxt/ccxt/issues/7745
'conf/pub:map:tx:method': 2.66,
'conf/pub:list:{object}': 2.66,
'conf/pub:list:{object}:{detail}': 2.66,
'conf/pub:list:currency': 2.66,
'conf/pub:list:pair:exchange': 2.66,
'conf/pub:list:pair:margin': 2.66,
'conf/pub:list:pair:futures': 2.66,
'conf/pub:list:competitions': 2.66,
'conf/pub:info:{object}': 2.66,
'conf/pub:info:{object}:{detail}': 2.66,
'conf/pub:info:pair': 2.66,
'conf/pub:info:tx:status': 2.66, // [ deposit, withdrawal ] statuses 1 = active, 0 = maintenance
'conf/pub:fees': 2.66,
'platform/status': 8, // 30 requests per minute = 0.5 requests per second => ( 1000ms / rateLimit ) / 0.5 = 8
'tickers': 2.66, // 90 requests a minute = 1.5 requests per second => ( 1000 / rateLimit ) / 1.5 = 2.666666666
'ticker/{symbol}': 2.66,
'tickers/hist': 2.66,
'trades/{symbol}/hist': 2.66,
'book/{symbol}/{precision}': 1, // 240 requests a minute
'book/{symbol}/P0': 1,
'book/{symbol}/P1': 1,
'book/{symbol}/P2': 1,
'book/{symbol}/P3': 1,
'book/{symbol}/R0': 1,
'stats1/{key}:{size}:{symbol}:{side}/{section}': 2.66,
'stats1/{key}:{size}:{symbol}:{side}/last': 2.66,
'stats1/{key}:{size}:{symbol}:{side}/hist': 2.66,
'stats1/{key}:{size}:{symbol}/{section}': 2.66,
'stats1/{key}:{size}:{symbol}/last': 2.66,
'stats1/{key}:{size}:{symbol}/hist': 2.66,
'stats1/{key}:{size}:{symbol}:long/last': 2.66,
'stats1/{key}:{size}:{symbol}:long/hist': 2.66,
'stats1/{key}:{size}:{symbol}:short/last': 2.66,
'stats1/{key}:{size}:{symbol}:short/hist': 2.66,
'candles/trade:{timeframe}:{symbol}:{period}/{section}': 2.66,
'candles/trade:{timeframe}:{symbol}/{section}': 2.66,
'candles/trade:{timeframe}:{symbol}/last': 2.66,
'candles/trade:{timeframe}:{symbol}/hist': 2.66,
'status/{type}': 2.66,
'status/deriv': 2.66,
'liquidations/hist': 80, // 3 requests a minute = 0.05 requests a second => ( 1000ms / rateLimit ) / 0.05 = 80
'rankings/{key}:{timeframe}:{symbol}/{section}': 2.66,
'rankings/{key}:{timeframe}:{symbol}/hist': 2.66,
'pulse/hist': 2.66,
'pulse/profile/{nickname}': 2.66,
'funding/stats/{symbol}/hist': 10, // ratelimit not in docs
},
'post': {
'calc/trade/avg': 2.66,
'calc/fx': 2.66,
},
},
'private': {
'post': {
// 'auth/r/orders/{symbol}/new', // outdated
// 'auth/r/stats/perf:{timeframe}/hist', // outdated
'auth/r/wallets': 2.66,
'auth/r/wallets/hist': 2.66,
'auth/r/orders': 2.66,
'auth/r/orders/{symbol}': 2.66,
'auth/w/order/submit': 2.66,
'auth/w/order/update': 2.66,
'auth/w/order/cancel': 2.66,
'auth/w/order/multi': 2.66,
'auth/w/order/cancel/multi': 2.66,
'auth/r/orders/{symbol}/hist': 2.66,
'auth/r/orders/hist': 2.66,
'auth/r/order/{symbol}:{id}/trades': 2.66,
'auth/r/trades/{symbol}/hist': 2.66,
'auth/r/trades/hist': 2.66,
'auth/r/ledgers/{currency}/hist': 2.66,
'auth/r/ledgers/hist': 2.66,
'auth/r/info/margin/{key}': 2.66,
'auth/r/info/margin/base': 2.66,
'auth/r/info/margin/sym_all': 2.66,
'auth/r/positions': 2.66,
'auth/w/position/claim': 2.66,
'auth/w/position/increase:': 2.66,
'auth/r/position/increase/info': 2.66,
'auth/r/positions/hist': 2.66,
'auth/r/positions/audit': 2.66,
'auth/r/positions/snap': 2.66,
'auth/w/deriv/collateral/set': 2.66,
'auth/w/deriv/collateral/limits': 2.66,
'auth/r/funding/offers': 2.66,
'auth/r/funding/offers/{symbol}': 2.66,
'auth/w/funding/offer/submit': 2.66,
'auth/w/funding/offer/cancel': 2.66,
'auth/w/funding/offer/cancel/all': 2.66,
'auth/w/funding/close': 2.66,
'auth/w/funding/auto': 2.66,
'auth/w/funding/keep': 2.66,
'auth/r/funding/offers/{symbol}/hist': 2.66,
'auth/r/funding/offers/hist': 2.66,
'auth/r/funding/loans': 2.66,
'auth/r/funding/loans/hist': 2.66,
'auth/r/funding/loans/{symbol}': 2.66,
'auth/r/funding/loans/{symbol}/hist': 2.66,
'auth/r/funding/credits': 2.66,
'auth/r/funding/credits/hist': 2.66,
'auth/r/funding/credits/{symbol}': 2.66,
'auth/r/funding/credits/{symbol}/hist': 2.66,
'auth/r/funding/trades/{symbol}/hist': 2.66,
'auth/r/funding/trades/hist': 2.66,
'auth/r/info/funding/{key}': 2.66,
'auth/r/info/user': 2.66,
'auth/r/summary': 2.66,
'auth/r/logins/hist': 2.66,
'auth/r/permissions': 2.66,
'auth/w/token': 2.66,
'auth/r/audit/hist': 2.66,
'auth/w/transfer': 2.66, // ratelimit not in docs...
'auth/w/deposit/address': 24, // 10 requests a minute = 0.166 requests per second => ( 1000ms / rateLimit ) / 0.166 = 24
'auth/w/deposit/invoice': 24, // ratelimit not in docs
'auth/w/withdraw': 24, // ratelimit not in docs
'auth/r/movements/{currency}/hist': 2.66,
'auth/r/movements/hist': 2.66,
'auth/r/alerts': 5.33, // 45 requests a minute = 0.75 requests per second => ( 1000ms / rateLimit ) / 0.75 => 5.33
'auth/w/alert/set': 2.66,
'auth/w/alert/price:{symbol}:{price}/del': 2.66,
'auth/w/alert/{type}:{symbol}:{price}/del': 2.66,
'auth/calc/order/avail': 2.66,
'auth/w/settings/set': 2.66,
'auth/r/settings': 2.66,
'auth/w/settings/del': 2.66,
'auth/r/pulse/hist': 2.66,
'auth/w/pulse/add': 16, // 15 requests a minute = 0.25 requests per second => ( 1000ms / rateLimit ) / 0.25 => 16
'auth/w/pulse/del': 2.66,
},
},
},
'fees': {
'trading': {
'feeSide': 'get',
'percentage': true,
'tierBased': true,
'maker': this.parseNumber ('0.001'),
'taker': this.parseNumber ('0.002'),
'tiers': {
'taker': [
[ this.parseNumber ('0'), this.parseNumber ('0.002') ],
[ this.parseNumber ('500000'), this.parseNumber ('0.002') ],
[ this.parseNumber ('1000000'), this.parseNumber ('0.002') ],
[ this.parseNumber ('2500000'), this.parseNumber ('0.002') ],
[ this.parseNumber ('5000000'), this.parseNumber ('0.002') ],
[ this.parseNumber ('7500000'), this.parseNumber ('0.002') ],
[ this.parseNumber ('10000000'), this.parseNumber ('0.0018') ],
[ this.parseNumber ('15000000'), this.parseNumber ('0.0016') ],
[ this.parseNumber ('20000000'), this.parseNumber ('0.0014') ],
[ this.parseNumber ('25000000'), this.parseNumber ('0.0012') ],
[ this.parseNumber ('30000000'), this.parseNumber ('0.001') ],
],
'maker': [
[ this.parseNumber ('0'), this.parseNumber ('0.001') ],
[ this.parseNumber ('500000'), this.parseNumber ('0.0008') ],
[ this.parseNumber ('1000000'), this.parseNumber ('0.0006') ],
[ this.parseNumber ('2500000'), this.parseNumber ('0.0004') ],
[ this.parseNumber ('5000000'), this.parseNumber ('0.0002') ],
[ this.parseNumber ('7500000'), this.parseNumber ('0') ],
[ this.parseNumber ('10000000'), this.parseNumber ('0') ],
[ this.parseNumber ('15000000'), this.parseNumber ('0') ],
[ this.parseNumber ('20000000'), this.parseNumber ('0') ],
[ this.parseNumber ('25000000'), this.parseNumber ('0') ],
[ this.parseNumber ('30000000'), this.parseNumber ('0') ],
],
},
},
'funding': {
'withdraw': {},
},
},
'options': {
'precision': 'R0', // P0, P1, P2, P3, P4, R0
// convert 'EXCHANGE MARKET' to lowercase 'market'
// convert 'EXCHANGE LIMIT' to lowercase 'limit'
// everything else remains uppercase
'exchangeTypes': {
// 'MARKET': undefined,
'EXCHANGE MARKET': 'market',
// 'LIMIT': undefined,
'EXCHANGE LIMIT': 'limit',
// 'STOP': undefined,
// 'EXCHANGE STOP': undefined,
// 'TRAILING STOP': undefined,
// 'EXCHANGE TRAILING STOP': undefined,
// 'FOK': undefined,
// 'EXCHANGE FOK': undefined,
// 'STOP LIMIT': undefined,
// 'EXCHANGE STOP LIMIT': undefined,
// 'IOC': undefined,
// 'EXCHANGE IOC': undefined,
},
// convert 'market' to 'EXCHANGE MARKET'
// convert 'limit' 'EXCHANGE LIMIT'
// everything else remains as is
'orderTypes': {
'market': 'EXCHANGE MARKET',
'limit': 'EXCHANGE LIMIT',
},
'fiat': {
'USD': 'USD',
'EUR': 'EUR',
'JPY': 'JPY',
'GBP': 'GBP',
'CHN': 'CHN',
},
// actually the correct names unlike the v1
// we don't want to extend this with accountsByType in v1
'v2AccountsByType': {
'spot': 'exchange',
'exchange': 'exchange',
'funding': 'funding',
'margin': 'margin',
'derivatives': 'margin',
'future': 'margin',
},
},
'exceptions': {
'exact': {
'10001': PermissionDenied, // api_key: permission invalid (#10001)
'10020': BadRequest,
'10100': AuthenticationError,
'10114': InvalidNonce,
'20060': OnMaintenance,
// {"code":503,"error":"temporarily_unavailable","error_description":"Sorry, the service is temporarily unavailable. See https://www.bitfinex.com/ for more info."}
'temporarily_unavailable': ExchangeNotAvailable,
},
'broad': {
'address': InvalidAddress,
'available balance is only': InsufficientFunds,
'not enough exchange balance': InsufficientFunds,
'Order not found': OrderNotFound,
'symbol: invalid': BadSymbol,
'Invalid order': InvalidOrder,
},
},
});
}
isFiat (code) {
return (code in this.options['fiat']);
}
getCurrencyId (code) {
return 'f' + code;
}
getCurrencyName (code) {
// temporary fix for transpiler recognition, even though this is in parent class
if (code in this.options['currencyNames']) {
return this.options['currencyNames'][code];
}
throw new NotSupported (this.id + ' ' + code + ' not supported for withdrawal');
}
async fetchStatus (params = {}) {
//
// [1] // operative
// [0] // maintenance
//
const response = await this.publicGetPlatformStatus (params);
const status = this.safeInteger (response, 0);
const formattedStatus = (status === 1) ? 'ok' : 'maintenance';
this.status = this.extend (this.status, {
'status': formattedStatus,
'updated': this.milliseconds (),
});
return this.status;
}
async fetchMarkets (params = {}) {
// todo drop v1 in favor of v2 configs ( temp-reference for v2update: https://pastebin.com/raw/S8CmqSHQ )
// pub:list:pair:exchange,pub:list:pair:margin,pub:list:pair:futures,pub:info:pair
const v2response = await this.publicGetConfPubListPairFutures (params);
const v1response = await this.v1GetSymbolsDetails (params);
const swapMarketIds = this.safeValue (v2response, 0, []);
const result = [];
for (let i = 0; i < v1response.length; i++) {
const market = v1response[i];
const id = this.safeStringUpper (market, 'pair');
let spot = true;
if (this.inArray (id, swapMarketIds)) {
spot = false;
}
const swap = !spot;
const type = spot ? 'spot' : 'swap';
let baseId = undefined;
let quoteId = undefined;
if (id.indexOf (':') >= 0) {
const parts = id.split (':');
baseId = parts[0];
quoteId = parts[1];
} else {
baseId = id.slice (0, 3);
quoteId = id.slice (3, 6);
}
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const symbol = base + '/' + quote;
baseId = this.getCurrencyId (baseId);
quoteId = this.getCurrencyId (quoteId);
const minOrderSizeString = this.safeString (market, 'minimum_order_size');
const maxOrderSizeString = this.safeString (market, 'maximum_order_size');
result.push ({
'id': 't' + id,
'symbol': symbol,
'base': base,
'quote': quote,
'settle': undefined, // TODO
'baseId': baseId,
'quoteId': quoteId,
'settleId': undefined, // TODO
'type': type,
'spot': spot,
'margin': this.safeValue (market, 'margin'),
'swap': swap,
'future': false,
'option': false,
'active': true,
'contract': swap,
'linear': spot ? undefined : true, // TODO
'inverse': spot ? undefined : false, // TODO
'contractSize': undefined, // TODO
'maintenanceMarginRate': undefined,
'expiry': undefined,
'expiryDatetime': undefined,
'strike': undefined,
'optionType': undefined,
'precision': {
'amount': parseInt ('8'), // https://github.com/ccxt/ccxt/issues/7310
'price': this.safeInteger (market, 'price_precision'),
},
'limits': {
'leverage': {
'min': undefined,
'max': undefined,
},
'amount': {
'min': this.parseNumber (minOrderSizeString),
'max': this.parseNumber (maxOrderSizeString),
},
'price': {
'min': this.parseNumber ('1e-8'),
'max': undefined,
},
'cost': {
'min': undefined,
'max': undefined,
},
},
'info': market,
});
}
return result;
}
async fetchCurrencies (params = {}) {
const labels = [
'pub:list:currency',
'pub:map:currency:sym', // maps symbols to their API symbols, BAB > BCH
'pub:map:currency:label', // verbose friendly names, BNT > Bancor
'pub:map:currency:unit', // maps symbols to unit of measure where applicable
'pub:map:currency:undl', // maps derivatives symbols to their underlying currency
'pub:map:currency:pool', // maps symbols to underlying network/protocol they operate on
'pub:map:currency:explorer', // maps symbols to their recognised block explorer URLs
'pub:map:currency:tx:fee', // maps currencies to their withdrawal fees https://github.com/ccxt/ccxt/issues/7745
];
const config = labels.join (',');
const request = {
'config': config,
};
const response = await this.publicGetConfConfig (this.extend (request, params));
//
// [
//
// a list of symbols
// ["AAA","ABS","ADA"],
//
// // sym
// // maps symbols to their API symbols, BAB > BCH
// [
// [ 'BAB', 'BCH' ],
// [ 'CNHT', 'CNHt' ],
// [ 'DSH', 'DASH' ],
// [ 'IOT', 'IOTA' ],
// [ 'LES', 'LEO-EOS' ],
// [ 'LET', 'LEO-ERC20' ],
// [ 'STJ', 'STORJ' ],
// [ 'TSD', 'TUSD' ],
// [ 'UDC', 'USDC' ],
// [ 'USK', 'USDK' ],
// [ 'UST', 'USDt' ],
// [ 'USTF0', 'USDt0' ],
// [ 'XCH', 'XCHF' ],
// [ 'YYW', 'YOYOW' ],
// // ...
// ],
// // label
// // verbose friendly names, BNT > Bancor
// [
// [ 'BAB', 'Bitcoin Cash' ],
// [ 'BCH', 'Bitcoin Cash' ],
// [ 'LEO', 'Unus Sed LEO' ],
// [ 'LES', 'Unus Sed LEO (EOS)' ],
// [ 'LET', 'Unus Sed LEO (ERC20)' ],
// // ...
// ],
// // unit
// // maps symbols to unit of measure where applicable
// [
// [ 'IOT', 'Mi|MegaIOTA' ],
// ],
// // undl
// // maps derivatives symbols to their underlying currency
// [
// [ 'USTF0', 'UST' ],
// [ 'BTCF0', 'BTC' ],
// [ 'ETHF0', 'ETH' ],
// ],
// // pool
// // maps symbols to underlying network/protocol they operate on
// [
// [ 'SAN', 'ETH' ], [ 'OMG', 'ETH' ], [ 'AVT', 'ETH' ], [ 'EDO', 'ETH' ],
// [ 'ESS', 'ETH' ], [ 'ATD', 'EOS' ], [ 'ADD', 'EOS' ], [ 'MTO', 'EOS' ],
// [ 'PNK', 'ETH' ], [ 'BAB', 'BCH' ], [ 'WLO', 'XLM' ], [ 'VLD', 'ETH' ],
// [ 'BTT', 'TRX' ], [ 'IMP', 'ETH' ], [ 'SCR', 'ETH' ], [ 'GNO', 'ETH' ],
// // ...
// ],
// // explorer
// // maps symbols to their recognised block explorer URLs
// [
// [
// 'AIO',
// [
// "https://mainnet.aion.network",
// "https://mainnet.aion.network/#/account/VAL",
// "https://mainnet.aion.network/#/transaction/VAL"
// ]
// ],
// // ...
// ],
// // fee
// // maps currencies to their withdrawal fees
// [
// ["AAA",[0,0]],
// ["ABS",[0,131.3]],
// ["ADA",[0,0.3]],
// ],
// ]
//
const indexed = {
'sym': this.indexBy (this.safeValue (response, 1, []), 0),
'label': this.indexBy (this.safeValue (response, 2, []), 0),
'unit': this.indexBy (this.safeValue (response, 3, []), 0),
'undl': this.indexBy (this.safeValue (response, 4, []), 0),
'pool': this.indexBy (this.safeValue (response, 5, []), 0),
'explorer': this.indexBy (this.safeValue (response, 6, []), 0),
'fees': this.indexBy (this.safeValue (response, 7, []), 0),
};
const ids = this.safeValue (response, 0, []);
const result = {};
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
const code = this.safeCurrencyCode (id);
const label = this.safeValue (indexed['label'], id, []);
const name = this.safeString (label, 1);
const pool = this.safeValue (indexed['pool'], id, []);
const type = this.safeString (pool, 1);
const feeValues = this.safeValue (indexed['fees'], id, []);
const fees = this.safeValue (feeValues, 1, []);
const fee = this.safeNumber (fees, 1);
const undl = this.safeValue (indexed['undl'], id, []);
const precision = 8; // default precision, todo: fix "magic constants"
const fid = 'f' + id;
result[code] = {
'id': fid,
'uppercaseId': id,
'code': code,
'info': [ id, label, pool, feeValues, undl ],
'type': type,
'name': name,
'active': true,
'deposit': undefined,
'withdraw': undefined,
'fee': fee,
'precision': precision,
'limits': {
'amount': {
'min': 1 / Math.pow (10, precision),
'max': undefined,
},
'withdraw': {
'min': fee,
'max': undefined,
},
},
};
}
return result;
}
async fetchBalance (params = {}) {
// this api call does not return the 'used' amount - use the v1 version instead (which also returns zero balances)
// there is a difference between this and the v1 api, namely trading wallet is called margin in v2
await this.loadMarkets ();
const accountsByType = this.safeValue (this.options, 'v2AccountsByType', {});
const requestedType = this.safeString (params, 'type', 'exchange');
const accountType = this.safeString (accountsByType, requestedType);
if (accountType === undefined) {
const keys = Object.keys (accountsByType);
throw new ExchangeError (this.id + ' fetchBalance type parameter must be one of ' + keys.join (', '));
}
const isDerivative = requestedType === 'derivatives';
const query = this.omit (params, 'type');
const response = await this.privatePostAuthRWallets (query);
const result = { 'info': response };
for (let i = 0; i < response.length; i++) {
const balance = response[i];
const type = this.safeString (balance, 0);
const currencyId = this.safeStringLower (balance, 1, '');
const start = currencyId.length - 2;
const isDerivativeCode = currencyId.slice (start) === 'f0';
// this will only filter the derivative codes if the requestedType is 'derivatives'
const derivativeCondition = (!isDerivative || isDerivativeCode);
if ((accountType === type) && derivativeCondition) {
const code = this.safeCurrencyCode (currencyId);
const account = this.account ();
account['total'] = this.safeString (balance, 2);
account['free'] = this.safeString (balance, 4);
result[code] = account;
}
}
return this.safeBalance (result);
}
async transfer (code, amount, fromAccount, toAccount, params = {}) {
// transferring between derivatives wallet and regular wallet is not documented in their API
// however we support it in CCXT (from just looking at web inspector)
await this.loadMarkets ();
const accountsByType = this.safeValue (this.options, 'v2AccountsByType', {});
const fromId = this.safeString (accountsByType, fromAccount);
if (fromId === undefined) {
const keys = Object.keys (accountsByType);
throw new ExchangeError (this.id + ' transfer fromAccount must be one of ' + keys.join (', '));
}
const toId = this.safeString (accountsByType, toAccount);
if (toId === undefined) {
const keys = Object.keys (accountsByType);
throw new ExchangeError (this.id + ' transfer toAccount must be one of ' + keys.join (', '));
}
const currency = this.currency (code);
const fromCurrencyId = this.convertDerivativesId (currency, fromAccount);
const toCurrencyId = this.convertDerivativesId (currency, toAccount);
const requestedAmount = this.currencyToPrecision (code, amount);
// this request is slightly different from v1 fromAccount -> from
const request = {
'amount': requestedAmount,
'currency': fromCurrencyId,
'currency_to': toCurrencyId,
'from': fromId,
'to': toId,
};
const response = await this.privatePostAuthWTransfer (this.extend (request, params));
// [1616451183763,"acc_tf",null,null,[1616451183763,"exchange","margin",null,"UST","UST",null,1],null,"SUCCESS","1.0 Tether USDt transfered from Exchange to Margin"]
const timestamp = this.safeInteger (response, 0);
// ["error",10001,"Momentary balance check. Please wait few seconds and try the transfer again."]
const error = this.safeString (response, 0);
if (error === 'error') {
const message = this.safeString (response, 2, '');
// same message as in v1
this.throwExactlyMatchedException (this.exceptions['exact'], message, this.id + ' ' + message);
throw new ExchangeError (this.id + ' ' + message);
}
const info = this.safeValue (response, 4);
const fromResponse = this.safeString (info, 1);
const toResponse = this.safeString (info, 2);
const toCode = this.safeCurrencyCode (this.safeString (info, 5));
const success = this.safeString (response, 6);
const status = (success === 'SUCCESS') ? 'ok' : undefined;
return {
'info': response,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'status': status,
'amount': requestedAmount,
'code': toCode,
'fromAccount': fromResponse,
'toAccount': toResponse,
};
}
convertDerivativesId (currency, type) {
// there is a difference between this and the v1 api, namely trading wallet is called margin in v2
// {
// id: 'fUSTF0',
// code: 'USTF0',
// info: [ 'USTF0', [], [], [], [ 'USTF0', 'UST' ] ],
const info = this.safeValue (currency, 'info');
const transferId = this.safeString (info, 0);
const underlying = this.safeValue (info, 4, []);
let currencyId = undefined;
if (type === 'derivatives') {
currencyId = this.safeString (underlying, 0, transferId);
const start = currencyId.length - 2;
const isDerivativeCode = currencyId.slice (start) === 'F0';
if (!isDerivativeCode) {
currencyId = currencyId + 'F0';
}
} else if (type !== 'margin') {
currencyId = this.safeString (underlying, 1, transferId);
} else {
currencyId = transferId;
}
return currencyId;
}
async fetchOrder (id, symbol = undefined, params = {}) {
throw new NotSupported (this.id + ' fetchOrder is not implemented yet');
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
const precision = this.safeValue (this.options, 'precision', 'R0');
const request = {
'symbol': this.marketId (symbol),
'precision': precision,
};
if (limit !== undefined) {
request['len'] = limit; // 25 or 100
}
const fullRequest = this.extend (request, params);
const orderbook = await this.publicGetBookSymbolPrecision (fullRequest);
const timestamp = this.milliseconds ();
const result = {
'symbol': symbol,
'bids': [],
'asks': [],
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'nonce': undefined,
};
const priceIndex = (fullRequest['precision'] === 'R0') ? 1 : 0;
for (let i = 0; i < orderbook.length; i++) {
const order = orderbook[i];
const price = this.safeNumber (order, priceIndex);
const signedAmount = this.safeNumber (order, 2);
const amount = Math.abs (signedAmount);
const side = (signedAmount > 0) ? 'bids' : 'asks';
result[side].push ([ price, amount ]);
}
result['bids'] = this.sortBy (result['bids'], 0, true);
result['asks'] = this.sortBy (result['asks'], 0);
return result;
}
parseTicker (ticker, market = undefined) {
//
// on trading pairs (ex. tBTCUSD)
//
// [
// SYMBOL,
// BID,
// BID_SIZE,
// ASK,
// ASK_SIZE,
// DAILY_CHANGE,
// DAILY_CHANGE_RELATIVE,
// LAST_PRICE,
// VOLUME,
// HIGH,
// LOW
// ]
//
// on funding currencies (ex. fUSD)
//
// [
// SYMBOL,
// FRR,
// BID,
// BID_PERIOD,
// BID_SIZE,
// ASK,
// ASK_PERIOD,
// ASK_SIZE,
// DAILY_CHANGE,
// DAILY_CHANGE_RELATIVE,
// LAST_PRICE,
// VOLUME,
// HIGH,
// LOW,
// _PLACEHOLDER,
// _PLACEHOLDER,
// FRR_AMOUNT_AVAILABLE
// ]
//
const timestamp = this.milliseconds ();
const symbol = this.safeSymbol (undefined, market);
const length = ticker.length;
const last = this.safeString (ticker, length - 4);
const percentage = this.safeString (ticker, length - 5);
return this.safeTicker ({
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeString (ticker, length - 2),
'low': this.safeString (ticker, length - 1),
'bid': this.safeString (ticker, length - 10),
'bidVolume': undefined,
'ask': this.safeString (ticker, length - 8),
'askVolume': undefined,
'vwap': undefined,
'open': undefined,
'close': last,
'last': last,
'previousClose': undefined,
'change': this.safeString (ticker, length - 6),
'percentage': Precise.stringMul (percentage, '100'),
'average': undefined,
'baseVolume': this.safeString (ticker, length - 3),
'quoteVolume': undefined,
'info': ticker,
}, market, false);
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
if (symbols !== undefined) {
const ids = this.marketIds (symbols);
request['symbols'] = ids.join (',');
} else {
request['symbols'] = 'ALL';
}
const tickers = await this.publicGetTickers (this.extend (request, params));
//
// [
// // on trading pairs (ex. tBTCUSD)
// [
// SYMBOL,
// BID,
// BID_SIZE,
// ASK,
// ASK_SIZE,
// DAILY_CHANGE,
// DAILY_CHANGE_RELATIVE,
// LAST_PRICE,
// VOLUME,
// HIGH,
// LOW
// ],
// // on funding currencies (ex. fUSD)
// [
// SYMBOL,
// FRR,
// BID,
// BID_PERIOD,
// BID_SIZE,
// ASK,
// ASK_PERIOD,
// ASK_SIZE,
// DAILY_CHANGE,
// DAILY_CHANGE_RELATIVE,
// LAST_PRICE,
// VOLUME,
// HIGH,
// LOW,
// _PLACEHOLDER,
// _PLACEHOLDER,
// FRR_AMOUNT_AVAILABLE
// ],
// ...
// ]
//
const result = {};
for (let i = 0; i < tickers.length; i++) {
const ticker = tickers[i];
const id = ticker[0];
if (id in this.markets_by_id) {
const market = this.markets_by_id[id];
const symbol = market['symbol'];
result[symbol] = this.parseTicker (ticker, market);
}
}
return this.filterByArray (result, 'symbol', symbols);
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
};
const ticker = await this.publicGetTickerSymbol (this.extend (request, params));
return this.parseTicker (ticker, market);
}
parseSymbol (marketId) {
if (marketId === undefined) {
return marketId;
}
marketId = marketId.replace ('t', '');
let baseId = undefined;
let quoteId = undefined;
if (marketId.indexOf (':') >= 0) {
const parts = marketId.split (':');
baseId = parts[0];
quoteId = parts[1];
} else {
baseId = marketId.slice (0, 3);
quoteId = marketId.slice (3, 6);
}
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
return base + '/' + quote;
}
parseTrade (trade, market = undefined) {
//
// fetchTrades (public)
//
// [
// ID,
// MTS, // timestamp
// AMOUNT,
// PRICE
// ]
//
// fetchMyTrades (private)
//
// [
// ID,
// PAIR,
// MTS_CREATE,
// ORDER_ID,
// EXEC_AMOUNT,
// EXEC_PRICE,
// ORDER_TYPE,
// ORDER_PRICE,
// MAKER,
// FEE,
// FEE_CURRENCY,
// ...
// ]
//
const tradeLength = trade.length;
const isPrivate = (tradeLength > 5);
const id = this.safeString (trade, 0);
const amountIndex = isPrivate ? 4 : 2;
let side = undefined;
let amountString = this.safeString (trade, amountIndex);
const priceIndex = isPrivate ? 5 : 3;
const priceString = this.safeString (trade, priceIndex);
if (amountString[0] === '-') {
side = 'sell';
amountString = Precise.stringAbs (amountString);
} else {
side = 'buy';
}
let orderId = undefined;
let takerOrMaker = undefined;
let type = undefined;
let fee = undefined;
let symbol = undefined;
const timestampIndex = isPrivate ? 2 : 1;
const timestamp = this.safeInteger (trade, timestampIndex);
if (isPrivate) {
const marketId = trade[1];
if (marketId in this.markets_by_id) {
market = this.markets_by_id[marketId];
symbol = market['symbol'];
} else {
symbol = this.parseSymbol (marketId);
}
orderId = this.safeString (trade, 3);
const maker = this.safeInteger (trade, 8);
takerOrMaker = (maker === 1) ? 'maker' : 'taker';
let feeCostString = this.safeString (trade, 9);
feeCostString = Precise.stringNeg (feeCostString);
const feeCurrencyId = this.safeString (trade, 10);
const feeCurrency = this.safeCurrencyCode (feeCurrencyId);
fee = {
'cost': feeCostString,
'currency': feeCurrency,
};
const orderType = trade[6];
type = this.safeString (this.options['exchangeTypes'], orderType);
}
if (symbol === undefined) {
if (market !== undefined) {
symbol = market['symbol'];
}
}
return this.safeTrade ({
'id': id,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'order': orderId,
'side': side,
'type': type,
'takerOrMaker': takerOrMaker,
'price': priceString,
'amount': amountString,
'cost': undefined,
'fee': fee,
'info': trade,
}, market);
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
let sort = '-1';
const request = {
'symbol': market['id'],
};
if (since !== undefined) {
request['start'] = since;
sort = '1';
}
if (limit !== undefined) {
request['limit'] = limit; // default 120, max 5000
}
request['sort'] = sort;
const response = await this.publicGetTradesSymbolHist (this.extend (request, params));
//
// [
// [
// ID,
// MTS, // timestamp
// AMOUNT,
// PRICE
// ]
// ]
//
const trades = this.sortBy (response, 1);
return this.parseTrades (trades, market, undefined, limit);
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = 100, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
if (limit === undefined) {
limit = 100; // default 100, max 5000
}
if (since === undefined) {
const duration = this.parseTimeframe (timeframe);
since = this.milliseconds () - duration * limit * 1000;
}
const request = {
'symbol': market['id'],
'timeframe': this.timeframes[timeframe],
'sort': 1,
'start': since,
'limit': limit,
};
const response = await this.publicGetCandlesTradeTimeframeSymbolHist (this.extend (request, params));
//
// [
// [1591503840000,0.025069,0.025068,0.025069,0.025068,1.97828998],
// [1591504500000,0.025065,0.025065,0.025065,0.025065,1.0164],
// [1591504620000,0.025062,0.025062,0.025062,0.025062,0.5],
// ]
//
return this.parseOHLCVs (response, market, timeframe, since, limit);
}
parseOrderStatus (status) {
if (status === undefined) {
return status;
}
const parts = status.split (' ');
const state = this.safeString (parts, 0);
const statuses = {
'ACTIVE': 'open',
'PARTIALLY': 'open',
'EXECUTED': 'closed',
'CANCELED': 'canceled',
'INSUFFICIENT': 'canceled',
'POSTONLY': 'canceled',
'RSN_DUST': 'rejected',
'RSN_PAUSE': 'rejected',
};
return this.safeString (statuses, state, status);
}
parseOrder (order, market = undefined) {
const id = this.safeString (order, 0);
let symbol = undefined;
const marketId = this.safeString (order, 3);
if (marketId in this.markets_by_id) {
market = this.markets_by_id[marketId];
} else {
symbol = this.parseSymbol (marketId);
}
if ((symbol === undefined) && (market !== undefined)) {
symbol = market['symbol'];
}
// https://github.com/ccxt/ccxt/issues/6686
// const timestamp = this.safeTimestamp (order, 5);
const timestamp = this.safeInteger (order, 5);
const remaining = Precise.stringAbs (this.safeString (order, 6));
const signedAmount = this.safeString (order, 7);
const amount = Precise.stringAbs (signedAmount);
const side = Precise.stringLt (signedAmount, '0') ? 'sell' : 'buy';
const orderType = this.safeString (order, 8);
const type = this.safeString (this.safeValue (this.options, 'exchangeTypes'), orderType);
let status = undefined;
const statusString = this.safeString (order, 13);
if (statusString !== undefined) {
const parts = statusString.split (' @ ');
status = this.parseOrderStatus (this.safeString (parts, 0));
}
const price = this.safeString (order, 16);
const average = this.safeString (order, 17);
const clientOrderId = this.safeString (order, 2);
return this.safeOrder ({
'info': order,
'id': id,
'clientOrderId': clientOrderId,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': undefined,
'symbol': symbol,
'type': type,
'timeInForce': undefined,
'postOnly': undefined,
'side': side,
'price': price,
'stopPrice': undefined,
'amount': amount,
'cost': undefined,
'average': average,
'filled': undefined,
'remaining': remaining,
'status': status,
'fee': undefined,
'trades': undefined,
}, market);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const orderTypes = this.safeValue (this.options, 'orderTypes', {});
const orderType = this.safeStringUpper (orderTypes, type, type);
const postOnly = this.safeValue (params, 'postOnly', false);
params = this.omit (params, [ 'postOnly' ]);
amount = (side === 'sell') ? -amount : amount;
const request = {
// 'gid': 0123456789, // int32, optional group id for the order
// 'cid': 0123456789, // int32 client order id
'type': orderType,
'symbol': market['id'],
// 'price': this.numberToString (price),
'amount': this.numberToString (amount),
// 'flags': 0, // int32, https://docs.bitfinex.com/v2/docs/flag-values
// 'lev': 10, // the value should be between 1 and 100 inclusive, optional, 10 by default
// 'price_trailing': this.numberToString (priceTrailing),
// 'price_aux_limit': this.numberToString (stopPrice),
// 'price_oco_stop': this.numberToString (ocoStopPrice),
// 'tif': '2020-01-01 10:45:23', // datetime for automatic order cancellation
// 'meta': {
// 'aff_code': 'AFF_CODE_HERE'
// },
};
if (postOnly) {
request['flags'] = 4096;
}
if ((orderType === 'LIMIT') || (orderType === 'EXCHANGE LIMIT')) {
request['price'] = this.numberToString (price);
} else if ((orderType === 'STOP') || (orderType === 'EXCHANGE STOP')) {
const stopPrice = this.safeNumber (params, 'stopPrice', price);
request['price'] = this.numberToString (stopPrice);
} else if ((orderType === 'STOP LIMIT') || (orderType === 'EXCHANGE STOP LIMIT')) {
const priceAuxLimit = this.safeNumber (params, 'price_aux_limit');
let stopPrice = this.safeNumber (params, 'stopPrice');
if (priceAuxLimit === undefined) {
if (stopPrice === undefined) {
throw new ArgumentsRequired (this.id + ' createOrder() requires a stopPrice parameter or a price_aux_limit parameter for a ' + orderType + ' order');
} else {
request['price_aux_limit'] = this.numberToString (price);
}
} else {
request['price_aux_limit'] = this.numberToString (priceAuxLimit);
if (stopPrice === undefined) {
stopPrice = price;
}
}
request['price'] = this.numberToString (stopPrice);
} else if ((orderType === 'TRAILING STOP') || (orderType === 'EXCHANGE TRAILING STOP')) {
const priceTrailing = this.safeNumber (params, 'price_trailing');
request['price_trailing'] = this.numberToString (priceTrailing);
const stopPrice = this.safeNumber (params, 'stopPrice', price);
request['price'] = this.numberToString (stopPrice);
} else if ((orderType === 'FOK') || (orderType === 'EXCHANGE FOK') || (orderType === 'IOC') || (orderType === 'EXCHANGE IOC')) {
request['price'] = this.numberToString (price);
}
params = this.omit (params, [ 'stopPrice', 'price_aux_limit', 'price_trailing' ]);
const clientOrderId = this.safeValue2 (params, 'cid', 'clientOrderId');
if (clientOrderId !== undefined) {
request['cid'] = clientOrderId;
params = this.omit (params, [ 'cid', 'clientOrderId' ]);
}
const response = await this.privatePostAuthWOrderSubmit (this.extend (request, params));
//
// [
// 1578784364.748, // Millisecond Time Stamp of the update
// "on-req", // Purpose of notification ('on-req', 'oc-req', 'uca', 'fon-req', 'foc-req')
// null, // Unique ID of the message
// null, // Ignore
// [
// [
// 37271830598, // Order ID
// null, // Group ID
// 1578784364748, // Client Order ID
// "tBTCUST", // Pair
// 1578784364748, // Millisecond timestamp of creation
// 1578784364748, // Millisecond timestamp of update
// -0.005, // Positive means buy, negative means sell
// -0.005, // Original amount
// "EXCHANGE LIMIT", // Order type (LIMIT, MARKET, STOP, TRAILING STOP, EXCHANGE MARKET, EXCHANGE LIMIT, EXCHANGE STOP, EXCHANGE TRAILING STOP, FOK, EXCHANGE FOK, IOC, EXCHANGE IOC)
// null, // Previous order type
// null, // Millisecond timestamp of Time-In-Force: automatic order cancellation
// null, // Ignore
// 0, // Flags (see https://docs.bitfinex.com/docs/flag-values)
// "ACTIVE", // Order Status
// null, // Ignore
// null, // Ignore
// 20000, // Price
// 0, // Average price
// 0, // The trailing price
// 0, // Auxiliary Limit price (for STOP LIMIT)
// null, // Ignore
// null, // Ignore
// null, // Ignore
// 0, // 1 - hidden order
// null, // If another order caused this order to be placed (OCO) this will be that other order's ID
// null, // Ignore
// null, // Ignore
// null, // Ignore
// "API>BFX", // Origin of action: BFX, ETHFX, API>BFX, API>ETHFX
// null, // Ignore
// null, // Ignore
// null // Meta
// ]
// ],
// null, // Error code
// "SUCCESS", // Status (SUCCESS, ERROR, FAILURE, ...)
// "Submitting 1 orders." // Text of the notification
// ]
//
const status = this.safeString (response, 6);
if (status !== 'SUCCESS') {
const errorCode = response[5];
const errorText = response[7];
throw new ExchangeError (this.id + ' ' + response[6] + ': ' + errorText + ' (#' + errorCode + ')');
}
const orders = this.safeValue (response, 4, []);
const order = this.safeValue (orders, 0);
return this.parseOrder (order, market);
}
async cancelAllOrders (symbol = undefined, params = {}) {
const request = {
'all': 1,
};
const response = await this.privatePostAuthWOrderCancelMulti (this.extend (request, params));
const orders = this.safeValue (response, 4, []);
return this.parseOrders (orders);
}
async cancelOrder (id, symbol = undefined, params = {}) {
const cid = this.safeValue2 (params, 'cid', 'clientOrderId'); // client order id
let request = undefined;
if (cid !== undefined) {
const cidDate = this.safeValue (params, 'cidDate'); // client order id date
if (cidDate === undefined) {
throw new InvalidOrder (this.id + " canceling an order by clientOrderId ('cid') requires both 'cid' and 'cid_date' ('YYYY-MM-DD')");
}
request = {
'cid': cid,
'cid_date': cidDate,
};
params = this.omit (params, [ 'cid', 'clientOrderId' ]);
} else {
request = {
'id': parseInt (id),
};
}
const response = await this.privatePostAuthWOrderCancel (this.extend (request, params));
const order = this.safeValue (response, 4);
return this.parseOrder (order);
}
async fetchOpenOrder (id, symbol = undefined, params = {}) {
const request = {
'id': [ parseInt (id) ],
};
const orders = await this.fetchOpenOrders (symbol, undefined, undefined, this.extend (request, params));
const order = this.safeValue (orders, 0);
if (order === undefined) {
throw new OrderNotFound (this.id + ' order ' + id + ' not found');
}
return order;
}
async fetchClosedOrder (id, symbol = undefined, params = {}) {
const request = {
'id': [ parseInt (id) ],
};
const orders = await this.fetchClosedOrders (symbol, undefined, undefined, this.extend (request, params));
const order = this.safeValue (orders, 0);
if (order === undefined) {
throw new OrderNotFound (this.id + ' order ' + id + ' not found');
}
return order;
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
let market = undefined;
let response = undefined;
if (symbol === undefined) {
response = await this.privatePostAuthROrders (this.extend (request, params));
} else {
market = this.market (symbol);
request['symbol'] = market['id'];
response = await this.privatePostAuthROrdersSymbol (this.extend (request, params));
}
return this.parseOrders (response, market, since, limit);
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
// returns the most recent closed or canceled orders up to circa two weeks ago
await this.loadMarkets ();
const request = {};
let market = undefined;
let response = undefined;
if (symbol === undefined) {
response = await this.privatePostAuthROrdersHist (this.extend (request, params));
} else {
market = this.market (symbol);
request['symbol'] = market['id'];
response = await this.privatePostAuthROrdersSymbolHist (this.extend (request, params));
}
if (since !== undefined) {
request['start'] = since;
}
if (limit !== undefined) {
request['limit'] = limit; // default 25, max 2500
}
return this.parseOrders (response, market, since, limit);
}
async fetchOrderTrades (id, symbol = undefined, since = undefined, limit = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchOrderTrades() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
const orderId = parseInt (id);
const request = {
'id': orderId,
'symbol': market['id'],
};
// valid for trades upto 10 days old
const response = await this.privatePostAuthROrderSymbolIdTrades (this.extend (request, params));
return this.parseTrades (response, market, since, limit);
}
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {
'end': this.milliseconds (),
};
if (since !== undefined) {
request['start'] = since;
}
if (limit !== undefined) {
request['limit'] = limit; // default 25, max 1000
}
let method = 'privatePostAuthRTradesHist';
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
method = 'privatePostAuthRTradesSymbolHist';
}
const response = await this[method] (this.extend (request, params));
return this.parseTrades (response, market, since, limit);
}
async createDepositAddress (code, params = {}) {
await this.loadMarkets ();
const request = {
'op_renew': 1,
};
const response = await this.fetchDepositAddress (code, this.extend (request, params));
return response;
}
async fetchDepositAddress (code, params = {}) {
await this.loadMarkets ();
// todo rewrite for https://api-pub.bitfinex.com//v2/conf/pub:map:tx:method
const name = this.getCurrencyName (code);
const request = {
'method': name,
'wallet': 'exchange', // 'exchange', 'margin', 'funding' and also old labels 'exchange', 'trading', 'deposit', respectively
'op_renew': 0, // a value of 1 will generate a new address
};
const response = await this.privatePostAuthWDepositAddress (this.extend (request, params));
//
// [
// 1582269616687, // MTS Millisecond Time Stamp of the update
// 'acc_dep', // TYPE Purpose of notification 'acc_dep' for account deposit
// null, // MESSAGE_ID unique ID of the message
// null, // not documented
// [
// null, // PLACEHOLDER
// 'BITCOIN', // METHOD Method of deposit
// 'BTC', // CURRENCY_CODE Currency code of new address
// null, // PLACEHOLDER
// '1BC9PZqpUmjyEB54uggn8TFKj49zSDYzqG', // ADDRESS
// null, // POOL_ADDRESS
// ],
// null, // CODE null or integer work in progress
// 'SUCCESS', // STATUS Status of the notification, SUCCESS, ERROR, FAILURE
// 'success', // TEXT Text of the notification
// ]
//
const result = this.safeValue (response, 4, []);
const poolAddress = this.safeString (result, 5);
const address = (poolAddress === undefined) ? this.safeString (result, 4) : poolAddress;
const tag = (poolAddress === undefined) ? undefined : this.safeString (result, 4);
this.checkAddress (address);
return {
'currency': code,
'address': address,
'tag': tag,
'network': undefined,
'info': response,
};
}
parseTransactionStatus (status) {
const statuses = {
'SUCCESS': 'ok',
'ERROR': 'failed',
'FAILURE': 'failed',
'CANCELED': 'canceled',
'COMPLETED': 'ok',
};
return this.safeString (statuses, status, status);
}
parseTransaction (transaction, currency = undefined) {
//
// withdraw
//
// [
// 1582271520931, // MTS Millisecond Time Stamp of the update
// "acc_wd-req", // TYPE Purpose of notification 'acc_wd-req' account withdrawal request
// null, // MESSAGE_ID unique ID of the message
// null, // not documented
// [
// 0, // WITHDRAWAL_ID Unique Withdrawal ID
// null, // PLACEHOLDER
// "bitcoin", // METHOD Method of withdrawal
// null, // PAYMENT_ID Payment ID if relevant
// "exchange", // WALLET Sending wallet
// 1, // AMOUNT Amount of Withdrawal less fee
// null, // PLACEHOLDER
// null, // PLACEHOLDER
// 0.0004, // WITHDRAWAL_FEE Fee on withdrawal
// ],
// null, // CODE null or integer Work in progress
// "SUCCESS", // STATUS Status of the notification, it may vary over time SUCCESS, ERROR, FAILURE
// "Invalid bitcoin address (abcdef)", // TEXT Text of the notification
// ]
//
// fetchTransactions
//
// [
// 13293039, // ID
// 'ETH', // CURRENCY
// 'ETHEREUM', // CURRENCY_NAME
// null,
// null,
// 1574175052000, // MTS_STARTED
// 1574181326000, // MTS_UPDATED
// null,
// null,
// 'CANCELED', // STATUS
// null,
// null,
// -0.24, // AMOUNT, negative for withdrawals
// -0.00135, // FEES
// null,
// null,
// '0x38110e0Fc932CB2BE...........', // DESTINATION_ADDRESS
// null,
// null,
// null,
// '0x523ec8945500.....................................', // TRANSACTION_ID
// "Purchase of 100 pizzas", // WITHDRAW_TRANSACTION_NOTE, might also be: null
// ]
//
const transactionLength = transaction.length;
let timestamp = undefined;
let updated = undefined;
let code = undefined;
let amount = undefined;
let id = undefined;
let status = undefined;
let tag = undefined;
let type = undefined;
let feeCost = undefined;
let txid = undefined;
let addressTo = undefined;
if (transactionLength === 8) {
const data = this.safeValue (transaction, 4, []);
timestamp = this.safeInteger (transaction, 0);
if (currency !== undefined) {
code = currency['code'];
}
feeCost = this.safeNumber (data, 8);
if (feeCost !== undefined) {
feeCost = -feeCost;
}
amount = this.safeNumber (data, 5);
id = this.safeValue (data, 0);
status = 'ok';
if (id === 0) {
id = undefined;
status = 'failed';
}
tag = this.safeString (data, 3);
type = 'withdrawal';
} else if (transactionLength === 22) {
id = this.safeString (transaction, 0);
const currencyId = this.safeString (transaction, 1);
code = this.safeCurrencyCode (currencyId, currency);
timestamp = this.safeInteger (transaction, 5);
updated = this.safeInteger (transaction, 6);
status = this.parseTransactionStatus (this.safeString (transaction, 9));
amount = this.safeNumber (transaction, 12);
if (amount !== undefined) {
if (amount < 0) {
type = 'withdrawal';
} else {
type = 'deposit';
}
}
feeCost = this.safeNumber (transaction, 13);
if (feeCost !== undefined) {
feeCost = -feeCost;
}
addressTo = this.safeString (transaction, 16);
txid = this.safeString (transaction, 20);
}
return {
'info': transaction,
'id': id,
'txid': txid,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'network': undefined,
'addressFrom': undefined,
'address': addressTo, // this is actually the tag for XRP transfers (the address is missing)
'addressTo': addressTo,
'tagFrom': undefined,
'tag': tag, // refix it properly for the tag from description
'tagTo': tag,
'type': type,
'amount': amount,
'currency': code,
'status': status,
'updated': updated,
'fee': {
'currency': code,
'cost': feeCost,
'rate': undefined,
},
};
}
async fetchTradingFees (params = {}) {
await this.loadMarkets ();
const response = await this.privatePostAuthRSummary (params);
//
// Response Spec:
// [
// PLACEHOLDER,
// PLACEHOLDER,
// PLACEHOLDER,
// PLACEHOLDER,
// [
// [
// MAKER_FEE,
// MAKER_FEE,
// MAKER_FEE,
// PLACEHOLDER,
// PLACEHOLDER,
// DERIV_REBATE
// ],
// [
// TAKER_FEE_TO_CRYPTO,
// TAKER_FEE_TO_STABLE,
// TAKER_FEE_TO_FIAT,
// PLACEHOLDER,
// PLACEHOLDER,
// DERIV_TAKER_FEE
// ]
// ],
// PLACEHOLDER,
// PLACEHOLDER,
// PLACEHOLDER,
// PLACEHOLDER,
// {
// LEO_LEV,
// LEO_AMOUNT_AVG
// }
// ]
//
// Example response:
//
// [
// null,
// null,
// null,
// null,
// [
// [ 0.001, 0.001, 0.001, null, null, 0.0002 ],
// [ 0.002, 0.002, 0.002, null, null, 0.00065 ]
// ],
// [
// [
// {
// curr: 'Total (USD)',
// vol: '0',
// vol_safe: '0',
// vol_maker: '0',
// vol_BFX: '0',
// vol_BFX_safe: '0',
// vol_BFX_maker: '0'
// }
// ],
// {},
// 0
// ],
// [ null, {}, 0 ],
// null,
// null,
// { leo_lev: '0', leo_amount_avg: '0' }
// ]
//
const result = {};
const fiat = this.safeValue (this.options, 'fiat', {});
const feeData = this.safeValue (response, 4, []);
const makerData = this.safeValue (feeData, 0, []);
const takerData = this.safeValue (feeData, 1, []);
const makerFee = this.safeNumber (makerData, 0);
const makerFeeFiat = this.safeNumber (makerData, 2);
const makerFeeDeriv = this.safeNumber (makerData, 5);
const takerFee = this.safeNumber (takerData, 0);
const takerFeeFiat = this.safeNumber (takerData, 2);
const takerFeeDeriv = this.safeNumber (takerData, 5);
for (let i = 0; i < this.symbols.length; i++) {
const symbol = this.symbols[i];
const market = this.market (symbol);
const fee = {
'info': response,
'symbol': symbol,
'percentage': true,
'tierBased': true,
};
if (market['quote'] in fiat) {
fee['maker'] = makerFeeFiat;
fee['taker'] = takerFeeFiat;
} else if (market['contract']) {
fee['maker'] = makerFeeDeriv;
fee['taker'] = takerFeeDeriv;
} else { // TODO check if stable coin
fee['maker'] = makerFee;
fee['taker'] = takerFee;
}
result[symbol] = fee;
}
return result;
}
async fetchTransactions (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let currency = undefined;
const request = {};
let method = 'privatePostAuthRMovementsHist';
if (code !== undefined) {
currency = this.currency (code);
request['currency'] = currency['uppercaseId'];
method = 'privatePostAuthRMovementsCurrencyHist';
}
if (since !== undefined) {
request['start'] = since;
}
if (limit !== undefined) {
request['limit'] = limit; // max 1000
}
const response = await this[method] (this.extend (request, params));
//
// [
// [
// 13293039, // ID
// 'ETH', // CURRENCY
// 'ETHEREUM', // CURRENCY_NAME
// null,
// null,
// 1574175052000, // MTS_STARTED
// 1574181326000, // MTS_UPDATED
// null,
// null,
// 'CANCELED', // STATUS
// null,
// null,
// -0.24, // AMOUNT, negative for withdrawals
// -0.00135, // FEES
// null,
// null,
// '0x38110e0Fc932CB2BE...........', // DESTINATION_ADDRESS
// null,
// null,
// null,
// '0x523ec8945500.....................................', // TRANSACTION_ID
// "Purchase of 100 pizzas", // WITHDRAW_TRANSACTION_NOTE, might also be: null
// ]
// ]
//
return this.parseTransactions (response, currency, since, limit);
}
async withdraw (code, amount, address, tag = undefined, params = {}) {
this.checkAddress (address);
await this.loadMarkets ();
const currency = this.currency (code);
// todo rewrite for https://api-pub.bitfinex.com//v2/conf/pub:map:tx:method
const name = this.getCurrencyName (code);
const request = {
'method': name,
'wallet': 'exchange', // 'exchange', 'margin', 'funding' and also old labels 'exchange', 'trading', 'deposit', respectively
'amount': this.numberToString (amount),
'address': address,
};
if (tag !== undefined) {
request['payment_id'] = tag;
}
const response = await this.privatePostAuthWWithdraw (this.extend (request, params));
//
// [
// 1582271520931, // MTS Millisecond Time Stamp of the update
// "acc_wd-req", // TYPE Purpose of notification 'acc_wd-req' account withdrawal request
// null, // MESSAGE_ID unique ID of the message
// null, // not documented
// [
// 0, // WITHDRAWAL_ID Unique Withdrawal ID
// null, // PLACEHOLDER
// "bitcoin", // METHOD Method of withdrawal
// null, // PAYMENT_ID Payment ID if relevant
// "exchange", // WALLET Sending wallet
// 1, // AMOUNT Amount of Withdrawal less fee
// null, // PLACEHOLDER
// null, // PLACEHOLDER
// 0.0004, // WITHDRAWAL_FEE Fee on withdrawal
// ],
// null, // CODE null or integer Work in progress
// "SUCCESS", // STATUS Status of the notification, it may vary over time SUCCESS, ERROR, FAILURE
// "Invalid bitcoin address (abcdef)", // TEXT Text of the notification
// ]
//
const text = this.safeString (response, 7);
if (text !== 'success') {
this.throwBroadlyMatchedException (this.exceptions['broad'], text, text);
}
const transaction = this.parseTransaction (response, currency);
return this.extend (transaction, {
'address': address,
});
}
async fetchPositions (symbols = undefined, params = {}) {
await this.loadMarkets ();
const response = await this.privatePostPositions (params);
//
// [
// [
// "tBTCUSD", // SYMBOL
// "ACTIVE", // STATUS
// 0.0195, // AMOUNT
// 8565.0267019, // BASE_PRICE
// 0, // MARGIN_FUNDING
// 0, // MARGIN_FUNDING_TYPE
// -0.33455568705000516, // PL
// -0.0003117550117425625, // PL_PERC
// 7045.876419249083, // PRICE_LIQ
// 3.0673001895895604, // LEVERAGE
// null, // _PLACEHOLDER
// 142355652, // POSITION_ID
// 1574002216000, // MTS_CREATE
// 1574002216000, // MTS_UPDATE
// null, // _PLACEHOLDER
// 0, // TYPE
// null, // _PLACEHOLDER
// 0, // COLLATERAL
// 0, // COLLATERAL_MIN
// // META
// {
// "reason":"TRADE",
// "order_id":34271018124,
// "liq_stage":null,
// "trade_price":"8565.0267019",
// "trade_amount":"0.0195",
// "order_id_oppo":34277498022
// }
// ]
// ]
//
// todo unify parsePosition/parsePositions
return response;
}
nonce () {
return this.milliseconds ();
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let request = '/' + this.implodeParams (path, params);
const query = this.omit (params, this.extractParams (path));
if (api === 'v1') {
request = api + request;
} else {
request = this.version + request;
}
let url = this.urls['api'][api] + '/' + request;
if (api === 'public') {
if (Object.keys (query).length) {
url += '?' + this.urlencode (query);
}
}
if (api === 'private') {
this.checkRequiredCredentials ();
const nonce = this.nonce ().toString ();
body = this.json (query);
const auth = '/api/' + request + nonce + body;
const signature = this.hmac (this.encode (auth), this.encode (this.secret), 'sha384');
headers = {
'bfx-nonce': nonce,
'bfx-apikey': this.apiKey,
'bfx-signature': signature,
'Content-Type': 'application/json',
};
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
handleErrors (statusCode, statusText, url, method, responseHeaders, responseBody, response, requestHeaders, requestBody) {
if (response !== undefined) {
if (!Array.isArray (response)) {
const message = this.safeString2 (response, 'message', 'error');
const feedback = this.id + ' ' + responseBody;
this.throwExactlyMatchedException (this.exceptions['exact'], message, feedback);
this.throwBroadlyMatchedException (this.exceptions['broad'], message, feedback);
throw new ExchangeError (this.id + ' ' + responseBody);
}
} else if (response === '') {
throw new ExchangeError (this.id + ' returned empty response');
}
if (statusCode === 500) {
// See https://docs.bitfinex.com/docs/abbreviations-glossary#section-errorinfo-codes
const errorCode = this.numberToString (response[1]);
const errorText = response[2];
const feedback = this.id + ' ' + errorText;
this.throwExactlyMatchedException (this.exceptions['exact'], errorCode, feedback);
this.throwExactlyMatchedException (this.exceptions['exact'], errorText, feedback);
this.throwBroadlyMatchedException (this.exceptions['broad'], errorText, feedback);
throw new ExchangeError (this.id + ' ' + errorText + ' (#' + errorCode + ')');
}
return response;
}
parseLedgerEntryType (type) {
if (type === undefined) {
return undefined;
} else if (type.indexOf ('fee') >= 0 || type.indexOf ('charged') >= 0) {
return 'fee';
} else if (type.indexOf ('exchange') >= 0 || type.indexOf ('position') >= 0) {
return 'trade';
} else if (type.indexOf ('rebate') >= 0) {
return 'rebate';
} else if (type.indexOf ('deposit') >= 0 || type.indexOf ('withdrawal') >= 0) {
return 'transaction';
} else if (type.indexOf ('transfer') >= 0) {
return 'transfer';
} else if (type.indexOf ('payment') >= 0) {
return 'payout';
} else {
return type;
}
}
parseLedgerEntry (item, currency = undefined) {
//
// [
// [
// 2531822314, // ID: Ledger identifier
// "USD", // CURRENCY: The symbol of the currency (ex. "BTC")
// null, // PLACEHOLDER
// 1573521810000, // MTS: Timestamp in milliseconds
// null, // PLACEHOLDER
// 0.01644445, // AMOUNT: Amount of funds moved
// 0, // BALANCE: New balance
// null, // PLACEHOLDER
// "Settlement @ 185.79 on wallet margin" // DESCRIPTION: Description of ledger transaction
// ]
// ]
//
let type = undefined;
const id = this.safeString (item, 0);
const currencyId = this.safeString (item, 1);
const code = this.safeCurrencyCode (currencyId, currency);
const timestamp = this.safeInteger (item, 3);
const amount = this.safeNumber (item, 5);
const after = this.safeNumber (item, 6);
const description = this.safeString (item, 8);
if (description !== undefined) {
const parts = description.split (' @ ');
const first = this.safeStringLower (parts, 0);
type = this.parseLedgerEntryType (first);
}
return {
'id': id,
'direction': undefined,
'account': undefined,
'referenceId': id,
'referenceAccount': undefined,
'type': type,
'currency': code,
'amount': amount,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'before': undefined,
'after': after,
'status': undefined,
'fee': undefined,
'info': item,
};
}
async fetchLedger (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
await this.loadMarkets ();
let currency = undefined;
const request = {};
let method = 'privatePostAuthRLedgersHist';
if (code !== undefined) {
currency = this.currency (code);
request['currency'] = currency['uppercaseId'];
method = 'privatePostAuthRLedgersCurrencyHist';
}
if (since !== undefined) {
request['start'] = since;
}
if (limit !== undefined) {
request['limit'] = limit; // max 2500
}
const response = await this[method] (this.extend (request, params));
//
// [
// [
// 2531822314, // ID: Ledger identifier
// "USD", // CURRENCY: The symbol of the currency (ex. "BTC")
// null, // PLACEHOLDER
// 1573521810000, // MTS: Timestamp in milliseconds
// null, // PLACEHOLDER
// 0.01644445, // AMOUNT: Amount of funds moved
// 0, // BALANCE: New balance
// null, // PLACEHOLDER
// "Settlement @ 185.79 on wallet margin" // DESCRIPTION: Description of ledger transaction
// ]
// ]
//
return this.parseLedger (response, currency, since, limit);
}
};
|
const router = require('express').Router();
const Workout = require('../models/workout');
//`GET /api/workouts` sends an array of all workouts.
router.get('/api/workouts', function(req, res) {
Workout.find({}).then(function(workouts) {
res.json(workouts);
})
});
//* `PUT /api/workouts/:id`appends the request body to the`exercises` array of the identified workout, then sends the updated workout.
router.put('/api/workouts/:id', function(req, res) {
Workout.findOne({ _id: req.params.id }).then(function(workout) {
workout.exercises.push(req.body);
Workout.findOneAndUpdate({ _id: req.params.id }, { exercises: workout.exercises }, (err, doc, op) => {
if (err) throw new err;
});
res.json(workout);
})
});
// * `POST /api/workouts/` adds a new workout and sends it. New workouts have no exercises, and their `day` field is set to the current time.
router.post('/api/workouts', function(req, res) {
Workout.create({}, function(err, newWorkout) {
if (err) throw new err;
res.json(newWorkout)
})
});
//* `GET /api/workouts/range` sends an array of the 7 most recent workouts.
router.get('/api/workouts/range', function(req, res) {
Workout.find({}).sort({day: 1}).limit(7)
.then(function(workouts) {
res.json(workouts);
})
});
//* `GET /exercise/` and`GET /stats/` serve`public/exercise.html` and`public/stats.html`, respectively.(And`public` as a whole is served as the static file directory.)
module.exports = router;
|
(function($){
$(document).ready(function(){
$('#footer-form').submit(function (e) {
e.preventDefault();
var data = {
name : $('#name2').val(),
email : $('#email2').val(),
message : $('#message2').val(),
};
$.ajax({
url : '//api.hurtigtechnologies.com/mail/send.php',
method : 'POST',
data : data,
success : function (msg) {
var json = JSON.parse(msg);
if (json.status == 'success') {
$('#name2').val('');
$('#email2').val('');
$('#message2').val('');
$('#footer-form-success').html(json.message).fadeIn();
} else {
$('#footer-form-error').html(json.message).fadeIn();
}
},
error : function () {
$('#footer-form-error').fadeIn();
}
});
});
$('#footer-form input, #footer-form textarea').focus(function () {
$('.alert').fadeOut();
})
});
})(this.jQuery);
|
import React from "react";
export default class Layout extends React.Component {
render() {
return (
<div>Layout here</div>
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.