text
stringlengths
2
1.05M
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * Setup handlers for the minimize and close topbar buttons. */ function initializeHandlers() { $('minimize-button').addEventListener('click', function(e) { e.preventDefault(); chrome.app.window.current().minimize(); }); $('minimize-button').addEventListener('mousedown', function(e) { e.preventDefault(); }); $('close-button').addEventListener('click', function() { window.close(); }); $('close-button').addEventListener('mousedown', function(e) { e.preventDefault(); }); } window.addEventListener('DOMContentLoaded', initializeHandlers);
import chai from 'chai'; import chaitHttp from 'chai-http'; import { app } from '../../index'; import initialize from '../../db/initialize'; import truncate from '../../db/truncate'; const { expect } = chai; chai.use(chaitHttp); describe('Testing author endpoints', () => { before(done => { (async () => { await initialize(); done(); })(); }); // after(done => { // (async () => { // await truncate('author'); // done(); // })(); // }); it('It should create an author', done => { const author = { name: 'author one', }; chai .request(app) .post('/api/author') .set('Accept', 'application/json') .send(author) .end((err, res) => { expect(res.status).to.equal(201); expect(res.body.data).to.include({ name: author.name, }); done(); }); }); it('It should not create an author with empty parameters', done => { const author = {}; chai .request(app) .post('/api/author') .set('Accept', 'application/json') .send(author) .end((err, res) => { expect(res.status).to.equal(400); res.body.should.have .property('message') .eql('some details are missing'); done(); }); }); it('It should get all authors', done => { chai .request(app) .get('/api/author') .set('Accept', 'application/json') .end((err, res) => { expect(res.status).to.equal(200); res.body.data[0].should.have.property('id'); res.body.data[0].should.have.property('name'); done(); }); }); it('It should get a particular author', done => { const authorId = 1; chai .request(app) .get(`/api/author/${authorId}`) .set('Accept', 'application/json') .end((err, res) => { expect(res.status).to.equal(200); res.body.data.should.have.property('id'); res.body.data.should.have.property('name'); res.body.data.should.have.property('books'); done(); }); }); it('It should not get a particular author with invalid id', done => { const authorId = 456789; chai .request(app) .get(`/api/author/${authorId}`) .set('Accept', 'application/json') .end((err, res) => { expect(res.status).to.equal(404); res.body.should.have .property('message') .eql(`cannot find author with the id ${authorId}`); done(); }); }); it('It should not get a particular author with non-numeric id', done => { const authorId = 'test'; chai .request(app) .get(`/api/author/${authorId}`) .set('Accept', 'application/json') .end((err, res) => { expect(res.status).to.equal(400); res.body.should.have .property('message') .eql('please provide a valid numeric value'); done(); }); }); it('It should update an author', done => { const authorId = 2; const updatedAuthor = { name: 'author two updated', }; chai .request(app) .put(`/api/author/${authorId}`) .set('Accept', 'application/json') .send(updatedAuthor) .end((err, res) => { expect(res.status).to.equal(200); expect(res.body.data.id).equal(updatedAuthor.id); expect(res.body.data.name).equal(updatedAuthor.name); done(); }); }); it('It should update an author books', done => { const authorId = 2; const updatedAuthor = { books: [1, 2], }; chai .request(app) .put(`/api/author/${authorId}/book`) .set('Accept', 'application/json') .send(updatedAuthor) .end((err, res) => { expect(res.status).to.equal(200); expect(res.body.data.books) .to.be.an('array') .that.does.not.include(3); expect(res.body.data.books).to.eql(updatedAuthor.books); done(); }); }); it('It should not update an author with invalid id', done => { const authorId = '567890'; const updatedAuthor = { name: 'author updated', }; chai .request(app) .put(`/api/author/${authorId}`) .set('Accept', 'application/json') .send(updatedAuthor) .end((err, res) => { expect(res.status).to.equal(404); res.body.should.have .property('message') .eql(`cannot find author with the id: ${authorId}`); done(); }); }); it('It should not update an author with non-numeric id value', done => { const authorId = 'test'; const updatedAuthor = { name: 'author updated', }; chai .request(app) .put(`/api/author/${authorId}`) .set('Accept', 'application/json') .send(updatedAuthor) .end((err, res) => { expect(res.status).to.equal(400); res.body.should.have .property('message') .eql('please provide a valid numeric value'); done(); }); }); it('It should delete an author', done => { const authorId = 2; chai .request(app) .delete(`/api/author/${authorId}`) .set('Accept', 'application/json') .end((err, res) => { expect(res.status).to.equal(200); expect(res.body.data).to.include({}); done(); }); }); it('It should not delete and author with invalid id', done => { const authorId = 87667; chai .request(app) .delete(`/api/author/${authorId}`) .set('Accept', 'application/json') .end((err, res) => { expect(res.status).to.equal(404); res.body.should.have .property('message') .eql(`author with the id ${authorId} cannot be found`); done(); }); }); });
module.exports=function(e,t){"use strict";var r={};function __webpack_require__(t){if(r[t]){return r[t].exports}var n=r[t]={i:t,l:false,exports:{}};var i=true;try{e[t].call(n.exports,n,n.exports,__webpack_require__);i=false}finally{if(i)delete r[t]}n.l=true;return n.exports}__webpack_require__.ab=__dirname+"/";function startup(){return __webpack_require__(131)}return startup()}({1:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r(function(t){t(e)})}return new(r||(r=Promise))(function(r,i){function fulfilled(e){try{step(n.next(e))}catch(e){i(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){i(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:true});const i=r(129);const o=r(622);const s=r(669);const a=r(672);const c=s.promisify(i.exec);function cp(e,t,r={}){return n(this,void 0,void 0,function*(){const{force:n,recursive:i}=readCopyOptions(r);const s=(yield a.exists(t))?yield a.stat(t):null;if(s&&s.isFile()&&!n){return}const c=s&&s.isDirectory()?o.join(t,o.basename(e)):t;if(!(yield a.exists(e))){throw new Error(`no such file or directory: ${e}`)}const u=yield a.stat(e);if(u.isDirectory()){if(!i){throw new Error(`Failed to copy. ${e} is a directory, but tried to copy without recursive flag.`)}else{yield cpDirRecursive(e,c,0,n)}}else{if(o.relative(e,c)===""){throw new Error(`'${c}' and '${e}' are the same file`)}yield copyFile(e,c,n)}})}t.cp=cp;function mv(e,t,r={}){return n(this,void 0,void 0,function*(){if(yield a.exists(t)){let n=true;if(yield a.isDirectory(t)){t=o.join(t,o.basename(e));n=yield a.exists(t)}if(n){if(r.force==null||r.force){yield rmRF(t)}else{throw new Error("Destination already exists")}}}yield mkdirP(o.dirname(t));yield a.rename(e,t)})}t.mv=mv;function rmRF(e){return n(this,void 0,void 0,function*(){if(a.IS_WINDOWS){try{if(yield a.isDirectory(e,true)){yield c(`rd /s /q "${e}"`)}else{yield c(`del /f /a "${e}"`)}}catch(e){if(e.code!=="ENOENT")throw e}try{yield a.unlink(e)}catch(e){if(e.code!=="ENOENT")throw e}}else{let t=false;try{t=yield a.isDirectory(e)}catch(e){if(e.code!=="ENOENT")throw e;return}if(t){yield c(`rm -rf "${e}"`)}else{yield a.unlink(e)}}})}t.rmRF=rmRF;function mkdirP(e){return n(this,void 0,void 0,function*(){yield a.mkdirP(e)})}t.mkdirP=mkdirP;function which(e,t){return n(this,void 0,void 0,function*(){if(!e){throw new Error("parameter 'tool' is required")}if(t){const t=yield which(e,false);if(!t){if(a.IS_WINDOWS){throw new Error(`Unable to locate executable file: ${e}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`)}else{throw new Error(`Unable to locate executable file: ${e}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`)}}}try{const t=[];if(a.IS_WINDOWS&&process.env.PATHEXT){for(const e of process.env.PATHEXT.split(o.delimiter)){if(e){t.push(e)}}}if(a.isRooted(e)){const r=yield a.tryGetExecutablePath(e,t);if(r){return r}return""}if(e.includes("/")||a.IS_WINDOWS&&e.includes("\\")){return""}const r=[];if(process.env.PATH){for(const e of process.env.PATH.split(o.delimiter)){if(e){r.push(e)}}}for(const n of r){const r=yield a.tryGetExecutablePath(n+o.sep+e,t);if(r){return r}}return""}catch(e){throw new Error(`which failed with message ${e.message}`)}})}t.which=which;function readCopyOptions(e){const t=e.force==null?true:e.force;const r=Boolean(e.recursive);return{force:t,recursive:r}}function cpDirRecursive(e,t,r,i){return n(this,void 0,void 0,function*(){if(r>=255)return;r++;yield mkdirP(t);const n=yield a.readdir(e);for(const o of n){const n=`${e}/${o}`;const s=`${t}/${o}`;const c=yield a.lstat(n);if(c.isDirectory()){yield cpDirRecursive(n,s,r,i)}else{yield copyFile(n,s,i)}}yield a.chmod(t,(yield a.stat(e)).mode)})}function copyFile(e,t,r){return n(this,void 0,void 0,function*(){if((yield a.lstat(e)).isSymbolicLink()){try{yield a.lstat(t);yield a.unlink(t)}catch(e){if(e.code==="EPERM"){yield a.chmod(t,"0666");yield a.unlink(t)}}const r=yield a.readlink(e);yield a.symlink(r,t,a.IS_WINDOWS?"junction":null)}else if(!(yield a.exists(t))||r){yield a.copyFile(e,t)}})}},9:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r(function(t){t(e)})}return new(r||(r=Promise))(function(r,i){function fulfilled(e){try{step(n.next(e))}catch(e){i(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){i(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())})};var i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(Object.hasOwnProperty.call(e,r))t[r]=e[r];t["default"]=e;return t};Object.defineProperty(t,"__esModule",{value:true});const o=i(r(87));const s=i(r(614));const a=i(r(129));const c=i(r(622));const u=i(r(1));const l=i(r(672));const f=process.platform==="win32";class ToolRunner extends s.EventEmitter{constructor(e,t,r){super();if(!e){throw new Error("Parameter 'toolPath' cannot be null or empty.")}this.toolPath=e;this.args=t||[];this.options=r||{}}_debug(e){if(this.options.listeners&&this.options.listeners.debug){this.options.listeners.debug(e)}}_getCommandString(e,t){const r=this._getSpawnFileName();const n=this._getSpawnArgs(e);let i=t?"":"[command]";if(f){if(this._isCmdFile()){i+=r;for(const e of n){i+=` ${e}`}}else if(e.windowsVerbatimArguments){i+=`"${r}"`;for(const e of n){i+=` ${e}`}}else{i+=this._windowsQuoteCmdArg(r);for(const e of n){i+=` ${this._windowsQuoteCmdArg(e)}`}}}else{i+=r;for(const e of n){i+=` ${e}`}}return i}_processLineBuffer(e,t,r){try{let n=t+e.toString();let i=n.indexOf(o.EOL);while(i>-1){const e=n.substring(0,i);r(e);n=n.substring(i+o.EOL.length);i=n.indexOf(o.EOL)}t=n}catch(e){this._debug(`error processing line. Failed with error ${e}`)}}_getSpawnFileName(){if(f){if(this._isCmdFile()){return process.env["COMSPEC"]||"cmd.exe"}}return this.toolPath}_getSpawnArgs(e){if(f){if(this._isCmdFile()){let t=`/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`;for(const r of this.args){t+=" ";t+=e.windowsVerbatimArguments?r:this._windowsQuoteCmdArg(r)}t+='"';return[t]}}return this.args}_endsWith(e,t){return e.endsWith(t)}_isCmdFile(){const e=this.toolPath.toUpperCase();return this._endsWith(e,".CMD")||this._endsWith(e,".BAT")}_windowsQuoteCmdArg(e){if(!this._isCmdFile()){return this._uvQuoteCmdArg(e)}if(!e){return'""'}const t=[" ","\t","&","(",")","[","]","{","}","^","=",";","!","'","+",",","`","~","|","<",">",'"'];let r=false;for(const n of e){if(t.some(e=>e===n)){r=true;break}}if(!r){return e}let n='"';let i=true;for(let t=e.length;t>0;t--){n+=e[t-1];if(i&&e[t-1]==="\\"){n+="\\"}else if(e[t-1]==='"'){i=true;n+='"'}else{i=false}}n+='"';return n.split("").reverse().join("")}_uvQuoteCmdArg(e){if(!e){return'""'}if(!e.includes(" ")&&!e.includes("\t")&&!e.includes('"')){return e}if(!e.includes('"')&&!e.includes("\\")){return`"${e}"`}let t='"';let r=true;for(let n=e.length;n>0;n--){t+=e[n-1];if(r&&e[n-1]==="\\"){t+="\\"}else if(e[n-1]==='"'){r=true;t+="\\"}else{r=false}}t+='"';return t.split("").reverse().join("")}_cloneExecOptions(e){e=e||{};const t={cwd:e.cwd||process.cwd(),env:e.env||process.env,silent:e.silent||false,windowsVerbatimArguments:e.windowsVerbatimArguments||false,failOnStdErr:e.failOnStdErr||false,ignoreReturnCode:e.ignoreReturnCode||false,delay:e.delay||1e4};t.outStream=e.outStream||process.stdout;t.errStream=e.errStream||process.stderr;return t}_getSpawnOptions(e,t){e=e||{};const r={};r.cwd=e.cwd;r.env=e.env;r["windowsVerbatimArguments"]=e.windowsVerbatimArguments||this._isCmdFile();if(e.windowsVerbatimArguments){r.argv0=`"${t}"`}return r}exec(){return n(this,void 0,void 0,function*(){if(!l.isRooted(this.toolPath)&&(this.toolPath.includes("/")||f&&this.toolPath.includes("\\"))){this.toolPath=c.resolve(process.cwd(),this.options.cwd||process.cwd(),this.toolPath)}this.toolPath=yield u.which(this.toolPath,true);return new Promise((e,t)=>{this._debug(`exec tool: ${this.toolPath}`);this._debug("arguments:");for(const e of this.args){this._debug(` ${e}`)}const r=this._cloneExecOptions(this.options);if(!r.silent&&r.outStream){r.outStream.write(this._getCommandString(r)+o.EOL)}const n=new ExecState(r,this.toolPath);n.on("debug",e=>{this._debug(e)});const i=this._getSpawnFileName();const s=a.spawn(i,this._getSpawnArgs(r),this._getSpawnOptions(this.options,i));const c="";if(s.stdout){s.stdout.on("data",e=>{if(this.options.listeners&&this.options.listeners.stdout){this.options.listeners.stdout(e)}if(!r.silent&&r.outStream){r.outStream.write(e)}this._processLineBuffer(e,c,e=>{if(this.options.listeners&&this.options.listeners.stdline){this.options.listeners.stdline(e)}})})}const u="";if(s.stderr){s.stderr.on("data",e=>{n.processStderr=true;if(this.options.listeners&&this.options.listeners.stderr){this.options.listeners.stderr(e)}if(!r.silent&&r.errStream&&r.outStream){const t=r.failOnStdErr?r.errStream:r.outStream;t.write(e)}this._processLineBuffer(e,u,e=>{if(this.options.listeners&&this.options.listeners.errline){this.options.listeners.errline(e)}})})}s.on("error",e=>{n.processError=e.message;n.processExited=true;n.processClosed=true;n.CheckComplete()});s.on("exit",e=>{n.processExitCode=e;n.processExited=true;this._debug(`Exit code ${e} received from tool '${this.toolPath}'`);n.CheckComplete()});s.on("close",e=>{n.processExitCode=e;n.processExited=true;n.processClosed=true;this._debug(`STDIO streams have closed for tool '${this.toolPath}'`);n.CheckComplete()});n.on("done",(r,n)=>{if(c.length>0){this.emit("stdline",c)}if(u.length>0){this.emit("errline",u)}s.removeAllListeners();if(r){t(r)}else{e(n)}});if(this.options.input){if(!s.stdin){throw new Error("child process missing stdin")}s.stdin.end(this.options.input)}})})}}t.ToolRunner=ToolRunner;function argStringToArray(e){const t=[];let r=false;let n=false;let i="";function append(e){if(n&&e!=='"'){i+="\\"}i+=e;n=false}for(let o=0;o<e.length;o++){const s=e.charAt(o);if(s==='"'){if(!n){r=!r}else{append(s)}continue}if(s==="\\"&&n){append(s);continue}if(s==="\\"&&r){n=true;continue}if(s===" "&&!r){if(i.length>0){t.push(i);i=""}continue}append(s)}if(i.length>0){t.push(i.trim())}return t}t.argStringToArray=argStringToArray;class ExecState extends s.EventEmitter{constructor(e,t){super();this.processClosed=false;this.processError="";this.processExitCode=0;this.processExited=false;this.processStderr=false;this.delay=1e4;this.done=false;this.timeout=null;if(!t){throw new Error("toolPath must not be empty")}this.options=e;this.toolPath=t;if(e.delay){this.delay=e.delay}}CheckComplete(){if(this.done){return}if(this.processClosed){this._setResult()}else if(this.processExited){this.timeout=setTimeout(ExecState.HandleTimeout,this.delay,this)}}_debug(e){this.emit("debug",e)}_setResult(){let e;if(this.processExited){if(this.processError){e=new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`)}else if(this.processExitCode!==0&&!this.options.ignoreReturnCode){e=new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`)}else if(this.processStderr&&this.options.failOnStdErr){e=new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`)}}if(this.timeout){clearTimeout(this.timeout);this.timeout=null}this.done=true;this.emit("done",e,this.processExitCode)}static HandleTimeout(e){if(e.done){return}if(!e.processClosed&&e.processExited){const t=`The STDIO streams did not close within ${e.delay/1e3} seconds of the exit event from process '${e.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`;e._debug(t)}e._setResult()}}},16:function(e){e.exports=require("tls")},31:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r(function(t){t(e)})}return new(r||(r=Promise))(function(r,i){function fulfilled(e){try{step(n.next(e))}catch(e){i(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){i(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())})};var i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(Object.hasOwnProperty.call(e,r))t[r]=e[r];t["default"]=e;return t};Object.defineProperty(t,"__esModule",{value:true});const o=i(r(280));const s=r(470);const a=r(87);const c=r(129);const u=r(747);function _findMatch(t,r,i,c){return n(this,void 0,void 0,function*(){const n=a.platform();let u;let l;let f;for(const a of i){const i=a.version;s.debug(`check ${i} satisfies ${t}`);if(o.satisfies(i,t)&&(!r||a.stable===r)){f=a.files.find(t=>{s.debug(`${t.arch}===${c} && ${t.platform}===${n}`);let r=t.arch===c&&t.platform===n;if(r&&t.platform_version){const n=e.exports._getOsVersion();if(n===t.platform_version){r=true}else{r=o.satisfies(n,t.platform_version)}}return r});if(f){s.debug(`matched ${a.version}`);l=a;break}}}if(l&&f){u=Object.assign({},l);u.files=[f]}return u})}t._findMatch=_findMatch;function _getOsVersion(){const t=a.platform();let r="";if(t==="darwin"){r=c.execSync("sw_vers -productVersion").toString()}else if(t==="linux"){const t=e.exports._readLinuxVersionFile();if(t){const e=t.split("\n");for(const t of e){const e=t.split("=");if(e.length===2&&e[0].trim()==="DISTRIB_RELEASE"){r=e[1].trim();break}}}}return r}t._getOsVersion=_getOsVersion;function _readLinuxVersionFile(){const e="/etc/lsb-release";let t="";if(u.existsSync(e)){t=u.readFileSync(e).toString()}return t}t._readLinuxVersionFile=_readLinuxVersionFile},82:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:true});function toCommandValue(e){if(e===null||e===undefined){return""}else if(typeof e==="string"||e instanceof String){return e}return JSON.stringify(e)}t.toCommandValue=toCommandValue},87:function(e){e.exports=require("os")},102:function(e,t,r){"use strict";var n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(Object.hasOwnProperty.call(e,r))t[r]=e[r];t["default"]=e;return t};Object.defineProperty(t,"__esModule",{value:true});const i=n(r(747));const o=n(r(87));const s=r(82);function issueCommand(e,t){const r=process.env[`GITHUB_${e}`];if(!r){throw new Error(`Unable to find environment variable for file command ${e}`)}if(!i.existsSync(r)){throw new Error(`Missing file at path: ${r}`)}i.appendFileSync(r,`${s.toCommandValue(t)}${o.EOL}`,{encoding:"utf8"})}t.issueCommand=issueCommand},129:function(e){e.exports=require("child_process")},131:function(__unusedmodule,exports,__webpack_require__){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,r,n){if(n===undefined)n=r;Object.defineProperty(e,n,{enumerable:true,get:function(){return t[r]}})}:function(e,t,r,n){if(n===undefined)n=r;e[n]=t[r]});var __setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e["default"]=t});var __importStar=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(r!=="default"&&Object.hasOwnProperty.call(e,r))__createBinding(t,e,r);__setModuleDefault(t,e);return t};var __awaiter=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r(function(t){t(e)})}return new(r||(r=Promise))(function(r,i){function fulfilled(e){try{step(n.next(e))}catch(e){i(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){i(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())})};Object.defineProperty(exports,"__esModule",{value:true});exports.fileName=exports.downloadUrl=exports.install=void 0;const core_1=__webpack_require__(470);const tc=__importStar(__webpack_require__(533));const http=__importStar(__webpack_require__(539));const os=__importStar(__webpack_require__(87));const fs=__importStar(__webpack_require__(747));const TOOL="aws-copilot";function install(e,t){return __awaiter(this,void 0,void 0,function*(){const r=tc.find(TOOL,e)||(yield download(e,t));core_1.addPath(r)})}exports.install=install;function downloadUrl(e,t){return`https://github.com/aws/copilot-cli/releases/download/${e}/${fileName(e,t)}`}exports.downloadUrl=downloadUrl;function download(e,t){return __awaiter(this,void 0,void 0,function*(){const r=downloadUrl(e,t);core_1.info(`Downloading ${r}`);const n=yield tc.downloadTool(r);fs.chmodSync(n,"777");return yield tc.cacheFile(n,"copilot",TOOL,e)})}function fileName(e,t){const r=t==="win32"?"windows":t;const n=t==="win32"?".exe":"";return`copilot-${r}-${e}${n}`}exports.fileName=fileName;function run(){return __awaiter(this,void 0,void 0,function*(){try{const e=core_1.getInput("version")||(yield latestVersion());if(!e){throw new Error("Failed to resolve latest version")}yield install(e,os.platform())}catch(e){core_1.setFailed(e.message)}})}function latestVersion(){return __awaiter(this,void 0,void 0,function*(){const e=`https://api.github.com/repos/aws/copilot-cli/releases/latest`;const t=new http.HttpClient("setup-aws-copilot");const r=(yield t.getJson(e)).result;return r===null||r===void 0?void 0:r.tag_name})}if(require.main===require.cache[eval("__filename")]){run()}},139:function(e,t,r){var n=r(417);e.exports=function nodeRNG(){return n.randomBytes(16)}},141:function(e,t,r){"use strict";var n=r(631);var i=r(16);var o=r(605);var s=r(211);var a=r(614);var c=r(357);var u=r(669);t.httpOverHttp=httpOverHttp;t.httpsOverHttp=httpsOverHttp;t.httpOverHttps=httpOverHttps;t.httpsOverHttps=httpsOverHttps;function httpOverHttp(e){var t=new TunnelingAgent(e);t.request=o.request;return t}function httpsOverHttp(e){var t=new TunnelingAgent(e);t.request=o.request;t.createSocket=createSecureSocket;t.defaultPort=443;return t}function httpOverHttps(e){var t=new TunnelingAgent(e);t.request=s.request;return t}function httpsOverHttps(e){var t=new TunnelingAgent(e);t.request=s.request;t.createSocket=createSecureSocket;t.defaultPort=443;return t}function TunnelingAgent(e){var t=this;t.options=e||{};t.proxyOptions=t.options.proxy||{};t.maxSockets=t.options.maxSockets||o.Agent.defaultMaxSockets;t.requests=[];t.sockets=[];t.on("free",function onFree(e,r,n,i){var o=toOptions(r,n,i);for(var s=0,a=t.requests.length;s<a;++s){var c=t.requests[s];if(c.host===o.host&&c.port===o.port){t.requests.splice(s,1);c.request.onSocket(e);return}}e.destroy();t.removeSocket(e)})}u.inherits(TunnelingAgent,a.EventEmitter);TunnelingAgent.prototype.addRequest=function addRequest(e,t,r,n){var i=this;var o=mergeOptions({request:e},i.options,toOptions(t,r,n));if(i.sockets.length>=this.maxSockets){i.requests.push(o);return}i.createSocket(o,function(t){t.on("free",onFree);t.on("close",onCloseOrRemove);t.on("agentRemove",onCloseOrRemove);e.onSocket(t);function onFree(){i.emit("free",t,o)}function onCloseOrRemove(e){i.removeSocket(t);t.removeListener("free",onFree);t.removeListener("close",onCloseOrRemove);t.removeListener("agentRemove",onCloseOrRemove)}})};TunnelingAgent.prototype.createSocket=function createSocket(e,t){var r=this;var n={};r.sockets.push(n);var i=mergeOptions({},r.proxyOptions,{method:"CONNECT",path:e.host+":"+e.port,agent:false,headers:{host:e.host+":"+e.port}});if(e.localAddress){i.localAddress=e.localAddress}if(i.proxyAuth){i.headers=i.headers||{};i.headers["Proxy-Authorization"]="Basic "+new Buffer(i.proxyAuth).toString("base64")}l("making CONNECT request");var o=r.request(i);o.useChunkedEncodingByDefault=false;o.once("response",onResponse);o.once("upgrade",onUpgrade);o.once("connect",onConnect);o.once("error",onError);o.end();function onResponse(e){e.upgrade=true}function onUpgrade(e,t,r){process.nextTick(function(){onConnect(e,t,r)})}function onConnect(i,s,a){o.removeAllListeners();s.removeAllListeners();if(i.statusCode!==200){l("tunneling socket could not be established, statusCode=%d",i.statusCode);s.destroy();var c=new Error("tunneling socket could not be established, "+"statusCode="+i.statusCode);c.code="ECONNRESET";e.request.emit("error",c);r.removeSocket(n);return}if(a.length>0){l("got illegal response body from proxy");s.destroy();var c=new Error("got illegal response body from proxy");c.code="ECONNRESET";e.request.emit("error",c);r.removeSocket(n);return}l("tunneling connection has established");r.sockets[r.sockets.indexOf(n)]=s;return t(s)}function onError(t){o.removeAllListeners();l("tunneling socket could not be established, cause=%s\n",t.message,t.stack);var i=new Error("tunneling socket could not be established, "+"cause="+t.message);i.code="ECONNRESET";e.request.emit("error",i);r.removeSocket(n)}};TunnelingAgent.prototype.removeSocket=function removeSocket(e){var t=this.sockets.indexOf(e);if(t===-1){return}this.sockets.splice(t,1);var r=this.requests.shift();if(r){this.createSocket(r,function(e){r.request.onSocket(e)})}};function createSecureSocket(e,t){var r=this;TunnelingAgent.prototype.createSocket.call(r,e,function(n){var o=e.request.getHeader("host");var s=mergeOptions({},r.options,{socket:n,servername:o?o.replace(/:.*$/,""):e.host});var a=i.connect(0,s);r.sockets[r.sockets.indexOf(n)]=a;t(a)})}function toOptions(e,t,r){if(typeof e==="string"){return{host:e,port:t,localAddress:r}}return e}function mergeOptions(e){for(var t=1,r=arguments.length;t<r;++t){var n=arguments[t];if(typeof n==="object"){var i=Object.keys(n);for(var o=0,s=i.length;o<s;++o){var a=i[o];if(n[a]!==undefined){e[a]=n[a]}}}}return e}var l;if(process.env.NODE_DEBUG&&/\btunnel\b/.test(process.env.NODE_DEBUG)){l=function(){var e=Array.prototype.slice.call(arguments);if(typeof e[0]==="string"){e[0]="TUNNEL: "+e[0]}else{e.unshift("TUNNEL:")}console.error.apply(console,e)}}else{l=function(){}}t.debug=l},211:function(e){e.exports=require("https")},280:function(e,t){t=e.exports=SemVer;var r;if(typeof process==="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)){r=function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER");console.log.apply(console,e)}}else{r=function(){}}t.SEMVER_SPEC_VERSION="2.0.0";var n=256;var i=Number.MAX_SAFE_INTEGER||9007199254740991;var o=16;var s=t.re=[];var a=t.src=[];var c=t.tokens={};var u=0;function tok(e){c[e]=u++}tok("NUMERICIDENTIFIER");a[c.NUMERICIDENTIFIER]="0|[1-9]\\d*";tok("NUMERICIDENTIFIERLOOSE");a[c.NUMERICIDENTIFIERLOOSE]="[0-9]+";tok("NONNUMERICIDENTIFIER");a[c.NONNUMERICIDENTIFIER]="\\d*[a-zA-Z-][a-zA-Z0-9-]*";tok("MAINVERSION");a[c.MAINVERSION]="("+a[c.NUMERICIDENTIFIER]+")\\."+"("+a[c.NUMERICIDENTIFIER]+")\\."+"("+a[c.NUMERICIDENTIFIER]+")";tok("MAINVERSIONLOOSE");a[c.MAINVERSIONLOOSE]="("+a[c.NUMERICIDENTIFIERLOOSE]+")\\."+"("+a[c.NUMERICIDENTIFIERLOOSE]+")\\."+"("+a[c.NUMERICIDENTIFIERLOOSE]+")";tok("PRERELEASEIDENTIFIER");a[c.PRERELEASEIDENTIFIER]="(?:"+a[c.NUMERICIDENTIFIER]+"|"+a[c.NONNUMERICIDENTIFIER]+")";tok("PRERELEASEIDENTIFIERLOOSE");a[c.PRERELEASEIDENTIFIERLOOSE]="(?:"+a[c.NUMERICIDENTIFIERLOOSE]+"|"+a[c.NONNUMERICIDENTIFIER]+")";tok("PRERELEASE");a[c.PRERELEASE]="(?:-("+a[c.PRERELEASEIDENTIFIER]+"(?:\\."+a[c.PRERELEASEIDENTIFIER]+")*))";tok("PRERELEASELOOSE");a[c.PRERELEASELOOSE]="(?:-?("+a[c.PRERELEASEIDENTIFIERLOOSE]+"(?:\\."+a[c.PRERELEASEIDENTIFIERLOOSE]+")*))";tok("BUILDIDENTIFIER");a[c.BUILDIDENTIFIER]="[0-9A-Za-z-]+";tok("BUILD");a[c.BUILD]="(?:\\+("+a[c.BUILDIDENTIFIER]+"(?:\\."+a[c.BUILDIDENTIFIER]+")*))";tok("FULL");tok("FULLPLAIN");a[c.FULLPLAIN]="v?"+a[c.MAINVERSION]+a[c.PRERELEASE]+"?"+a[c.BUILD]+"?";a[c.FULL]="^"+a[c.FULLPLAIN]+"$";tok("LOOSEPLAIN");a[c.LOOSEPLAIN]="[v=\\s]*"+a[c.MAINVERSIONLOOSE]+a[c.PRERELEASELOOSE]+"?"+a[c.BUILD]+"?";tok("LOOSE");a[c.LOOSE]="^"+a[c.LOOSEPLAIN]+"$";tok("GTLT");a[c.GTLT]="((?:<|>)?=?)";tok("XRANGEIDENTIFIERLOOSE");a[c.XRANGEIDENTIFIERLOOSE]=a[c.NUMERICIDENTIFIERLOOSE]+"|x|X|\\*";tok("XRANGEIDENTIFIER");a[c.XRANGEIDENTIFIER]=a[c.NUMERICIDENTIFIER]+"|x|X|\\*";tok("XRANGEPLAIN");a[c.XRANGEPLAIN]="[v=\\s]*("+a[c.XRANGEIDENTIFIER]+")"+"(?:\\.("+a[c.XRANGEIDENTIFIER]+")"+"(?:\\.("+a[c.XRANGEIDENTIFIER]+")"+"(?:"+a[c.PRERELEASE]+")?"+a[c.BUILD]+"?"+")?)?";tok("XRANGEPLAINLOOSE");a[c.XRANGEPLAINLOOSE]="[v=\\s]*("+a[c.XRANGEIDENTIFIERLOOSE]+")"+"(?:\\.("+a[c.XRANGEIDENTIFIERLOOSE]+")"+"(?:\\.("+a[c.XRANGEIDENTIFIERLOOSE]+")"+"(?:"+a[c.PRERELEASELOOSE]+")?"+a[c.BUILD]+"?"+")?)?";tok("XRANGE");a[c.XRANGE]="^"+a[c.GTLT]+"\\s*"+a[c.XRANGEPLAIN]+"$";tok("XRANGELOOSE");a[c.XRANGELOOSE]="^"+a[c.GTLT]+"\\s*"+a[c.XRANGEPLAINLOOSE]+"$";tok("COERCE");a[c.COERCE]="(^|[^\\d])"+"(\\d{1,"+o+"})"+"(?:\\.(\\d{1,"+o+"}))?"+"(?:\\.(\\d{1,"+o+"}))?"+"(?:$|[^\\d])";tok("COERCERTL");s[c.COERCERTL]=new RegExp(a[c.COERCE],"g");tok("LONETILDE");a[c.LONETILDE]="(?:~>?)";tok("TILDETRIM");a[c.TILDETRIM]="(\\s*)"+a[c.LONETILDE]+"\\s+";s[c.TILDETRIM]=new RegExp(a[c.TILDETRIM],"g");var l="$1~";tok("TILDE");a[c.TILDE]="^"+a[c.LONETILDE]+a[c.XRANGEPLAIN]+"$";tok("TILDELOOSE");a[c.TILDELOOSE]="^"+a[c.LONETILDE]+a[c.XRANGEPLAINLOOSE]+"$";tok("LONECARET");a[c.LONECARET]="(?:\\^)";tok("CARETTRIM");a[c.CARETTRIM]="(\\s*)"+a[c.LONECARET]+"\\s+";s[c.CARETTRIM]=new RegExp(a[c.CARETTRIM],"g");var f="$1^";tok("CARET");a[c.CARET]="^"+a[c.LONECARET]+a[c.XRANGEPLAIN]+"$";tok("CARETLOOSE");a[c.CARETLOOSE]="^"+a[c.LONECARET]+a[c.XRANGEPLAINLOOSE]+"$";tok("COMPARATORLOOSE");a[c.COMPARATORLOOSE]="^"+a[c.GTLT]+"\\s*("+a[c.LOOSEPLAIN]+")$|^$";tok("COMPARATOR");a[c.COMPARATOR]="^"+a[c.GTLT]+"\\s*("+a[c.FULLPLAIN]+")$|^$";tok("COMPARATORTRIM");a[c.COMPARATORTRIM]="(\\s*)"+a[c.GTLT]+"\\s*("+a[c.LOOSEPLAIN]+"|"+a[c.XRANGEPLAIN]+")";s[c.COMPARATORTRIM]=new RegExp(a[c.COMPARATORTRIM],"g");var d="$1$2$3";tok("HYPHENRANGE");a[c.HYPHENRANGE]="^\\s*("+a[c.XRANGEPLAIN]+")"+"\\s+-\\s+"+"("+a[c.XRANGEPLAIN]+")"+"\\s*$";tok("HYPHENRANGELOOSE");a[c.HYPHENRANGELOOSE]="^\\s*("+a[c.XRANGEPLAINLOOSE]+")"+"\\s+-\\s+"+"("+a[c.XRANGEPLAINLOOSE]+")"+"\\s*$";tok("STAR");a[c.STAR]="(<|>)?=?\\s*\\*";for(var p=0;p<u;p++){r(p,a[p]);if(!s[p]){s[p]=new RegExp(a[p])}}t.parse=parse;function parse(e,t){if(!t||typeof t!=="object"){t={loose:!!t,includePrerelease:false}}if(e instanceof SemVer){return e}if(typeof e!=="string"){return null}if(e.length>n){return null}var r=t.loose?s[c.LOOSE]:s[c.FULL];if(!r.test(e)){return null}try{return new SemVer(e,t)}catch(e){return null}}t.valid=valid;function valid(e,t){var r=parse(e,t);return r?r.version:null}t.clean=clean;function clean(e,t){var r=parse(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null}t.SemVer=SemVer;function SemVer(e,t){if(!t||typeof t!=="object"){t={loose:!!t,includePrerelease:false}}if(e instanceof SemVer){if(e.loose===t.loose){return e}else{e=e.version}}else if(typeof e!=="string"){throw new TypeError("Invalid Version: "+e)}if(e.length>n){throw new TypeError("version is longer than "+n+" characters")}if(!(this instanceof SemVer)){return new SemVer(e,t)}r("SemVer",e,t);this.options=t;this.loose=!!t.loose;var o=e.trim().match(t.loose?s[c.LOOSE]:s[c.FULL]);if(!o){throw new TypeError("Invalid Version: "+e)}this.raw=e;this.major=+o[1];this.minor=+o[2];this.patch=+o[3];if(this.major>i||this.major<0){throw new TypeError("Invalid major version")}if(this.minor>i||this.minor<0){throw new TypeError("Invalid minor version")}if(this.patch>i||this.patch<0){throw new TypeError("Invalid patch version")}if(!o[4]){this.prerelease=[]}else{this.prerelease=o[4].split(".").map(function(e){if(/^[0-9]+$/.test(e)){var t=+e;if(t>=0&&t<i){return t}}return e})}this.build=o[5]?o[5].split("."):[];this.format()}SemVer.prototype.format=function(){this.version=this.major+"."+this.minor+"."+this.patch;if(this.prerelease.length){this.version+="-"+this.prerelease.join(".")}return this.version};SemVer.prototype.toString=function(){return this.version};SemVer.prototype.compare=function(e){r("SemVer.compare",this.version,this.options,e);if(!(e instanceof SemVer)){e=new SemVer(e,this.options)}return this.compareMain(e)||this.comparePre(e)};SemVer.prototype.compareMain=function(e){if(!(e instanceof SemVer)){e=new SemVer(e,this.options)}return compareIdentifiers(this.major,e.major)||compareIdentifiers(this.minor,e.minor)||compareIdentifiers(this.patch,e.patch)};SemVer.prototype.comparePre=function(e){if(!(e instanceof SemVer)){e=new SemVer(e,this.options)}if(this.prerelease.length&&!e.prerelease.length){return-1}else if(!this.prerelease.length&&e.prerelease.length){return 1}else if(!this.prerelease.length&&!e.prerelease.length){return 0}var t=0;do{var n=this.prerelease[t];var i=e.prerelease[t];r("prerelease compare",t,n,i);if(n===undefined&&i===undefined){return 0}else if(i===undefined){return 1}else if(n===undefined){return-1}else if(n===i){continue}else{return compareIdentifiers(n,i)}}while(++t)};SemVer.prototype.compareBuild=function(e){if(!(e instanceof SemVer)){e=new SemVer(e,this.options)}var t=0;do{var n=this.build[t];var i=e.build[t];r("prerelease compare",t,n,i);if(n===undefined&&i===undefined){return 0}else if(i===undefined){return 1}else if(n===undefined){return-1}else if(n===i){continue}else{return compareIdentifiers(n,i)}}while(++t)};SemVer.prototype.inc=function(e,t){switch(e){case"premajor":this.prerelease.length=0;this.patch=0;this.minor=0;this.major++;this.inc("pre",t);break;case"preminor":this.prerelease.length=0;this.patch=0;this.minor++;this.inc("pre",t);break;case"prepatch":this.prerelease.length=0;this.inc("patch",t);this.inc("pre",t);break;case"prerelease":if(this.prerelease.length===0){this.inc("patch",t)}this.inc("pre",t);break;case"major":if(this.minor!==0||this.patch!==0||this.prerelease.length===0){this.major++}this.minor=0;this.patch=0;this.prerelease=[];break;case"minor":if(this.patch!==0||this.prerelease.length===0){this.minor++}this.patch=0;this.prerelease=[];break;case"patch":if(this.prerelease.length===0){this.patch++}this.prerelease=[];break;case"pre":if(this.prerelease.length===0){this.prerelease=[0]}else{var r=this.prerelease.length;while(--r>=0){if(typeof this.prerelease[r]==="number"){this.prerelease[r]++;r=-2}}if(r===-1){this.prerelease.push(0)}}if(t){if(this.prerelease[0]===t){if(isNaN(this.prerelease[1])){this.prerelease=[t,0]}}else{this.prerelease=[t,0]}}break;default:throw new Error("invalid increment argument: "+e)}this.format();this.raw=this.version;return this};t.inc=inc;function inc(e,t,r,n){if(typeof r==="string"){n=r;r=undefined}try{return new SemVer(e,r).inc(t,n).version}catch(e){return null}}t.diff=diff;function diff(e,t){if(eq(e,t)){return null}else{var r=parse(e);var n=parse(t);var i="";if(r.prerelease.length||n.prerelease.length){i="pre";var o="prerelease"}for(var s in r){if(s==="major"||s==="minor"||s==="patch"){if(r[s]!==n[s]){return i+s}}}return o}}t.compareIdentifiers=compareIdentifiers;var h=/^[0-9]+$/;function compareIdentifiers(e,t){var r=h.test(e);var n=h.test(t);if(r&&n){e=+e;t=+t}return e===t?0:r&&!n?-1:n&&!r?1:e<t?-1:1}t.rcompareIdentifiers=rcompareIdentifiers;function rcompareIdentifiers(e,t){return compareIdentifiers(t,e)}t.major=major;function major(e,t){return new SemVer(e,t).major}t.minor=minor;function minor(e,t){return new SemVer(e,t).minor}t.patch=patch;function patch(e,t){return new SemVer(e,t).patch}t.compare=compare;function compare(e,t,r){return new SemVer(e,r).compare(new SemVer(t,r))}t.compareLoose=compareLoose;function compareLoose(e,t){return compare(e,t,true)}t.compareBuild=compareBuild;function compareBuild(e,t,r){var n=new SemVer(e,r);var i=new SemVer(t,r);return n.compare(i)||n.compareBuild(i)}t.rcompare=rcompare;function rcompare(e,t,r){return compare(t,e,r)}t.sort=sort;function sort(e,r){return e.sort(function(e,n){return t.compareBuild(e,n,r)})}t.rsort=rsort;function rsort(e,r){return e.sort(function(e,n){return t.compareBuild(n,e,r)})}t.gt=gt;function gt(e,t,r){return compare(e,t,r)>0}t.lt=lt;function lt(e,t,r){return compare(e,t,r)<0}t.eq=eq;function eq(e,t,r){return compare(e,t,r)===0}t.neq=neq;function neq(e,t,r){return compare(e,t,r)!==0}t.gte=gte;function gte(e,t,r){return compare(e,t,r)>=0}t.lte=lte;function lte(e,t,r){return compare(e,t,r)<=0}t.cmp=cmp;function cmp(e,t,r,n){switch(t){case"===":if(typeof e==="object")e=e.version;if(typeof r==="object")r=r.version;return e===r;case"!==":if(typeof e==="object")e=e.version;if(typeof r==="object")r=r.version;return e!==r;case"":case"=":case"==":return eq(e,r,n);case"!=":return neq(e,r,n);case">":return gt(e,r,n);case">=":return gte(e,r,n);case"<":return lt(e,r,n);case"<=":return lte(e,r,n);default:throw new TypeError("Invalid operator: "+t)}}t.Comparator=Comparator;function Comparator(e,t){if(!t||typeof t!=="object"){t={loose:!!t,includePrerelease:false}}if(e instanceof Comparator){if(e.loose===!!t.loose){return e}else{e=e.value}}if(!(this instanceof Comparator)){return new Comparator(e,t)}r("comparator",e,t);this.options=t;this.loose=!!t.loose;this.parse(e);if(this.semver===E){this.value=""}else{this.value=this.operator+this.semver.version}r("comp",this)}var E={};Comparator.prototype.parse=function(e){var t=this.options.loose?s[c.COMPARATORLOOSE]:s[c.COMPARATOR];var r=e.match(t);if(!r){throw new TypeError("Invalid comparator: "+e)}this.operator=r[1]!==undefined?r[1]:"";if(this.operator==="="){this.operator=""}if(!r[2]){this.semver=E}else{this.semver=new SemVer(r[2],this.options.loose)}};Comparator.prototype.toString=function(){return this.value};Comparator.prototype.test=function(e){r("Comparator.test",e,this.options.loose);if(this.semver===E||e===E){return true}if(typeof e==="string"){try{e=new SemVer(e,this.options)}catch(e){return false}}return cmp(e,this.operator,this.semver,this.options)};Comparator.prototype.intersects=function(e,t){if(!(e instanceof Comparator)){throw new TypeError("a Comparator is required")}if(!t||typeof t!=="object"){t={loose:!!t,includePrerelease:false}}var r;if(this.operator===""){if(this.value===""){return true}r=new Range(e.value,t);return satisfies(this.value,r,t)}else if(e.operator===""){if(e.value===""){return true}r=new Range(this.value,t);return satisfies(e.semver,r,t)}var n=(this.operator===">="||this.operator===">")&&(e.operator===">="||e.operator===">");var i=(this.operator==="<="||this.operator==="<")&&(e.operator==="<="||e.operator==="<");var o=this.semver.version===e.semver.version;var s=(this.operator===">="||this.operator==="<=")&&(e.operator===">="||e.operator==="<=");var a=cmp(this.semver,"<",e.semver,t)&&((this.operator===">="||this.operator===">")&&(e.operator==="<="||e.operator==="<"));var c=cmp(this.semver,">",e.semver,t)&&((this.operator==="<="||this.operator==="<")&&(e.operator===">="||e.operator===">"));return n||i||o&&s||a||c};t.Range=Range;function Range(e,t){if(!t||typeof t!=="object"){t={loose:!!t,includePrerelease:false}}if(e instanceof Range){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease){return e}else{return new Range(e.raw,t)}}if(e instanceof Comparator){return new Range(e.value,t)}if(!(this instanceof Range)){return new Range(e,t)}this.options=t;this.loose=!!t.loose;this.includePrerelease=!!t.includePrerelease;this.raw=e;this.set=e.split(/\s*\|\|\s*/).map(function(e){return this.parseRange(e.trim())},this).filter(function(e){return e.length});if(!this.set.length){throw new TypeError("Invalid SemVer Range: "+e)}this.format()}Range.prototype.format=function(){this.range=this.set.map(function(e){return e.join(" ").trim()}).join("||").trim();return this.range};Range.prototype.toString=function(){return this.range};Range.prototype.parseRange=function(e){var t=this.options.loose;e=e.trim();var n=t?s[c.HYPHENRANGELOOSE]:s[c.HYPHENRANGE];e=e.replace(n,hyphenReplace);r("hyphen replace",e);e=e.replace(s[c.COMPARATORTRIM],d);r("comparator trim",e,s[c.COMPARATORTRIM]);e=e.replace(s[c.TILDETRIM],l);e=e.replace(s[c.CARETTRIM],f);e=e.split(/\s+/).join(" ");var i=t?s[c.COMPARATORLOOSE]:s[c.COMPARATOR];var o=e.split(" ").map(function(e){return parseComparator(e,this.options)},this).join(" ").split(/\s+/);if(this.options.loose){o=o.filter(function(e){return!!e.match(i)})}o=o.map(function(e){return new Comparator(e,this.options)},this);return o};Range.prototype.intersects=function(e,t){if(!(e instanceof Range)){throw new TypeError("a Range is required")}return this.set.some(function(r){return isSatisfiable(r,t)&&e.set.some(function(e){return isSatisfiable(e,t)&&r.every(function(r){return e.every(function(e){return r.intersects(e,t)})})})})};function isSatisfiable(e,t){var r=true;var n=e.slice();var i=n.pop();while(r&&n.length){r=n.every(function(e){return i.intersects(e,t)});i=n.pop()}return r}t.toComparators=toComparators;function toComparators(e,t){return new Range(e,t).set.map(function(e){return e.map(function(e){return e.value}).join(" ").trim().split(" ")})}function parseComparator(e,t){r("comp",e,t);e=replaceCarets(e,t);r("caret",e);e=replaceTildes(e,t);r("tildes",e);e=replaceXRanges(e,t);r("xrange",e);e=replaceStars(e,t);r("stars",e);return e}function isX(e){return!e||e.toLowerCase()==="x"||e==="*"}function replaceTildes(e,t){return e.trim().split(/\s+/).map(function(e){return replaceTilde(e,t)}).join(" ")}function replaceTilde(e,t){var n=t.loose?s[c.TILDELOOSE]:s[c.TILDE];return e.replace(n,function(t,n,i,o,s){r("tilde",e,t,n,i,o,s);var a;if(isX(n)){a=""}else if(isX(i)){a=">="+n+".0.0 <"+(+n+1)+".0.0"}else if(isX(o)){a=">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0"}else if(s){r("replaceTilde pr",s);a=">="+n+"."+i+"."+o+"-"+s+" <"+n+"."+(+i+1)+".0"}else{a=">="+n+"."+i+"."+o+" <"+n+"."+(+i+1)+".0"}r("tilde return",a);return a})}function replaceCarets(e,t){return e.trim().split(/\s+/).map(function(e){return replaceCaret(e,t)}).join(" ")}function replaceCaret(e,t){r("caret",e,t);var n=t.loose?s[c.CARETLOOSE]:s[c.CARET];return e.replace(n,function(t,n,i,o,s){r("caret",e,t,n,i,o,s);var a;if(isX(n)){a=""}else if(isX(i)){a=">="+n+".0.0 <"+(+n+1)+".0.0"}else if(isX(o)){if(n==="0"){a=">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0"}else{a=">="+n+"."+i+".0 <"+(+n+1)+".0.0"}}else if(s){r("replaceCaret pr",s);if(n==="0"){if(i==="0"){a=">="+n+"."+i+"."+o+"-"+s+" <"+n+"."+i+"."+(+o+1)}else{a=">="+n+"."+i+"."+o+"-"+s+" <"+n+"."+(+i+1)+".0"}}else{a=">="+n+"."+i+"."+o+"-"+s+" <"+(+n+1)+".0.0"}}else{r("no pr");if(n==="0"){if(i==="0"){a=">="+n+"."+i+"."+o+" <"+n+"."+i+"."+(+o+1)}else{a=">="+n+"."+i+"."+o+" <"+n+"."+(+i+1)+".0"}}else{a=">="+n+"."+i+"."+o+" <"+(+n+1)+".0.0"}}r("caret return",a);return a})}function replaceXRanges(e,t){r("replaceXRanges",e,t);return e.split(/\s+/).map(function(e){return replaceXRange(e,t)}).join(" ")}function replaceXRange(e,t){e=e.trim();var n=t.loose?s[c.XRANGELOOSE]:s[c.XRANGE];return e.replace(n,function(n,i,o,s,a,c){r("xRange",e,n,i,o,s,a,c);var u=isX(o);var l=u||isX(s);var f=l||isX(a);var d=f;if(i==="="&&d){i=""}c=t.includePrerelease?"-0":"";if(u){if(i===">"||i==="<"){n="<0.0.0-0"}else{n="*"}}else if(i&&d){if(l){s=0}a=0;if(i===">"){i=">=";if(l){o=+o+1;s=0;a=0}else{s=+s+1;a=0}}else if(i==="<="){i="<";if(l){o=+o+1}else{s=+s+1}}n=i+o+"."+s+"."+a+c}else if(l){n=">="+o+".0.0"+c+" <"+(+o+1)+".0.0"+c}else if(f){n=">="+o+"."+s+".0"+c+" <"+o+"."+(+s+1)+".0"+c}r("xRange return",n);return n})}function replaceStars(e,t){r("replaceStars",e,t);return e.trim().replace(s[c.STAR],"")}function hyphenReplace(e,t,r,n,i,o,s,a,c,u,l,f,d){if(isX(r)){t=""}else if(isX(n)){t=">="+r+".0.0"}else if(isX(i)){t=">="+r+"."+n+".0"}else{t=">="+t}if(isX(c)){a=""}else if(isX(u)){a="<"+(+c+1)+".0.0"}else if(isX(l)){a="<"+c+"."+(+u+1)+".0"}else if(f){a="<="+c+"."+u+"."+l+"-"+f}else{a="<="+a}return(t+" "+a).trim()}Range.prototype.test=function(e){if(!e){return false}if(typeof e==="string"){try{e=new SemVer(e,this.options)}catch(e){return false}}for(var t=0;t<this.set.length;t++){if(testSet(this.set[t],e,this.options)){return true}}return false};function testSet(e,t,n){for(var i=0;i<e.length;i++){if(!e[i].test(t)){return false}}if(t.prerelease.length&&!n.includePrerelease){for(i=0;i<e.length;i++){r(e[i].semver);if(e[i].semver===E){continue}if(e[i].semver.prerelease.length>0){var o=e[i].semver;if(o.major===t.major&&o.minor===t.minor&&o.patch===t.patch){return true}}}return false}return true}t.satisfies=satisfies;function satisfies(e,t,r){try{t=new Range(t,r)}catch(e){return false}return t.test(e)}t.maxSatisfying=maxSatisfying;function maxSatisfying(e,t,r){var n=null;var i=null;try{var o=new Range(t,r)}catch(e){return null}e.forEach(function(e){if(o.test(e)){if(!n||i.compare(e)===-1){n=e;i=new SemVer(n,r)}}});return n}t.minSatisfying=minSatisfying;function minSatisfying(e,t,r){var n=null;var i=null;try{var o=new Range(t,r)}catch(e){return null}e.forEach(function(e){if(o.test(e)){if(!n||i.compare(e)===1){n=e;i=new SemVer(n,r)}}});return n}t.minVersion=minVersion;function minVersion(e,t){e=new Range(e,t);var r=new SemVer("0.0.0");if(e.test(r)){return r}r=new SemVer("0.0.0-0");if(e.test(r)){return r}r=null;for(var n=0;n<e.set.length;++n){var i=e.set[n];i.forEach(function(e){var t=new SemVer(e.semver.version);switch(e.operator){case">":if(t.prerelease.length===0){t.patch++}else{t.prerelease.push(0)}t.raw=t.format();case"":case">=":if(!r||gt(r,t)){r=t}break;case"<":case"<=":break;default:throw new Error("Unexpected operation: "+e.operator)}})}if(r&&e.test(r)){return r}return null}t.validRange=validRange;function validRange(e,t){try{return new Range(e,t).range||"*"}catch(e){return null}}t.ltr=ltr;function ltr(e,t,r){return outside(e,t,"<",r)}t.gtr=gtr;function gtr(e,t,r){return outside(e,t,">",r)}t.outside=outside;function outside(e,t,r,n){e=new SemVer(e,n);t=new Range(t,n);var i,o,s,a,c;switch(r){case">":i=gt;o=lte;s=lt;a=">";c=">=";break;case"<":i=lt;o=gte;s=gt;a="<";c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(satisfies(e,t,n)){return false}for(var u=0;u<t.set.length;++u){var l=t.set[u];var f=null;var d=null;l.forEach(function(e){if(e.semver===E){e=new Comparator(">=0.0.0")}f=f||e;d=d||e;if(i(e.semver,f.semver,n)){f=e}else if(s(e.semver,d.semver,n)){d=e}});if(f.operator===a||f.operator===c){return false}if((!d.operator||d.operator===a)&&o(e,d.semver)){return false}else if(d.operator===c&&s(e,d.semver)){return false}}return true}t.prerelease=prerelease;function prerelease(e,t){var r=parse(e,t);return r&&r.prerelease.length?r.prerelease:null}t.intersects=intersects;function intersects(e,t,r){e=new Range(e,r);t=new Range(t,r);return e.intersects(t)}t.coerce=coerce;function coerce(e,t){if(e instanceof SemVer){return e}if(typeof e==="number"){e=String(e)}if(typeof e!=="string"){return null}t=t||{};var r=null;if(!t.rtl){r=e.match(s[c.COERCE])}else{var n;while((n=s[c.COERCERTL].exec(e))&&(!r||r.index+r[0].length!==e.length)){if(!r||n.index+n[0].length!==r.index+r[0].length){r=n}s[c.COERCERTL].lastIndex=n.index+n[1].length+n[2].length}s[c.COERCERTL].lastIndex=-1}if(r===null){return null}return parse(r[2]+"."+(r[3]||"0")+"."+(r[4]||"0"),t)}},357:function(e){e.exports=require("assert")},413:function(e,t,r){e.exports=r(141)},417:function(e){e.exports=require("crypto")},431:function(e,t,r){"use strict";var n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(Object.hasOwnProperty.call(e,r))t[r]=e[r];t["default"]=e;return t};Object.defineProperty(t,"__esModule",{value:true});const i=n(r(87));const o=r(82);function issueCommand(e,t,r){const n=new Command(e,t,r);process.stdout.write(n.toString()+i.EOL)}t.issueCommand=issueCommand;function issue(e,t=""){issueCommand(e,{},t)}t.issue=issue;const s="::";class Command{constructor(e,t,r){if(!e){e="missing.command"}this.command=e;this.properties=t;this.message=r}toString(){let e=s+this.command;if(this.properties&&Object.keys(this.properties).length>0){e+=" ";let t=true;for(const r in this.properties){if(this.properties.hasOwnProperty(r)){const n=this.properties[r];if(n){if(t){t=false}else{e+=","}e+=`${r}=${escapeProperty(n)}`}}}}e+=`${s}${escapeData(this.message)}`;return e}}function escapeData(e){return o.toCommandValue(e).replace(/%/g,"%25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function escapeProperty(e){return o.toCommandValue(e).replace(/%/g,"%25").replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/:/g,"%3A").replace(/,/g,"%2C")}},470:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r(function(t){t(e)})}return new(r||(r=Promise))(function(r,i){function fulfilled(e){try{step(n.next(e))}catch(e){i(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){i(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())})};var i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(Object.hasOwnProperty.call(e,r))t[r]=e[r];t["default"]=e;return t};Object.defineProperty(t,"__esModule",{value:true});const o=r(431);const s=r(102);const a=r(82);const c=i(r(87));const u=i(r(622));var l;(function(e){e[e["Success"]=0]="Success";e[e["Failure"]=1]="Failure"})(l=t.ExitCode||(t.ExitCode={}));function exportVariable(e,t){const r=a.toCommandValue(t);process.env[e]=r;const n=process.env["GITHUB_ENV"]||"";if(n){const t="_GitHubActionsFileCommandDelimeter_";const n=`${e}<<${t}${c.EOL}${r}${c.EOL}${t}`;s.issueCommand("ENV",n)}else{o.issueCommand("set-env",{name:e},r)}}t.exportVariable=exportVariable;function setSecret(e){o.issueCommand("add-mask",{},e)}t.setSecret=setSecret;function addPath(e){const t=process.env["GITHUB_PATH"]||"";if(t){s.issueCommand("PATH",e)}else{o.issueCommand("add-path",{},e)}process.env["PATH"]=`${e}${u.delimiter}${process.env["PATH"]}`}t.addPath=addPath;function getInput(e,t){const r=process.env[`INPUT_${e.replace(/ /g,"_").toUpperCase()}`]||"";if(t&&t.required&&!r){throw new Error(`Input required and not supplied: ${e}`)}return r.trim()}t.getInput=getInput;function setOutput(e,t){o.issueCommand("set-output",{name:e},t)}t.setOutput=setOutput;function setCommandEcho(e){o.issue("echo",e?"on":"off")}t.setCommandEcho=setCommandEcho;function setFailed(e){process.exitCode=l.Failure;error(e)}t.setFailed=setFailed;function isDebug(){return process.env["RUNNER_DEBUG"]==="1"}t.isDebug=isDebug;function debug(e){o.issueCommand("debug",{},e)}t.debug=debug;function error(e){o.issue("error",e instanceof Error?e.toString():e)}t.error=error;function warning(e){o.issue("warning",e instanceof Error?e.toString():e)}t.warning=warning;function info(e){process.stdout.write(e+c.EOL)}t.info=info;function startGroup(e){o.issue("group",e)}t.startGroup=startGroup;function endGroup(){o.issue("endgroup")}t.endGroup=endGroup;function group(e,t){return n(this,void 0,void 0,function*(){startGroup(e);let r;try{r=yield t()}finally{endGroup()}return r})}t.group=group;function saveState(e,t){o.issueCommand("save-state",{name:e},t)}t.saveState=saveState;function getState(e){return process.env[`STATE_${e}`]||""}t.getState=getState},533:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r(function(t){t(e)})}return new(r||(r=Promise))(function(r,i){function fulfilled(e){try{step(n.next(e))}catch(e){i(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){i(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())})};var i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(Object.hasOwnProperty.call(e,r))t[r]=e[r];t["default"]=e;return t};var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});const s=i(r(470));const a=i(r(1));const c=i(r(747));const u=i(r(31));const l=i(r(87));const f=i(r(622));const d=i(r(539));const p=i(r(280));const h=i(r(794));const E=i(r(669));const v=o(r(826));const y=r(986);const w=r(357);const m=r(979);class HTTPError extends Error{constructor(e){super(`Unexpected HTTP response: ${e}`);this.httpStatusCode=e;Object.setPrototypeOf(this,new.target.prototype)}}t.HTTPError=HTTPError;const R=process.platform==="win32";const g=process.platform==="darwin";const O="actions/tool-cache";function downloadTool(e,t,r){return n(this,void 0,void 0,function*(){t=t||f.join(_getTempDirectory(),v.default());yield a.mkdirP(f.dirname(t));s.debug(`Downloading ${e}`);s.debug(`Destination ${t}`);const i=3;const o=_getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS",10);const c=_getGlobal("TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS",20);const u=new m.RetryHelper(i,o,c);return yield u.execute(()=>n(this,void 0,void 0,function*(){return yield downloadToolAttempt(e,t||"",r)}),e=>{if(e instanceof HTTPError&&e.httpStatusCode){if(e.httpStatusCode<500&&e.httpStatusCode!==408&&e.httpStatusCode!==429){return false}}return true})})}t.downloadTool=downloadTool;function downloadToolAttempt(e,t,r){return n(this,void 0,void 0,function*(){if(c.existsSync(t)){throw new Error(`Destination file path ${t} already exists`)}const n=new d.HttpClient(O,[],{allowRetries:false});let i;if(r){s.debug("set auth");i={authorization:r}}const o=yield n.get(e,i);if(o.message.statusCode!==200){const t=new HTTPError(o.message.statusCode);s.debug(`Failed to download from "${e}". Code(${o.message.statusCode}) Message(${o.message.statusMessage})`);throw t}const u=E.promisify(h.pipeline);const l=_getGlobal("TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY",()=>o.message);const f=l();let p=false;try{yield u(f,c.createWriteStream(t));s.debug("download complete");p=true;return t}finally{if(!p){s.debug("download failed");try{yield a.rmRF(t)}catch(e){s.debug(`Failed to delete '${t}'. ${e.message}`)}}}})}function extract7z(e,t,r){return n(this,void 0,void 0,function*(){w.ok(R,"extract7z() not supported on current OS");w.ok(e,'parameter "file" is required');t=yield _createExtractFolder(t);const n=process.cwd();process.chdir(t);if(r){try{const t=s.isDebug()?"-bb1":"-bb0";const i=["x",t,"-bd","-sccUTF-8",e];const o={silent:true};yield y.exec(`"${r}"`,i,o)}finally{process.chdir(n)}}else{const r=f.join(__dirname,"..","scripts","Invoke-7zdec.ps1").replace(/'/g,"''").replace(/"|\n|\r/g,"");const i=e.replace(/'/g,"''").replace(/"|\n|\r/g,"");const o=t.replace(/'/g,"''").replace(/"|\n|\r/g,"");const s=`& '${r}' -Source '${i}' -Target '${o}'`;const c=["-NoLogo","-Sta","-NoProfile","-NonInteractive","-ExecutionPolicy","Unrestricted","-Command",s];const u={silent:true};try{const e=yield a.which("powershell",true);yield y.exec(`"${e}"`,c,u)}finally{process.chdir(n)}}return t})}t.extract7z=extract7z;function extractTar(e,t,r="xz"){return n(this,void 0,void 0,function*(){if(!e){throw new Error("parameter 'file' is required")}t=yield _createExtractFolder(t);s.debug("Checking tar --version");let n="";yield y.exec("tar --version",[],{ignoreReturnCode:true,silent:true,listeners:{stdout:e=>n+=e.toString(),stderr:e=>n+=e.toString()}});s.debug(n.trim());const i=n.toUpperCase().includes("GNU TAR");let o;if(r instanceof Array){o=r}else{o=[r]}if(s.isDebug()&&!r.includes("v")){o.push("-v")}let a=t;let c=e;if(R&&i){o.push("--force-local");a=t.replace(/\\/g,"/");c=e.replace(/\\/g,"/")}if(i){o.push("--warning=no-unknown-keyword")}o.push("-C",a,"-f",c);yield y.exec(`tar`,o);return t})}t.extractTar=extractTar;function extractXar(e,t,r=[]){return n(this,void 0,void 0,function*(){w.ok(g,"extractXar() not supported on current OS");w.ok(e,'parameter "file" is required');t=yield _createExtractFolder(t);let n;if(r instanceof Array){n=r}else{n=[r]}n.push("-x","-C",t,"-f",e);if(s.isDebug()){n.push("-v")}const i=yield a.which("xar",true);yield y.exec(`"${i}"`,_unique(n));return t})}t.extractXar=extractXar;function extractZip(e,t){return n(this,void 0,void 0,function*(){if(!e){throw new Error("parameter 'file' is required")}t=yield _createExtractFolder(t);if(R){yield extractZipWin(e,t)}else{yield extractZipNix(e,t)}return t})}t.extractZip=extractZip;function extractZipWin(e,t){return n(this,void 0,void 0,function*(){const r=e.replace(/'/g,"''").replace(/"|\n|\r/g,"");const n=t.replace(/'/g,"''").replace(/"|\n|\r/g,"");const i=`$ErrorActionPreference = 'Stop' ; try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ; [System.IO.Compression.ZipFile]::ExtractToDirectory('${r}', '${n}')`;const o=yield a.which("powershell",true);const s=["-NoLogo","-Sta","-NoProfile","-NonInteractive","-ExecutionPolicy","Unrestricted","-Command",i];yield y.exec(`"${o}"`,s)})}function extractZipNix(e,t){return n(this,void 0,void 0,function*(){const r=yield a.which("unzip",true);const n=[e];if(!s.isDebug()){n.unshift("-q")}yield y.exec(`"${r}"`,n,{cwd:t})})}function cacheDir(e,t,r,i){return n(this,void 0,void 0,function*(){r=p.clean(r)||r;i=i||l.arch();s.debug(`Caching tool ${t} ${r} ${i}`);s.debug(`source dir: ${e}`);if(!c.statSync(e).isDirectory()){throw new Error("sourceDir is not a directory")}const n=yield _createToolPath(t,r,i);for(const t of c.readdirSync(e)){const r=f.join(e,t);yield a.cp(r,n,{recursive:true})}_completeToolPath(t,r,i);return n})}t.cacheDir=cacheDir;function cacheFile(e,t,r,i,o){return n(this,void 0,void 0,function*(){i=p.clean(i)||i;o=o||l.arch();s.debug(`Caching tool ${r} ${i} ${o}`);s.debug(`source file: ${e}`);if(!c.statSync(e).isFile()){throw new Error("sourceFile is not a file")}const n=yield _createToolPath(r,i,o);const u=f.join(n,t);s.debug(`destination file ${u}`);yield a.cp(e,u);_completeToolPath(r,i,o);return n})}t.cacheFile=cacheFile;function find(e,t,r){if(!e){throw new Error("toolName parameter is required")}if(!t){throw new Error("versionSpec parameter is required")}r=r||l.arch();if(!_isExplicitVersion(t)){const n=findAllVersions(e,r);const i=_evaluateVersions(n,t);t=i}let n="";if(t){t=p.clean(t)||"";const i=f.join(_getCacheDirectory(),e,t,r);s.debug(`checking cache: ${i}`);if(c.existsSync(i)&&c.existsSync(`${i}.complete`)){s.debug(`Found tool in cache ${e} ${t} ${r}`);n=i}else{s.debug("not found")}}return n}t.find=find;function findAllVersions(e,t){const r=[];t=t||l.arch();const n=f.join(_getCacheDirectory(),e);if(c.existsSync(n)){const e=c.readdirSync(n);for(const i of e){if(_isExplicitVersion(i)){const e=f.join(n,i,t||"");if(c.existsSync(e)&&c.existsSync(`${e}.complete`)){r.push(i)}}}}return r}t.findAllVersions=findAllVersions;function getManifestFromRepo(e,t,r,i="master"){return n(this,void 0,void 0,function*(){let n=[];const o=`https://api.github.com/repos/${e}/${t}/git/trees/${i}`;const a=new d.HttpClient("tool-cache");const c={};if(r){s.debug("set auth");c.authorization=r}const u=yield a.getJson(o,c);if(!u.result){return n}let l="";for(const e of u.result.tree){if(e.path==="versions-manifest.json"){l=e.url;break}}c["accept"]="application/vnd.github.VERSION.raw";let f=yield(yield a.get(l,c)).readBody();if(f){f=f.replace(/^\uFEFF/,"");try{n=JSON.parse(f)}catch(e){s.debug("Invalid json")}}return n})}t.getManifestFromRepo=getManifestFromRepo;function findFromManifest(e,t,r,i=l.arch()){return n(this,void 0,void 0,function*(){const n=yield u._findMatch(e,t,r,i);return n})}t.findFromManifest=findFromManifest;function _createExtractFolder(e){return n(this,void 0,void 0,function*(){if(!e){e=f.join(_getTempDirectory(),v.default())}yield a.mkdirP(e);return e})}function _createToolPath(e,t,r){return n(this,void 0,void 0,function*(){const n=f.join(_getCacheDirectory(),e,p.clean(t)||t,r||"");s.debug(`destination ${n}`);const i=`${n}.complete`;yield a.rmRF(n);yield a.rmRF(i);yield a.mkdirP(n);return n})}function _completeToolPath(e,t,r){const n=f.join(_getCacheDirectory(),e,p.clean(t)||t,r||"");const i=`${n}.complete`;c.writeFileSync(i,"");s.debug("finished caching tool")}function _isExplicitVersion(e){const t=p.clean(e)||"";s.debug(`isExplicit: ${t}`);const r=p.valid(t)!=null;s.debug(`explicit? ${r}`);return r}function _evaluateVersions(e,t){let r="";s.debug(`evaluating ${e.length} versions`);e=e.sort((e,t)=>{if(p.gt(e,t)){return 1}return-1});for(let n=e.length-1;n>=0;n--){const i=e[n];const o=p.satisfies(i,t);if(o){r=i;break}}if(r){s.debug(`matched: ${r}`)}else{s.debug("match not found")}return r}function _getCacheDirectory(){const e=process.env["RUNNER_TOOL_CACHE"]||"";w.ok(e,"Expected RUNNER_TOOL_CACHE to be defined");return e}function _getTempDirectory(){const e=process.env["RUNNER_TEMP"]||"";w.ok(e,"Expected RUNNER_TEMP to be defined");return e}function _getGlobal(e,t){const r=global[e];return r!==undefined?r:t}function _unique(e){return Array.from(new Set(e))}},539:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:true});const n=r(605);const i=r(211);const o=r(950);let s;var a;(function(e){e[e["OK"]=200]="OK";e[e["MultipleChoices"]=300]="MultipleChoices";e[e["MovedPermanently"]=301]="MovedPermanently";e[e["ResourceMoved"]=302]="ResourceMoved";e[e["SeeOther"]=303]="SeeOther";e[e["NotModified"]=304]="NotModified";e[e["UseProxy"]=305]="UseProxy";e[e["SwitchProxy"]=306]="SwitchProxy";e[e["TemporaryRedirect"]=307]="TemporaryRedirect";e[e["PermanentRedirect"]=308]="PermanentRedirect";e[e["BadRequest"]=400]="BadRequest";e[e["Unauthorized"]=401]="Unauthorized";e[e["PaymentRequired"]=402]="PaymentRequired";e[e["Forbidden"]=403]="Forbidden";e[e["NotFound"]=404]="NotFound";e[e["MethodNotAllowed"]=405]="MethodNotAllowed";e[e["NotAcceptable"]=406]="NotAcceptable";e[e["ProxyAuthenticationRequired"]=407]="ProxyAuthenticationRequired";e[e["RequestTimeout"]=408]="RequestTimeout";e[e["Conflict"]=409]="Conflict";e[e["Gone"]=410]="Gone";e[e["TooManyRequests"]=429]="TooManyRequests";e[e["InternalServerError"]=500]="InternalServerError";e[e["NotImplemented"]=501]="NotImplemented";e[e["BadGateway"]=502]="BadGateway";e[e["ServiceUnavailable"]=503]="ServiceUnavailable";e[e["GatewayTimeout"]=504]="GatewayTimeout"})(a=t.HttpCodes||(t.HttpCodes={}));var c;(function(e){e["Accept"]="accept";e["ContentType"]="content-type"})(c=t.Headers||(t.Headers={}));var u;(function(e){e["ApplicationJson"]="application/json"})(u=t.MediaTypes||(t.MediaTypes={}));function getProxyUrl(e){let t=o.getProxyUrl(new URL(e));return t?t.href:""}t.getProxyUrl=getProxyUrl;const l=[a.MovedPermanently,a.ResourceMoved,a.SeeOther,a.TemporaryRedirect,a.PermanentRedirect];const f=[a.BadGateway,a.ServiceUnavailable,a.GatewayTimeout];const d=["OPTIONS","GET","DELETE","HEAD"];const p=10;const h=5;class HttpClientError extends Error{constructor(e,t){super(e);this.name="HttpClientError";this.statusCode=t;Object.setPrototypeOf(this,HttpClientError.prototype)}}t.HttpClientError=HttpClientError;class HttpClientResponse{constructor(e){this.message=e}readBody(){return new Promise(async(e,t)=>{let r=Buffer.alloc(0);this.message.on("data",e=>{r=Buffer.concat([r,e])});this.message.on("end",()=>{e(r.toString())})})}}t.HttpClientResponse=HttpClientResponse;function isHttps(e){let t=new URL(e);return t.protocol==="https:"}t.isHttps=isHttps;class HttpClient{constructor(e,t,r){this._ignoreSslError=false;this._allowRedirects=true;this._allowRedirectDowngrade=false;this._maxRedirects=50;this._allowRetries=false;this._maxRetries=1;this._keepAlive=false;this._disposed=false;this.userAgent=e;this.handlers=t||[];this.requestOptions=r;if(r){if(r.ignoreSslError!=null){this._ignoreSslError=r.ignoreSslError}this._socketTimeout=r.socketTimeout;if(r.allowRedirects!=null){this._allowRedirects=r.allowRedirects}if(r.allowRedirectDowngrade!=null){this._allowRedirectDowngrade=r.allowRedirectDowngrade}if(r.maxRedirects!=null){this._maxRedirects=Math.max(r.maxRedirects,0)}if(r.keepAlive!=null){this._keepAlive=r.keepAlive}if(r.allowRetries!=null){this._allowRetries=r.allowRetries}if(r.maxRetries!=null){this._maxRetries=r.maxRetries}}}options(e,t){return this.request("OPTIONS",e,null,t||{})}get(e,t){return this.request("GET",e,null,t||{})}del(e,t){return this.request("DELETE",e,null,t||{})}post(e,t,r){return this.request("POST",e,t,r||{})}patch(e,t,r){return this.request("PATCH",e,t,r||{})}put(e,t,r){return this.request("PUT",e,t,r||{})}head(e,t){return this.request("HEAD",e,null,t||{})}sendStream(e,t,r,n){return this.request(e,t,r,n)}async getJson(e,t={}){t[c.Accept]=this._getExistingOrDefaultHeader(t,c.Accept,u.ApplicationJson);let r=await this.get(e,t);return this._processResponse(r,this.requestOptions)}async postJson(e,t,r={}){let n=JSON.stringify(t,null,2);r[c.Accept]=this._getExistingOrDefaultHeader(r,c.Accept,u.ApplicationJson);r[c.ContentType]=this._getExistingOrDefaultHeader(r,c.ContentType,u.ApplicationJson);let i=await this.post(e,n,r);return this._processResponse(i,this.requestOptions)}async putJson(e,t,r={}){let n=JSON.stringify(t,null,2);r[c.Accept]=this._getExistingOrDefaultHeader(r,c.Accept,u.ApplicationJson);r[c.ContentType]=this._getExistingOrDefaultHeader(r,c.ContentType,u.ApplicationJson);let i=await this.put(e,n,r);return this._processResponse(i,this.requestOptions)}async patchJson(e,t,r={}){let n=JSON.stringify(t,null,2);r[c.Accept]=this._getExistingOrDefaultHeader(r,c.Accept,u.ApplicationJson);r[c.ContentType]=this._getExistingOrDefaultHeader(r,c.ContentType,u.ApplicationJson);let i=await this.patch(e,n,r);return this._processResponse(i,this.requestOptions)}async request(e,t,r,n){if(this._disposed){throw new Error("Client has already been disposed.")}let i=new URL(t);let o=this._prepareRequest(e,i,n);let s=this._allowRetries&&d.indexOf(e)!=-1?this._maxRetries+1:1;let c=0;let u;while(c<s){u=await this.requestRaw(o,r);if(u&&u.message&&u.message.statusCode===a.Unauthorized){let e;for(let t=0;t<this.handlers.length;t++){if(this.handlers[t].canHandleAuthentication(u)){e=this.handlers[t];break}}if(e){return e.handleAuthentication(this,o,r)}else{return u}}let t=this._maxRedirects;while(l.indexOf(u.message.statusCode)!=-1&&this._allowRedirects&&t>0){const s=u.message.headers["location"];if(!s){break}let a=new URL(s);if(i.protocol=="https:"&&i.protocol!=a.protocol&&!this._allowRedirectDowngrade){throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.")}await u.readBody();if(a.hostname!==i.hostname){for(let e in n){if(e.toLowerCase()==="authorization"){delete n[e]}}}o=this._prepareRequest(e,a,n);u=await this.requestRaw(o,r);t--}if(f.indexOf(u.message.statusCode)==-1){return u}c+=1;if(c<s){await u.readBody();await this._performExponentialBackoff(c)}}return u}dispose(){if(this._agent){this._agent.destroy()}this._disposed=true}requestRaw(e,t){return new Promise((r,n)=>{let i=function(e,t){if(e){n(e)}r(t)};this.requestRawWithCallback(e,t,i)})}requestRawWithCallback(e,t,r){let n;if(typeof t==="string"){e.options.headers["Content-Length"]=Buffer.byteLength(t,"utf8")}let i=false;let o=(e,t)=>{if(!i){i=true;r(e,t)}};let s=e.httpModule.request(e.options,e=>{let t=new HttpClientResponse(e);o(null,t)});s.on("socket",e=>{n=e});s.setTimeout(this._socketTimeout||3*6e4,()=>{if(n){n.end()}o(new Error("Request timeout: "+e.options.path),null)});s.on("error",function(e){o(e,null)});if(t&&typeof t==="string"){s.write(t,"utf8")}if(t&&typeof t!=="string"){t.on("close",function(){s.end()});t.pipe(s)}else{s.end()}}getAgent(e){let t=new URL(e);return this._getAgent(t)}_prepareRequest(e,t,r){const o={};o.parsedUrl=t;const s=o.parsedUrl.protocol==="https:";o.httpModule=s?i:n;const a=s?443:80;o.options={};o.options.host=o.parsedUrl.hostname;o.options.port=o.parsedUrl.port?parseInt(o.parsedUrl.port):a;o.options.path=(o.parsedUrl.pathname||"")+(o.parsedUrl.search||"");o.options.method=e;o.options.headers=this._mergeHeaders(r);if(this.userAgent!=null){o.options.headers["user-agent"]=this.userAgent}o.options.agent=this._getAgent(o.parsedUrl);if(this.handlers){this.handlers.forEach(e=>{e.prepareRequest(o.options)})}return o}_mergeHeaders(e){const t=e=>Object.keys(e).reduce((t,r)=>(t[r.toLowerCase()]=e[r],t),{});if(this.requestOptions&&this.requestOptions.headers){return Object.assign({},t(this.requestOptions.headers),t(e))}return t(e||{})}_getExistingOrDefaultHeader(e,t,r){const n=e=>Object.keys(e).reduce((t,r)=>(t[r.toLowerCase()]=e[r],t),{});let i;if(this.requestOptions&&this.requestOptions.headers){i=n(this.requestOptions.headers)[t]}return e[t]||i||r}_getAgent(e){let t;let a=o.getProxyUrl(e);let c=a&&a.hostname;if(this._keepAlive&&c){t=this._proxyAgent}if(this._keepAlive&&!c){t=this._agent}if(!!t){return t}const u=e.protocol==="https:";let l=100;if(!!this.requestOptions){l=this.requestOptions.maxSockets||n.globalAgent.maxSockets}if(c){if(!s){s=r(413)}const e={maxSockets:l,keepAlive:this._keepAlive,proxy:{proxyAuth:`${a.username}:${a.password}`,host:a.hostname,port:a.port}};let n;const i=a.protocol==="https:";if(u){n=i?s.httpsOverHttps:s.httpsOverHttp}else{n=i?s.httpOverHttps:s.httpOverHttp}t=n(e);this._proxyAgent=t}if(this._keepAlive&&!t){const e={keepAlive:this._keepAlive,maxSockets:l};t=u?new i.Agent(e):new n.Agent(e);this._agent=t}if(!t){t=u?i.globalAgent:n.globalAgent}if(u&&this._ignoreSslError){t.options=Object.assign(t.options||{},{rejectUnauthorized:false})}return t}_performExponentialBackoff(e){e=Math.min(p,e);const t=h*Math.pow(2,e);return new Promise(e=>setTimeout(()=>e(),t))}static dateTimeDeserializer(e,t){if(typeof t==="string"){let e=new Date(t);if(!isNaN(e.valueOf())){return e}}return t}async _processResponse(e,t){return new Promise(async(r,n)=>{const i=e.message.statusCode;const o={statusCode:i,result:null,headers:{}};if(i==a.NotFound){r(o)}let s;let c;try{c=await e.readBody();if(c&&c.length>0){if(t&&t.deserializeDates){s=JSON.parse(c,HttpClient.dateTimeDeserializer)}else{s=JSON.parse(c)}o.result=s}o.headers=e.message.headers}catch(e){}if(i>299){let e;if(s&&s.message){e=s.message}else if(c&&c.length>0){e=c}else{e="Failed request: ("+i+")"}let t=new HttpClientError(e,i);t.result=o.result;n(t)}else{r(o)}})}}t.HttpClient=HttpClient},605:function(e){e.exports=require("http")},614:function(e){e.exports=require("events")},622:function(e){e.exports=require("path")},631:function(e){e.exports=require("net")},669:function(e){e.exports=require("util")},672:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r(function(t){t(e)})}return new(r||(r=Promise))(function(r,i){function fulfilled(e){try{step(n.next(e))}catch(e){i(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){i(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())})};var i;Object.defineProperty(t,"__esModule",{value:true});const o=r(357);const s=r(747);const a=r(622);i=s.promises,t.chmod=i.chmod,t.copyFile=i.copyFile,t.lstat=i.lstat,t.mkdir=i.mkdir,t.readdir=i.readdir,t.readlink=i.readlink,t.rename=i.rename,t.rmdir=i.rmdir,t.stat=i.stat,t.symlink=i.symlink,t.unlink=i.unlink;t.IS_WINDOWS=process.platform==="win32";function exists(e){return n(this,void 0,void 0,function*(){try{yield t.stat(e)}catch(e){if(e.code==="ENOENT"){return false}throw e}return true})}t.exists=exists;function isDirectory(e,r=false){return n(this,void 0,void 0,function*(){const n=r?yield t.stat(e):yield t.lstat(e);return n.isDirectory()})}t.isDirectory=isDirectory;function isRooted(e){e=normalizeSeparators(e);if(!e){throw new Error('isRooted() parameter "p" cannot be empty')}if(t.IS_WINDOWS){return e.startsWith("\\")||/^[A-Z]:/i.test(e)}return e.startsWith("/")}t.isRooted=isRooted;function mkdirP(e,r=1e3,i=1){return n(this,void 0,void 0,function*(){o.ok(e,"a path argument must be provided");e=a.resolve(e);if(i>=r)return t.mkdir(e);try{yield t.mkdir(e);return}catch(n){switch(n.code){case"ENOENT":{yield mkdirP(a.dirname(e),r,i+1);yield t.mkdir(e);return}default:{let r;try{r=yield t.stat(e)}catch(e){throw n}if(!r.isDirectory())throw n}}}})}t.mkdirP=mkdirP;function tryGetExecutablePath(e,r){return n(this,void 0,void 0,function*(){let n=undefined;try{n=yield t.stat(e)}catch(t){if(t.code!=="ENOENT"){console.log(`Unexpected error attempting to determine if executable file exists '${e}': ${t}`)}}if(n&&n.isFile()){if(t.IS_WINDOWS){const t=a.extname(e).toUpperCase();if(r.some(e=>e.toUpperCase()===t)){return e}}else{if(isUnixExecutable(n)){return e}}}const i=e;for(const o of r){e=i+o;n=undefined;try{n=yield t.stat(e)}catch(t){if(t.code!=="ENOENT"){console.log(`Unexpected error attempting to determine if executable file exists '${e}': ${t}`)}}if(n&&n.isFile()){if(t.IS_WINDOWS){try{const r=a.dirname(e);const n=a.basename(e).toUpperCase();for(const i of yield t.readdir(r)){if(n===i.toUpperCase()){e=a.join(r,i);break}}}catch(t){console.log(`Unexpected error attempting to determine the actual case of the file '${e}': ${t}`)}return e}else{if(isUnixExecutable(n)){return e}}}}return""})}t.tryGetExecutablePath=tryGetExecutablePath;function normalizeSeparators(e){e=e||"";if(t.IS_WINDOWS){e=e.replace(/\//g,"\\");return e.replace(/\\\\+/g,"\\")}return e.replace(/\/\/+/g,"/")}function isUnixExecutable(e){return(e.mode&1)>0||(e.mode&8)>0&&e.gid===process.getgid()||(e.mode&64)>0&&e.uid===process.getuid()}},722:function(e){var t=[];for(var r=0;r<256;++r){t[r]=(r+256).toString(16).substr(1)}function bytesToUuid(e,r){var n=r||0;var i=t;return[i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]]].join("")}e.exports=bytesToUuid},747:function(e){e.exports=require("fs")},794:function(e){e.exports=require("stream")},826:function(e,t,r){var n=r(139);var i=r(722);function v4(e,t,r){var o=t&&r||0;if(typeof e=="string"){t=e==="binary"?new Array(16):null;e=null}e=e||{};var s=e.random||(e.rng||n)();s[6]=s[6]&15|64;s[8]=s[8]&63|128;if(t){for(var a=0;a<16;++a){t[o+a]=s[a]}}return t||i(s)}e.exports=v4},950:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:true});function getProxyUrl(e){let t=e.protocol==="https:";let r;if(checkBypass(e)){return r}let n;if(t){n=process.env["https_proxy"]||process.env["HTTPS_PROXY"]}else{n=process.env["http_proxy"]||process.env["HTTP_PROXY"]}if(n){r=new URL(n)}return r}t.getProxyUrl=getProxyUrl;function checkBypass(e){if(!e.hostname){return false}let t=process.env["no_proxy"]||process.env["NO_PROXY"]||"";if(!t){return false}let r;if(e.port){r=Number(e.port)}else if(e.protocol==="http:"){r=80}else if(e.protocol==="https:"){r=443}let n=[e.hostname.toUpperCase()];if(typeof r==="number"){n.push(`${n[0]}:${r}`)}for(let e of t.split(",").map(e=>e.trim().toUpperCase()).filter(e=>e)){if(n.some(t=>t===e)){return true}}return false}t.checkBypass=checkBypass},979:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r(function(t){t(e)})}return new(r||(r=Promise))(function(r,i){function fulfilled(e){try{step(n.next(e))}catch(e){i(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){i(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())})};var i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(Object.hasOwnProperty.call(e,r))t[r]=e[r];t["default"]=e;return t};Object.defineProperty(t,"__esModule",{value:true});const o=i(r(470));class RetryHelper{constructor(e,t,r){if(e<1){throw new Error("max attempts should be greater than or equal to 1")}this.maxAttempts=e;this.minSeconds=Math.floor(t);this.maxSeconds=Math.floor(r);if(this.minSeconds>this.maxSeconds){throw new Error("min seconds should be less than or equal to max seconds")}}execute(e,t){return n(this,void 0,void 0,function*(){let r=1;while(r<this.maxAttempts){try{return yield e()}catch(e){if(t&&!t(e)){throw e}o.info(e.message)}const n=this.getSleepAmount();o.info(`Waiting ${n} seconds before trying again`);yield this.sleep(n);r++}return yield e()})}getSleepAmount(){return Math.floor(Math.random()*(this.maxSeconds-this.minSeconds+1))+this.minSeconds}sleep(e){return n(this,void 0,void 0,function*(){return new Promise(t=>setTimeout(t,e*1e3))})}}t.RetryHelper=RetryHelper},986:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r(function(t){t(e)})}return new(r||(r=Promise))(function(r,i){function fulfilled(e){try{step(n.next(e))}catch(e){i(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){i(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())})};var i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(Object.hasOwnProperty.call(e,r))t[r]=e[r];t["default"]=e;return t};Object.defineProperty(t,"__esModule",{value:true});const o=i(r(9));function exec(e,t,r){return n(this,void 0,void 0,function*(){const n=o.argStringToArray(e);if(n.length===0){throw new Error(`Parameter 'commandLine' cannot be null or empty.`)}const i=n[0];t=n.slice(1).concat(t||[]);const s=new o.ToolRunner(i,t,r);return s.exec()})}t.exec=exec}});
module.exports = (api) => { api.electrum.get_addresses = (coin) => { const coinLc = coin.toLowerCase() let addresses = { public: [], private: [] } return new Promise((resolve, reject) => { if (!api.electrumKeys[coinLc] || !api.electrumKeys[coinLc].pub) { throw new Error(`No address found for ${coin}`); } addresses.public.push({address: api.electrumKeys[coinLc].pub, tag: 'public'}) Promise.all(addresses.public.map((addressObj) => { return api.electrum.get_balances(addressObj.address, coin) })) .then((addressBalances) => { addresses.public = addresses.public.map((addressObj, index) => { return {...addressObj, balances: {native: addressBalances[index].confirmed, reserve: {}}} }) resolve(addresses) }) .catch(err => { reject(err) }) }); }; api.setPost('/electrum/get_pubkey', (req, res, next) => { const coin = req.body.chainTicker; const coinLc = coin.toLowerCase() if (api.electrumKeys[coinLc] && api.electrumKeys[coinLc].pubHex) { res.send(JSON.stringify({ msg: 'success', result: api.electrumKeys[coinLc].pubHex })); } else { res.send(JSON.stringify({ msg: 'error', result: `No pubkey found for electrum coin ${coin}` })); } }); api.setPost('/electrum/get_privkey', (req, res, next) => { const coin = req.body.chainTicker; const coinLc = coin.toLowerCase() if (api.electrumKeys[coinLc] && api.electrumKeys[coinLc].priv) { res.send(JSON.stringify({ msg: 'success', result: api.electrumKeys[coinLc].priv })); } else { res.send(JSON.stringify({ msg: 'error', result: `No privkey found for electrum coin ${coin}` })); } }); api.setGet('/electrum/get_addresses', (req, res, next) => { const coin = req.query.chainTicker; if (!req.query.chainTicker) { res.send(JSON.stringify({msg: 'error', result: "No coin passed to electrum get_addresses"})); } api.electrum.get_addresses(coin) .then((addresses) => { const retObj = { msg: 'success', result: addresses, }; res.send(JSON.stringify(retObj)); }) .catch(error => { const retObj = { msg: 'error', result: error.message, }; res.send(JSON.stringify(retObj)); }) }); return api; };
'use strict' /** * Constants affecting the animation curve of an action, used by the timingMode property. * @typedef {Object} SCNActionTimingMode * @property {number} linear - Linear pacing. The animation progresses evenly throughout its duration. * @property {number} easeIn - Ease-in pacing. The animation begins slowly, and then speeds up as it progresses. * @property {number} easeOut - Ease-out pacing. The animation begins quickly, and then slows as it completes. * @property {number} easeInEaseOut - Ease-in ease-out pacing. The animation begins slowly, accelerates through the middle of its duration, and then slows again before completing. * @see https://developer.apple.com/documentation/scenekit/scnactiontimingmode */ const SCNActionTimingMode = { linear: 0, easeIn: 1, easeOut: 2, easeInEaseOut: 3 } export default SCNActionTimingMode
import React, {useEffect} from 'react'; import MyCv from '../fileDownload/MyCv.pdf' import { AiOutlineCloudDownload } from "react-icons/ai" import HeaderContainer from '../components/Layout/HeaderContainer' import '../styles/Pdf.scss' const Pdf = () => { useEffect(() => { if(typeof window.orientation !== "undefined"){ document.getElementById('enlaceDescargarPdf').click(); window.close(); } }, []) return ( <> <HeaderContainer/> <section className='Pdf-Container'> <object data={MyCv} type="application/pdf" width="100%" height="105%" > <div> <img src='https://www.programando.org/blog/2021/06/28/el-camino-del-backend-developer-lenguajes-formales/featured.png' alr='Frontend Developer'/> <a href={MyCv} id="enlaceDescargarPdf" download="David-Arevalo-CV.pdf" >Your device cannot view pdf, Downloading Automatically. <AiOutlineCloudDownload/></a> </div> </object> </section> </> ); } export default Pdf
//Global Vars var inProp = {}; var CertUtils = Java.type("com.tremolosecurity.kubernetes.artifacts.util.CertUtils"); var NetUtil = Java.type("com.tremolosecurity.kubernetes.artifacts.util.NetUtil"); var cfg_obj = {}; var k8s_obj = {}; var ouKS; var ksPassword; var secret_data_changed = true; var amq_secrets_changed = true; var amq_env_secrets_changed = true; var System = Java.type("java.lang.System"); var Integer = Java.type("java.lang.Integer"); var Class = Java.type("java.lang.Class"); var DriverManager = Java.type("java.sql.DriverManager");
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * 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 from 'react'; import { Button, Dialog, Loading, Table } from '@alifd/next'; import RegionGroup from '../../components/RegionGroup'; import DeleteDialog from '../../components/DeleteDialog'; import NewNameSpace from '../../components/NewNameSpace'; import EditorNameSpace from '../../components/EditorNameSpace'; import { getParams, setParams, request, aliwareIntl } from '../../globalLib'; import './index.less'; /*****************************此行为标记行, 请勿删和修改此行, 文件和组件依赖请写在此行上面, 主体代码请写在此行下面的class中*****************************/ class NameSpace extends React.Component { constructor(props) { super(props); this.state = { loading: false, defaultNamespace: "", dataSource: [] }; } componentDidMount() { this.getNameSpaces(0); } getNameSpaces(delayTime = 2000) { let self = this; // let serverId = getParams('serverId') || 'center'; self.openLoading(); setTimeout(() => { request({ type: 'get', beforeSend: function () { }, url: `/nacos/v1/console/namespaces`, success: res => { if (res.code === 200) { let data = res.data || []; window.namespaceList = data; for (var i = 0; i < data.length; i++) { if (data[i].type === 1) { this.setState({ defaultNamespace: data[i].namespace }); } } this.setState({ dataSource: data }); } else { Dialog.alert({ language: aliwareIntl.currentLanguageCode || 'zh-cn', title: aliwareIntl.get('com.alibaba.nacos.page.namespace.prompt'), content: res.message }); } }, complete: function () { self.closeLoading(); }, error: res => { window.namespaceList = [{ "namespace": "", "namespaceShowName": "公共空间", "type": 0 }]; } }); }, delayTime); } openLoading() { this.setState({ loading: true }); } closeLoading() { this.setState({ loading: false }); } detailNamespace(record) { let namespace = record.namespace; //获取ak,sk request({ url: `/nacos/v1/console/namespaces?show=all&namespaceId=${namespace}`, beforeSend: () => { this.openLoading(); }, success: res => { if (res !== null) { Dialog.alert({ style: { width: "500px" }, needWrapper: false, language: aliwareIntl.currentLanguageCode || 'zh-cn', title: aliwareIntl.get('nacos.page.namespace.Namespace_details'), content: <div> <div style={{ marginTop: '10px' }}> <p> <span style={{ color: '#999', marginRight: 5 }}>{aliwareIntl.get('nacos.page.namespace.namespace_name')}</span> <span style={{ color: '#c7254e' }}> {res.namespaceShowName} </span> </p> <p> <span style={{ color: '#999', marginRight: 5 }}>{aliwareIntl.get('nacos.page.namespace.namespace_ID')}</span> <span style={{ color: '#c7254e' }}> {res.namespace} </span> </p> <p> <span style={{ color: '#999', marginRight: 5 }}>{aliwareIntl.get('com.alibaba.nacos.page.namespace.configuration')}</span> <span style={{ color: '#c7254e' }}> {res.configCount} / {res.quota} </span> </p> <p> <span style={{ color: '#999', marginRight: 5 }}>{aliwareIntl.get('nacos.page.configdetail.Description')}</span> <span style={{ color: '#c7254e' }}> {res.namespaceDesc} </span> </p> </div> </div> }); } }, complete: () => { this.closeLoading(); } }); } removeNamespace(record) { // let serverId = getParams('serverId') || 'center'; Dialog.confirm({ title: aliwareIntl.get('nacos.page.namespace.remove_the_namespace'), content: <div style={{ marginTop: '-20px' }}> <h3>{aliwareIntl.get('nacos.page.namespace.sure_you_want_to_delete_the_following_namespaces?')}</h3> <p> <span style={{ color: '#999', marginRight: 5 }}>{aliwareIntl.get('nacos.page.namespace.namespace_name')}</span> <span style={{ color: '#c7254e' }}> {record.namespaceShowName} </span> </p> <p> <span style={{ color: '#999', marginRight: 5 }}>{aliwareIntl.get('nacos.page.namespace.namespace_ID')}</span> <span style={{ color: '#c7254e' }}> {record.namespace} </span> </p> </div>, language: aliwareIntl.currentLanguageCode || 'zh-cn', onOk: () => { let url = `/nacos/v1/console/namespaces?namespaceId=${record.namespace}`; request({ url: url, type: 'delete', success: res => { let _payload = {}; _payload.title = aliwareIntl.get('com.alibaba.nacos.page.configurationManagement.configuration_management'); if (res === true) { let urlnamespace = getParams('namespace'); if (record.namespace === urlnamespace) { setParams('namespace', this.state.defaultNamespace); } Dialog.confirm({ language: aliwareIntl.currentLanguageCode || 'zh-cn', content: aliwareIntl.get('nacos.page.namespace._Remove_the_namespace_success'), title: aliwareIntl.get('nacos.page.namespace.deleted_successfully') }); } else { Dialog.confirm({ language: aliwareIntl.currentLanguageCode || 'zh-cn', content: res.message, title: "删除失败" }); } this.getNameSpaces(); } }); } }); } refreshNameSpace() { request({ type: 'get', url: `/nacos/v1/console/namespaces`, success: res => { if (res.code === 200) { window.namespaceList = res.data; } }, error: res => { window.namespaceList = [{ "namespace": "", "namespaceShowName": "公共空间", "type": 0 }];; } }); } openToEdit(record) { this.refs['editgroup'].openDialog(record); } renderOption(value, index, record) { let _delinfo = <a onClick={this.removeNamespace.bind(this, record)} style={{ marginRight: 10 }}>{aliwareIntl.get('com.alibaba.nacos.page.namespace.delete')}</a>; if (record.type === 1 || record.type === 0) { _delinfo = <span style={{ marginRight: 10, cursor: 'not-allowed' }} disabled={true}>{aliwareIntl.get('com.alibaba.nacos.page.namespace.delete')}</span>; } let _detailinfo = <a onClick={this.detailNamespace.bind(this, record)} style={{ marginRight: 10 }}>{aliwareIntl.get('nacos.page.namespace.details')}</a>; let _editinfo = <a onClick={this.openToEdit.bind(this, record)}>{aliwareIntl.get('com.alibaba.nacos.page.namespace.edit')}</a>; if (record.type === 0 || record.type === 1) { _editinfo = <span style={{ marginRight: 10, cursor: 'not-allowed' }} disabled={true}>{aliwareIntl.get('com.alibaba.nacos.page.namespace.edit')}</span>; } return <div> {_detailinfo} {_delinfo} {_editinfo} </div>; } addNameSpace() { this.refs['newnamespace'].openDialog(this.state.dataSource); } renderName(value, index, record) { let name = record.namespaceShowName; if (record.type === 0) { name = aliwareIntl.get('com.alibaba.nacos.page.namespace.public'); } return <div>{name}</div>; } renderConfigCount(value, index, record) { return <div>{value} / {record.quota}</div>; } render() { const pubnodedata = aliwareIntl.get('pubnodata'); const locale = { empty: pubnodedata }; return <div style={{ padding: 10 }} className='clearfix'> <RegionGroup left={aliwareIntl.get('nacos.page.namespace.Namespace')} /> <div className="fusion-demo"> <Loading shape="flower" tip="Loading..." color="#333" style={{ width: '100%' }} visible={this.state.loading}> <div> <div style={{ textAlign: 'right', marginBottom: 10 }}> <Button type="primary" style={{ marginRight: 0, marginTop: 10 }} onClick={this.addNameSpace.bind(this)}>{aliwareIntl.get('com.alibaba.nacos.page.namespace.add')}</Button> </div> <div> <Table dataSource={this.state.dataSource} locale={locale} language={aliwareIntl.currentLanguageCode}> <Table.Column title={aliwareIntl.get('com.alibaba.nacos.page.namespace.namespace_names')} dataIndex="namespaceShowName" cell={this.renderName.bind(this)} /> <Table.Column title={aliwareIntl.get('nacos.page.namespace.namespace_number')} dataIndex="namespace" /> <Table.Column title={aliwareIntl.get('com.alibaba.nacos.page.namespace.configuration')} dataIndex="configCount" cell={this.renderConfigCount.bind(this)} /> <Table.Column title={aliwareIntl.get('com.alibaba.nacos.page.namespace.operation')} dataIndex="time" cell={this.renderOption.bind(this)} /> </Table> </div> </div> <DeleteDialog ref="delete" /> <NewNameSpace ref={'newnamespace'} getNameSpaces={this.getNameSpaces.bind(this)} /> <EditorNameSpace ref={'editgroup'} getNameSpaces={this.getNameSpaces.bind(this)} /> </Loading> </div> </div>; } } /*****************************此行为标记行, 请勿删和修改此行, 主体代码请写在此行上面的class中, 组件导出语句及其他信息请写在此行下面*****************************/ export default NameSpace;
$(document).on({ ajaxStart: function () { $("body").addClass("loading"); }, ajaxStop: function () { $("body").removeClass("loading"); }, }); $(() => { getTechnicalReports(); }); /*Funcion para recuperar las ordenes de trabajo*/ getTechnicalReports = () => { let xhr = new XMLHttpRequest(); xhr.open("get", `${host_url}/api/tmGetTechnicalReport`); xhr.responseType = "json"; xhr.addEventListener("load", () => { if (xhr.status === 200) { let data = xhr.response; console.log(data); if(data){ $aux=[]; data.forEach((item)=>{ validation = JSON.parse(item.details); if(validation){ let date; if(validation.date_technical_report) date = validation.date_technical_report; else date = 'Pendiente'; if(validation.check_technical == 'true'){ if(validation.check_adm == 'false' || validation.check_adm == '') { report = { number_ot : item.number_ot, date : date, client: item.client, component: item.component, service : item.service, check_technical: 'Realizado', check_adm: 'No Aprobado', time_init: item.time_init, aux: item.aux, time_end: item.time_end, } $aux.push(report); } }else{ report = { number_ot : item.number_ot, date : date, client: item.client, component: item.component, service : item.service, check_technical: 'No Realizado', check_adm: 'No Aprobado', time_init: item.time_init, aux: item.aux, time_end: item.time_end, } $aux.push(report); } } }); tabla.clear(); tabla.rows.add($aux); tabla.order( [ 5, 'asc' ] ).draw(); } } else { swal({ title: "Error", icon: "error", text: "Error al obtener los reportes técnicos", }); } }); xhr.send(); }; /*Constante para rellenar las filas de la tabla: lista de ordenes de trabajo*/ const tabla = $('#tableTechnicalReports').DataTable({ // searching: true, language: { url: "//cdn.datatables.net/plug-ins/1.10.20/i18n/Spanish.json", }, "columnDefs": [ { className: "text-center", "targets": [7] , }, { className: "text-center", "targets": [8] , }, { "width": "5%", "targets": 0 }, { "width": "10%", "targets": 1 }, { "width": "20%", "targets": 2 }, { "width": "10%", "targets": 3 }, { "width": "10%", "targets": 4 }, { "width": "10%", "targets": 5 }, { "width": "10%", "targets": 6 }, { "width": "10%", "targets": 7 }, { "width": "10%", "targets": 8 }, ], columns: [ { data: "number_ot"}, { data: "date" }, { data: "client" }, { data: "component" }, { data: "service" }, { data: "check_technical" }, { data: "check_adm" }, { defaultContent: "tec", "render": function (data, type, row){ if(row.check_technical === 'Realizado'){ return `<button type='button' class='btn btn-primary'> Finalizado </button>` /* }else{ if(row.time_init){ if(row.aux){ return `<button name='tr_btn_play_continue' class="btn btn-success rounded-circle"><i class="fas fa-play"></i></button>` }else{ return `<button name='tr_btn_stop' class="btn btn-warning rounded-circle"><i class="fas fa-pause"></i></button>` } }else{ return `<button name='tr_btn_play' class="btn btn-success rounded-circle"><i class="fas fa-play"></i></button>` } } */ }else{ if(row.time_init){ return `<button type='button' class='btn btn-warning'> En proceso </button>` }else{ return `<button name='tr_btn_play' class="btn btn-success rounded-circle"><i class="fas fa-play"></i></button>` } } } }, { defaultContent: "oc", "render": function (data, type, row){ if(row.check_technical === 'Realizado'){ return `<button type='button' name='btn_tr' class='btn btn-primary'> Ver informe <i class="fas fa-search"></i> </button>` }else{ if(row.time_init){ if(row.aux){ return `<button type='button' name='btn_tr' class='btn btn-primary'> Ver informe <i class="fas fa-search"></i> </button>` }else{ return `<button type='button' name='btn_tr' class='btn btn-warning'>Realizar<i class="fas fa-pencil-alt"></i></button>` } }else{ return `<button type='button' name='btn_tr' class='btn btn-primary'> Ver informe <i class="fas fa-search"></i> </button>` } } } }, { defaultContent: `<button type='button' name='btn_images' class='btn btn-primary'> Imágenes <i class="fas fa-images"></i> </button>` }, ], }); $("#tableTechnicalReports").on("click", "button", function () { let data = tabla.row($(this).parents("tr")).data(); if ($(this)[0].name == "btn_tr") { window.location.assign(host_url+`tmAdminViewTechnicalReport/${data.number_ot}`); }else if($(this)[0].name == "tr_btn_play"){ show_play(data); }else if($(this)[0].name == "tr_btn_stop"){ show_stop(data); }else if($(this)[0].name == "tr_btn_play_continue"){ show_continue(data); }else if($(this)[0].name == "btn_images"){ let ot = data.number_ot; let url = 'adminImages'+'?ot='+ot; window.location.assign(host_url+url); } }); show_play = (data) =>{ swal({ title: `Comenzar Informe Técnico`, icon: "warning", text: `¿Esta seguro de comenzar el informe técnico asociado a la OT ${data.number_ot}"?`, buttons: { confirm: { text: `Confirmar`, value: "play", }, cancel: { text: "Cancelar", value: "cancelar", visible: true, }, }, }).then((action) => { if (action == "play") { chronometer(data, 'iniciado'); } else { swal.close(); } }); } /*Función para preparar la información a des/habilitar*/ show_continue = (data) =>{ swal({ title: `Continuar Informe Técnico`, icon: "warning", text: `¿Esta seguro de reanudar el informe técnico asociado a la OT ${data.number_ot}"?`, buttons: { confirm: { text: `Confirmar`, value: "continue", }, cancel: { text: "Cancelar", value: "cancelar", visible: true, }, }, }).then((action) => { if (action == "continue") { chronometer(data, 'reanudado'); } else { swal.close(); } }); } /*Función para preparar la información a des/habilitar*/ show_stop = (data) =>{ swal({ title: `Pausar el Informe Técnico`, icon: "warning", text: `¿Esta seguro de pausar el informe técnico asociado a la OT ${data.number_ot}"?`, buttons: { confirm: { text: `Confirmar`, value: "stop", }, cancel: { text: "Cancelar", value: "cancelar", visible: true, }, }, }).then((action) => { if (action == "stop") { chronometer(data, 'detenido'); } else { swal.close(); } }); } chronometer = (data, msg) =>{ datos = { ot_id : data.number_ot, msg: msg, name : 'technical_report' } $.ajax({ type: "POST", url: host_url + "api/chronometer", data: {datos}, dataType: "json", success: (result) => { swal({ title: "Éxito!", icon: "success", text: result.msg, button: "OK", }).then(() => { getTechnicalReports(); }); }, error: () => { swal({ title: "Error", icon: "error", text: "No se pudo encontrar el recurso", }).then(() => { $("body").removeClass("loading"); }); }, }); }
import { _getProvider as t, getApp as e, _removeServiceInstance as n, _registerComponent as r, registerVersion as s, SDK_VERSION as i } from "@firebase/app"; import { Component as o } from "@firebase/component"; import { createMockUserToken as u, getModularInstance as c } from "@firebase/util"; import { Logger as a, LogLevel as h } from "@firebase/logger"; /** * @license * Copyright 2017 Google LLC * * 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. */ let l = "8.10.0"; /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Simple wrapper around a nullable UID. Mostly exists to make code more * readable. */ class f { constructor(t) { this.uid = t; } isAuthenticated() { return null != this.uid; } /** * Returns a key representing this user, suitable for inclusion in a * dictionary. */ toKey() { return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user"; } isEqual(t) { return t.uid === this.uid; } } /** A user with a null UID. */ f.UNAUTHENTICATED = new f(null), // TODO(mikelehen): Look into getting a proper uid-equivalent for // non-FirebaseAuth providers. f.GOOGLE_CREDENTIALS = new f("google-credentials-uid"), f.FIRST_PARTY = new f("first-party-uid"), f.MOCK_USER = new f("mock-user"); /** * @license * Copyright 2017 Google LLC * * 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. */ const d = new a("@firebase/firestore"); /** * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). * * @param logLevel - The verbosity you set for activity and error logging. Can * be any of the following values: * * <ul> * <li>`debug` for the most verbose logging level, primarily for * debugging.</li> * <li>`error` to log errors only.</li> * <li><code>`silent` to turn off logging.</li> * </ul> */ function w(t) { d.setLogLevel(t); } function m(t, ...e) { if (d.logLevel <= h.DEBUG) { const n = e.map(_); d.debug(`Firestore (${l}): ${t}`, ...n); } } function p(t, ...e) { if (d.logLevel <= h.ERROR) { const n = e.map(_); d.error(`Firestore (${l}): ${t}`, ...n); } } function y(t, ...e) { if (d.logLevel <= h.WARN) { const n = e.map(_); d.warn(`Firestore (${l}): ${t}`, ...n); } } /** * Converts an additional log parameter to a string representation. */ function _(t) { if ("string" == typeof t) return t; try { return e = t, JSON.stringify(e); } catch (e) { // Converting to JSON failed, just log the object directly return t; } /** * @license * Copyright 2020 Google LLC * * 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. */ /** Formats an object as a JSON string, suitable for logging. */ var e; } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Unconditionally fails, throwing an Error with the given message. * Messages are stripped in production builds. * * Returns `never` and can be used in expressions: * @example * let futureVar = fail('not implemented yet'); */ function g(t = "Unexpected state") { // Log the failure in addition to throw an exception, just in case the // exception is swallowed. const e = `FIRESTORE (${l}) INTERNAL ASSERTION FAILED: ` + t; // NOTE: We don't use FirestoreError here because these are internal failures // that cannot be handled by the user. (Also it would create a circular // dependency between the error and assert modules which doesn't work.) throw p(e), new Error(e); } /** * Fails if the given assertion condition is false, throwing an Error with the * given message if it did. * * Messages are stripped in production builds. */ function v(t, e) { t || g(); } /** * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an * instance of `T` before casting. */ function b(t, // eslint-disable-next-line @typescript-eslint/no-explicit-any e) { return t; } /** * @license * Copyright 2017 Google LLC * * 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. */ const E = "ok", T = "cancelled", I = "unknown", A = "invalid-argument", P = "deadline-exceeded", R = "not-found", V = "already-exists", N = "permission-denied", D = "unauthenticated", $ = "resource-exhausted", F = "failed-precondition", S = "aborted", q = "out-of-range", x = "unimplemented", O = "internal", C = "unavailable", L = "data-loss"; /** An error returned by a Firestore operation. */ class U extends Error { /** @hideconstructor */ constructor( /** * The backend error code associated with this error. */ t, /** * A custom error description. */ e) { super(e), this.code = t, this.message = e, /** The custom name for all FirestoreErrors. */ this.name = "FirebaseError", // HACK: We write a toString property directly because Error is not a real // class and so inheritance does not work correctly. We could alternatively // do the same "back-door inheritance" trick that FirebaseError does. this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`; } } /** * @license * Copyright 2017 Google LLC * * 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. */ class k { constructor() { this.promise = new Promise(((t, e) => { this.resolve = t, this.reject = e; })); } } /** * @license * Copyright 2017 Google LLC * * 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. */ class j { constructor(t, e) { this.user = e, this.type = "OAuth", this.authHeaders = {}, // Set the headers using Object Literal notation to avoid minification this.authHeaders.Authorization = `Bearer ${t}`; } } /** A CredentialsProvider that always yields an empty token. */ class M { constructor() { /** * Stores the listener registered with setChangeListener() * This isn't actually necessary since the UID never changes, but we use this * to verify the listen contract is adhered to in tests. */ this.changeListener = null; } getToken() { return Promise.resolve(null); } invalidateToken() {} setChangeListener(t, e) { this.changeListener = e, // Fire with initial user. t.enqueueRetryable((() => e(f.UNAUTHENTICATED))); } removeChangeListener() { this.changeListener = null; } } /** * A CredentialsProvider that always returns a constant token. Used for * emulator token mocking. */ class B { constructor(t) { this.token = t, /** * Stores the listener registered with setChangeListener() * This isn't actually necessary since the UID never changes, but we use this * to verify the listen contract is adhered to in tests. */ this.changeListener = null; } getToken() { return Promise.resolve(this.token); } invalidateToken() {} setChangeListener(t, e) { this.changeListener = e, // Fire with initial user. t.enqueueRetryable((() => e(this.token.user))); } removeChangeListener() { this.changeListener = null; } } class Q { constructor(t) { /** Tracks the current User. */ this.currentUser = f.UNAUTHENTICATED, /** Promise that allows blocking on the initialization of Firebase Auth. */ this.t = new k, /** * Counter used to detect if the token changed while a getToken request was * outstanding. */ this.i = 0, this.forceRefresh = !1, this.auth = null, this.asyncQueue = null, this.o = () => { this.i++, this.currentUser = this.u(), this.t.resolve(), this.changeListener && this.asyncQueue.enqueueRetryable((() => this.changeListener(this.currentUser))); }; const e = t => { m("FirebaseCredentialsProvider", "Auth detected"), this.auth = t, this.auth.addAuthTokenListener(this.o); }; t.onInit((t => e(t))), // Our users can initialize Auth right after Firestore, so we give it // a chance to register itself with the component framework before we // determine whether to start up in unauthenticated mode. setTimeout((() => { if (!this.auth) { const n = t.getImmediate({ optional: !0 }); n ? e(n) : ( // If auth is still not available, proceed with `null` user m("FirebaseCredentialsProvider", "Auth not yet detected"), this.t.resolve()); } }), 0); } getToken() { // Take note of the current value of the tokenCounter so that this method // can fail (with an ABORTED error) if there is a token change while the // request is outstanding. const t = this.i, e = this.forceRefresh; return this.forceRefresh = !1, this.auth ? this.auth.getToken(e).then((e => // Cancel the request since the token changed while the request was // outstanding so the response is potentially for a previous user (which // user, we can't be sure). this.i !== t ? (m("FirebaseCredentialsProvider", "getToken aborted due to token change."), this.getToken()) : e ? (v("string" == typeof e.accessToken), new j(e.accessToken, this.currentUser)) : null)) : Promise.resolve(null); } invalidateToken() { this.forceRefresh = !0; } setChangeListener(t, e) { this.asyncQueue = t, // Blocks the AsyncQueue until the next user is available. this.asyncQueue.enqueueRetryable((async () => { await this.t.promise, await e(this.currentUser), this.changeListener = e; })); } removeChangeListener() { this.auth && this.auth.removeAuthTokenListener(this.o), this.changeListener = () => Promise.resolve(); } // Auth.getUid() can return null even with a user logged in. It is because // getUid() is synchronous, but the auth code populating Uid is asynchronous. // This method should only be called in the AuthTokenListener callback // to guarantee to get the actual user. u() { const t = this.auth && this.auth.getUid(); return v(null === t || "string" == typeof t), new f(t); } } /* * FirstPartyToken provides a fresh token each time its value * is requested, because if the token is too old, requests will be rejected. * Technically this may no longer be necessary since the SDK should gracefully * recover from unauthenticated errors (see b/33147818 for context), but it's * safer to keep the implementation as-is. */ class z { constructor(t, e, n) { this.h = t, this.l = e, this.m = n, this.type = "FirstParty", this.user = f.FIRST_PARTY; } get authHeaders() { const t = { "X-Goog-AuthUser": this.l }, e = this.h.auth.getAuthHeaderValueForFirstParty([]); // Use array notation to prevent minification return e && (t.Authorization = e), this.m && (t["X-Goog-Iam-Authorization-Token"] = this.m), t; } } /* * Provides user credentials required for the Firestore JavaScript SDK * to authenticate the user, using technique that is only available * to applications hosted by Google. */ class W { constructor(t, e, n) { this.h = t, this.l = e, this.m = n; } getToken() { return Promise.resolve(new z(this.h, this.l, this.m)); } setChangeListener(t, e) { // Fire with initial uid. t.enqueueRetryable((() => e(f.FIRST_PARTY))); } removeChangeListener() {} invalidateToken() {} } /** * Builds a CredentialsProvider depending on the type of * the credentials passed in. */ /** * @license * Copyright 2017 Google LLC * * 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. */ class G { /** * Constructs a DatabaseInfo using the provided host, databaseId and * persistenceKey. * * @param databaseId - The database to use. * @param appId - The Firebase App Id. * @param persistenceKey - A unique identifier for this Firestore's local * storage (used in conjunction with the databaseId). * @param host - The Firestore backend host to connect to. * @param ssl - Whether to use SSL when connecting. * @param forceLongPolling - Whether to use the forceLongPolling option * when using WebChannel as the network transport. * @param autoDetectLongPolling - Whether to use the detectBufferingProxy * option when using WebChannel as the network transport. * @param useFetchStreams Whether to use the Fetch API instead of * XMLHTTPRequest */ constructor(t, e, n, r, s, i, o, u) { this.databaseId = t, this.appId = e, this.persistenceKey = n, this.host = r, this.ssl = s, this.forceLongPolling = i, this.autoDetectLongPolling = o, this.useFetchStreams = u; } } /** The default database name for a project. */ /** Represents the database ID a Firestore client is associated with. */ class H { constructor(t, e) { this.projectId = t, this.database = e || "(default)"; } get isDefaultDatabase() { return "(default)" === this.database; } isEqual(t) { return t instanceof H && t.projectId === this.projectId && t.database === this.database; } } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Path represents an ordered sequence of string segments. */ class Y { constructor(t, e, n) { void 0 === e ? e = 0 : e > t.length && g(), void 0 === n ? n = t.length - e : n > t.length - e && g(), this.segments = t, this.offset = e, this.len = n; } get length() { return this.len; } isEqual(t) { return 0 === Y.comparator(this, t); } child(t) { const e = this.segments.slice(this.offset, this.limit()); return t instanceof Y ? t.forEach((t => { e.push(t); })) : e.push(t), this.construct(e); } /** The index of one past the last segment of the path. */ limit() { return this.offset + this.length; } popFirst(t) { return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t); } popLast() { return this.construct(this.segments, this.offset, this.length - 1); } firstSegment() { return this.segments[this.offset]; } lastSegment() { return this.get(this.length - 1); } get(t) { return this.segments[this.offset + t]; } isEmpty() { return 0 === this.length; } isPrefixOf(t) { if (t.length < this.length) return !1; for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1; return !0; } isImmediateParentOf(t) { if (this.length + 1 !== t.length) return !1; for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1; return !0; } forEach(t) { for (let e = this.offset, n = this.limit(); e < n; e++) t(this.segments[e]); } toArray() { return this.segments.slice(this.offset, this.limit()); } static comparator(t, e) { const n = Math.min(t.length, e.length); for (let r = 0; r < n; r++) { const n = t.get(r), s = e.get(r); if (n < s) return -1; if (n > s) return 1; } return t.length < e.length ? -1 : t.length > e.length ? 1 : 0; } } /** * A slash-separated path for navigating resources (documents and collections) * within Firestore. */ class K extends Y { construct(t, e, n) { return new K(t, e, n); } canonicalString() { // NOTE: The client is ignorant of any path segments containing escape // sequences (e.g. __id123__) and just passes them through raw (they exist // for legacy reasons and should not be used frequently). return this.toArray().join("/"); } toString() { return this.canonicalString(); } /** * Creates a resource path from the given slash-delimited string. If multiple * arguments are provided, all components are combined. Leading and trailing * slashes from all components are ignored. */ static fromString(...t) { // NOTE: The client is ignorant of any path segments containing escape // sequences (e.g. __id123__) and just passes them through raw (they exist // for legacy reasons and should not be used frequently). const e = []; for (const n of t) { if (n.indexOf("//") >= 0) throw new U(A, `Invalid segment (${n}). Paths must not contain // in them.`); // Strip leading and traling slashed. e.push(...n.split("/").filter((t => t.length > 0))); } return new K(e); } static emptyPath() { return new K([]); } } const J = /^[_a-zA-Z][_a-zA-Z0-9]*$/; /** A dot-separated path for navigating sub-objects within a document. */ class Z extends Y { construct(t, e, n) { return new Z(t, e, n); } /** * Returns true if the string could be used as a segment in a field path * without escaping. */ static isValidIdentifier(t) { return J.test(t); } canonicalString() { return this.toArray().map((t => (t = t.replace(/\\/g, "\\\\").replace(/`/g, "\\`"), Z.isValidIdentifier(t) || (t = "`" + t + "`"), t))).join("."); } toString() { return this.canonicalString(); } /** * Returns true if this field references the key of a document. */ isKeyField() { return 1 === this.length && "__name__" === this.get(0); } /** * The field designating the key of a document. */ static keyField() { return new Z([ "__name__" ]); } /** * Parses a field string from the given server-formatted string. * * - Splitting the empty string is not allowed (for now at least). * - Empty segments within the string (e.g. if there are two consecutive * separators) are not allowed. * * TODO(b/37244157): we should make this more strict. Right now, it allows * non-identifier path components, even if they aren't escaped. */ static fromServerFormat(t) { const e = []; let n = "", r = 0; const s = () => { if (0 === n.length) throw new U(A, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`); e.push(n), n = ""; }; let i = !1; for (;r < t.length; ) { const e = t[r]; if ("\\" === e) { if (r + 1 === t.length) throw new U(A, "Path has trailing escape character: " + t); const e = t[r + 1]; if ("\\" !== e && "." !== e && "`" !== e) throw new U(A, "Path has invalid escape sequence: " + t); n += e, r += 2; } else "`" === e ? (i = !i, r++) : "." !== e || i ? (n += e, r++) : (s(), r++); } if (s(), i) throw new U(A, "Unterminated ` in path: " + t); return new Z(e); } static emptyPath() { return new Z([]); } } /** * @license * Copyright 2017 Google LLC * * 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. */ class X { constructor(t) { this.path = t; } static fromPath(t) { return new X(K.fromString(t)); } static fromName(t) { return new X(K.fromString(t).popFirst(5)); } /** Returns true if the document is in the specified collectionId. */ hasCollectionId(t) { return this.path.length >= 2 && this.path.get(this.path.length - 2) === t; } isEqual(t) { return null !== t && 0 === K.comparator(this.path, t.path); } toString() { return this.path.toString(); } static comparator(t, e) { return K.comparator(t.path, e.path); } static isDocumentKey(t) { return t.length % 2 == 0; } /** * Creates and returns a new document key with the given segments. * * @param segments - The segments of the path to the document * @returns A new instance of DocumentKey */ static fromSegments(t) { return new X(new K(t.slice())); } } /** * @license * Copyright 2017 Google LLC * * 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. */ function tt(t, e, n) { if (!n) throw new U(A, `Function ${t}() cannot be called with an empty ${e}.`); } /** * Validates that two boolean options are not set at the same time. */ /** * Validates that `path` refers to a document (indicated by the fact it contains * an even numbers of segments). */ function et(t) { if (!X.isDocumentKey(t)) throw new U(A, `Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`); } /** * Validates that `path` refers to a collection (indicated by the fact it * contains an odd numbers of segments). */ function nt(t) { if (X.isDocumentKey(t)) throw new U(A, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`); } /** * Returns true if it's a non-null object without a custom prototype * (i.e. excludes Array, Date, etc.). */ /** Returns a string describing the type / value of the provided input. */ function rt(t) { if (void 0 === t) return "undefined"; if (null === t) return "null"; if ("string" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`), JSON.stringify(t); if ("number" == typeof t || "boolean" == typeof t) return "" + t; if ("object" == typeof t) { if (t instanceof Array) return "an array"; { const e = /** Hacky method to try to get the constructor name for an object. */ function(t) { if (t.constructor) { const e = /function\s+([^\s(]+)\s*\(/.exec(t.constructor.toString()); if (e && e.length > 1) return e[1]; } return null; } /** * Casts `obj` to `T`, optionally unwrapping Compat types to expose the * underlying instance. Throws if `obj` is not an instance of `T`. * * This cast is used in the Lite and Full SDK to verify instance types for * arguments passed to the public API. */ (t); return e ? `a custom ${e} object` : "an object"; } } return "function" == typeof t ? "a function" : g(); } function st(t, // eslint-disable-next-line @typescript-eslint/no-explicit-any e) { if ("_delegate" in t && ( // Unwrap Compat types // eslint-disable-next-line @typescript-eslint/no-explicit-any t = t._delegate), !(t instanceof e)) { if (e.name === t.constructor.name) throw new U(A, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?"); { const n = rt(t); throw new U(A, `Expected type '${e.name}', but it was: ${n}`); } } return t; } function it(t, e) { if (e <= 0) throw new U(A, `Function ${t}() requires a positive number, but it was: ${e}.`); } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Returns whether a variable is either undefined or null. */ function ot(t) { return null == t; } /** Returns whether the value represents -0. */ function ut(t) { // Detect if the value is -0.0. Based on polyfill from // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is return 0 === t && 1 / t == -1 / 0; } /** * Returns whether a value is an integer and in the safe integer range * @param value - The value to test for being an integer and in the safe range */ /** * @license * Copyright 2020 Google LLC * * 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. */ const ct = { BatchGetDocuments: "batchGet", Commit: "commit", RunQuery: "runQuery" }; /** * Maps RPC names to the corresponding REST endpoint name. * * We use array notation to avoid mangling. */ /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Error Codes describing the different ways GRPC can fail. These are copied * directly from GRPC's sources here: * * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h * * Important! The names of these identifiers matter because the string forms * are used for reverse lookups from the webchannel stream. Do NOT change the * names of these identifiers or change this into a const enum. */ var at, ht; /** * Converts an HTTP Status Code to the equivalent error code. * * @param status - An HTTP Status Code, like 200, 404, 503, etc. * @returns The equivalent Code. Unknown status codes are mapped to * Code.UNKNOWN. */ function lt(t) { if (void 0 === t) return p("RPC_ERROR", "HTTP error has no status"), I; // The canonical error codes for Google APIs [1] specify mapping onto HTTP // status codes but the mapping is not bijective. In each case of ambiguity // this function chooses a primary error. // [1] // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto switch (t) { case 200: // OK return E; case 400: // Bad Request return F; // Other possibilities based on the forward mapping // return Code.INVALID_ARGUMENT; // return Code.OUT_OF_RANGE; case 401: // Unauthorized return D; case 403: // Forbidden return N; case 404: // Not Found return R; case 409: // Conflict return S; // Other possibilities: // return Code.ALREADY_EXISTS; case 416: // Range Not Satisfiable return q; case 429: // Too Many Requests return $; case 499: // Client Closed Request return T; case 500: // Internal Server Error return I; // Other possibilities: // return Code.INTERNAL; // return Code.DATA_LOSS; case 501: // Unimplemented return x; case 503: // Service Unavailable return C; case 504: // Gateway Timeout return P; default: return t >= 200 && t < 300 ? E : t >= 400 && t < 500 ? F : t >= 500 && t < 600 ? O : I; } } /** * @license * Copyright 2020 Google LLC * * 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. */ /** * A Rest-based connection that relies on the native HTTP stack * (e.g. `fetch` or a polyfill). */ (ht = at || (at = {}))[ht.OK = 0] = "OK", ht[ht.CANCELLED = 1] = "CANCELLED", ht[ht.UNKNOWN = 2] = "UNKNOWN", ht[ht.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT", ht[ht.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", ht[ht.NOT_FOUND = 5] = "NOT_FOUND", ht[ht.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", ht[ht.PERMISSION_DENIED = 7] = "PERMISSION_DENIED", ht[ht.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", ht[ht.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED", ht[ht.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", ht[ht.ABORTED = 10] = "ABORTED", ht[ht.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", ht[ht.UNIMPLEMENTED = 12] = "UNIMPLEMENTED", ht[ht.INTERNAL = 13] = "INTERNAL", ht[ht.UNAVAILABLE = 14] = "UNAVAILABLE", ht[ht.DATA_LOSS = 15] = "DATA_LOSS"; class ft extends /** * Base class for all Rest-based connections to the backend (WebChannel and * HTTP). */ class { constructor(t) { this.databaseInfo = t, this.databaseId = t.databaseId; const e = t.ssl ? "https" : "http"; this.p = e + "://" + t.host, this.g = "projects/" + this.databaseId.projectId + "/databases/" + this.databaseId.database + "/documents"; } v(t, e, n, r) { const s = this.T(t, e); m("RestConnection", "Sending: ", s, n); const i = {}; return this.I(i, r), this.A(t, s, i, n).then((t => (m("RestConnection", "Received: ", t), t)), (e => { throw y("RestConnection", `${t} failed with error: `, e, "url: ", s, "request:", n), e; })); } P(t, e, n, r) { // The REST API automatically aggregates all of the streamed results, so we // can just use the normal invoke() method. return this.v(t, e, n, r); } /** * Modifies the headers for a request, adding any authorization token if * present and any additional headers for the request. */ I(t, e) { if (t["X-Goog-Api-Client"] = "gl-js/ fire/" + l, // Content-Type: text/plain will avoid preflight requests which might // mess with CORS and redirects by proxies. If we add custom headers // we will need to change this code to potentially use the $httpOverwrite // parameter supported by ESF to avoid triggering preflight requests. t["Content-Type"] = "text/plain", this.databaseInfo.appId && (t["X-Firebase-GMPID"] = this.databaseInfo.appId), e) for (const n in e.authHeaders) e.authHeaders.hasOwnProperty(n) && (t[n] = e.authHeaders[n]); } T(t, e) { const n = ct[t]; return `${this.p}/v1/${e}:${n}`; } } { /** * @param databaseInfo - The connection info. * @param fetchImpl - `fetch` or a Polyfill that implements the fetch API. */ constructor(t, e) { super(t), this.R = e; } V(t, e) { throw new Error("Not supported by FetchConnection"); } async A(t, e, n, r) { const s = JSON.stringify(r); let i; try { i = await this.R(e, { method: "POST", headers: n, body: s }); } catch (t) { throw new U(lt(t.status), "Request failed with error: " + t.statusText); } if (!i.ok) throw new U(lt(i.status), "Request failed with error: " + i.statusText); return i.json(); } } /** * @license * Copyright 2020 Google LLC * * 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. */ /** Initializes the HTTP connection for the REST API. */ /** * @license * Copyright 2020 Google LLC * * 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. */ /** * Generates `nBytes` of random bytes. * * If `nBytes < 0` , an error will be thrown. */ function dt(t) { // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available. const e = // eslint-disable-next-line @typescript-eslint/no-explicit-any "undefined" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(t); if (e && "function" == typeof e.getRandomValues) e.getRandomValues(n); else // Falls back to Math.random for (let e = 0; e < t; e++) n[e] = Math.floor(256 * Math.random()); return n; } /** * @license * Copyright 2017 Google LLC * * 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. */ class wt { static N() { // Alphanumeric characters const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = Math.floor(256 / t.length) * t.length; // The largest byte value that is a multiple of `char.length`. let n = ""; for (;n.length < 20; ) { const r = dt(40); for (let s = 0; s < r.length; ++s) // Only accept values that are [0, maxMultiple), this ensures they can // be evenly mapped to indices of `chars` via a modulo operation. n.length < 20 && r[s] < e && (n += t.charAt(r[s] % t.length)); } return n; } } function mt(t, e) { return t < e ? -1 : t > e ? 1 : 0; } /** Helper to compare arrays using isEqual(). */ function pt(t, e, n) { return t.length === e.length && t.every(((t, r) => n(t, e[r]))); } /** * @license * Copyright 2017 Google LLC * * 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. */ // The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z). /** * A `Timestamp` represents a point in time independent of any time zone or * calendar, represented as seconds and fractions of seconds at nanosecond * resolution in UTC Epoch time. * * It is encoded using the Proleptic Gregorian Calendar which extends the * Gregorian calendar backwards to year one. It is encoded assuming all minutes * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to * 9999-12-31T23:59:59.999999999Z. * * For examples and further specifications, refer to the * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. */ class yt { /** * Creates a new timestamp. * * @param seconds - The number of seconds of UTC time since Unix epoch * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to * 9999-12-31T23:59:59Z inclusive. * @param nanoseconds - The non-negative fractions of a second at nanosecond * resolution. Negative second values with fractions must still have * non-negative nanoseconds values that count forward in time. Must be * from 0 to 999,999,999 inclusive. */ constructor( /** * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. */ t, /** * The fractions of a second at nanosecond resolution.* */ e) { if (this.seconds = t, this.nanoseconds = e, e < 0) throw new U(A, "Timestamp nanoseconds out of range: " + e); if (e >= 1e9) throw new U(A, "Timestamp nanoseconds out of range: " + e); if (t < -62135596800) throw new U(A, "Timestamp seconds out of range: " + t); // This will break in the year 10,000. if (t >= 253402300800) throw new U(A, "Timestamp seconds out of range: " + t); } /** * Creates a new timestamp with the current date, with millisecond precision. * * @returns a new timestamp representing the current date. */ static now() { return yt.fromMillis(Date.now()); } /** * Creates a new timestamp from the given date. * * @param date - The date to initialize the `Timestamp` from. * @returns A new `Timestamp` representing the same point in time as the given * date. */ static fromDate(t) { return yt.fromMillis(t.getTime()); } /** * Creates a new timestamp from the given number of milliseconds. * * @param milliseconds - Number of milliseconds since Unix epoch * 1970-01-01T00:00:00Z. * @returns A new `Timestamp` representing the same point in time as the given * number of milliseconds. */ static fromMillis(t) { const e = Math.floor(t / 1e3), n = Math.floor(1e6 * (t - 1e3 * e)); return new yt(e, n); } /** * Converts a `Timestamp` to a JavaScript `Date` object. This conversion * causes a loss of precision since `Date` objects only support millisecond * precision. * * @returns JavaScript `Date` object representing the same point in time as * this `Timestamp`, with millisecond precision. */ toDate() { return new Date(this.toMillis()); } /** * Converts a `Timestamp` to a numeric timestamp (in milliseconds since * epoch). This operation causes a loss of precision. * * @returns The point in time corresponding to this timestamp, represented as * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. */ toMillis() { return 1e3 * this.seconds + this.nanoseconds / 1e6; } _compareTo(t) { return this.seconds === t.seconds ? mt(this.nanoseconds, t.nanoseconds) : mt(this.seconds, t.seconds); } /** * Returns true if this `Timestamp` is equal to the provided one. * * @param other - The `Timestamp` to compare against. * @returns true if this `Timestamp` is equal to the provided one. */ isEqual(t) { return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds; } /** Returns a textual representation of this Timestamp. */ toString() { return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")"; } /** Returns a JSON-serializable representation of this Timestamp. */ toJSON() { return { seconds: this.seconds, nanoseconds: this.nanoseconds }; } /** * Converts this object to a primitive string, which allows Timestamp objects * to be compared using the `>`, `<=`, `>=` and `>` operators. */ valueOf() { // This method returns a string of the form <seconds>.<nanoseconds> where // <seconds> is translated to have a non-negative value and both <seconds> // and <nanoseconds> are left-padded with zeroes to be a consistent length. // Strings with this format then have a lexiographical ordering that matches // the expected ordering. The <seconds> translation is done to avoid having // a leading negative sign (i.e. a leading '-' character) in its string // representation, which would affect its lexiographical ordering. const t = this.seconds - -62135596800; // Note: Up to 12 decimal digits are required to represent all valid // 'seconds' values. return String(t).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0"); } } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * A version of a document in Firestore. This corresponds to the version * timestamp, such as update_time or read_time. */ class _t { constructor(t) { this.timestamp = t; } static fromTimestamp(t) { return new _t(t); } static min() { return new _t(new yt(0, 0)); } compareTo(t) { return this.timestamp._compareTo(t.timestamp); } isEqual(t) { return this.timestamp.isEqual(t.timestamp); } /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() { // Convert to microseconds. return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3; } toString() { return "SnapshotVersion(" + this.timestamp.toString() + ")"; } toTimestamp() { return this.timestamp; } } /** * @license * Copyright 2017 Google LLC * * 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. */ function gt(t) { let e = 0; for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e++; return e; } function vt(t, e) { for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e(n, t[n]); } /** * @license * Copyright 2020 Google LLC * * 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. */ /** * Provides a set of fields that can be used to partially patch a document. * FieldMask is used in conjunction with ObjectValue. * Examples: * foo - Overwrites foo entirely with the provided value. If foo is not * present in the companion ObjectValue, the field is deleted. * foo.bar - Overwrites only the field bar of the object foo. * If foo is not an object, foo is replaced with an object * containing foo */ class bt { constructor(t) { this.fields = t, // TODO(dimond): validation of FieldMask // Sort the field mask to support `FieldMask.isEqual()` and assert below. t.sort(Z.comparator); } /** * Verifies that `fieldPath` is included by at least one field in this field * mask. * * This is an O(n) operation, where `n` is the size of the field mask. */ covers(t) { for (const e of this.fields) if (e.isPrefixOf(t)) return !0; return !1; } isEqual(t) { return pt(this.fields, t.fields, ((t, e) => t.isEqual(e))); } } /** * @license * Copyright 2020 Google LLC * * 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. */ /** Converts a Base64 encoded string to a binary string. */ /** * @license * Copyright 2020 Google LLC * * 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. */ /** * Immutable class that represents a "proto" byte string. * * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when * sent on the wire. This class abstracts away this differentiation by holding * the proto byte string in a common class that must be converted into a string * before being sent as a proto. */ class Et { constructor(t) { this.binaryString = t; } static fromBase64String(t) { const e = atob(t); return new Et(e); } static fromUint8Array(t) { const e = /** * Helper function to convert an Uint8array to a binary string. */ function(t) { let e = ""; for (let n = 0; n < t.length; ++n) e += String.fromCharCode(t[n]); return e; } /** * Helper function to convert a binary string to an Uint8Array. */ (t); return new Et(e); } toBase64() { return t = this.binaryString, btoa(t); /** Converts a binary string to a Base64 encoded string. */ var t; } toUint8Array() { return function(t) { const e = new Uint8Array(t.length); for (let n = 0; n < t.length; n++) e[n] = t.charCodeAt(n); return e; } /** * @license * Copyright 2020 Google LLC * * 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. */ // A RegExp matching ISO 8601 UTC timestamps with optional fraction. (this.binaryString); } approximateByteSize() { return 2 * this.binaryString.length; } compareTo(t) { return mt(this.binaryString, t.binaryString); } isEqual(t) { return this.binaryString === t.binaryString; } } Et.EMPTY_BYTE_STRING = new Et(""); const Tt = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/); /** * Converts the possible Proto values for a timestamp value into a "seconds and * nanos" representation. */ function It(t) { // The json interface (for the browser) will return an iso timestamp string, // while the proto js library (for node) will return a // google.protobuf.Timestamp instance. if (v(!!t), "string" == typeof t) { // The date string can have higher precision (nanos) than the Date class // (millis), so we do some custom parsing here. // Parse the nanos right out of the string. let e = 0; const n = Tt.exec(t); if (v(!!n), n[1]) { // Pad the fraction out to 9 digits (nanos). let t = n[1]; t = (t + "000000000").substr(0, 9), e = Number(t); } // Parse the date to get the seconds. const r = new Date(t); return { seconds: Math.floor(r.getTime() / 1e3), nanos: e }; } return { seconds: At(t.seconds), nanos: At(t.nanos) }; } /** * Converts the possible Proto types for numbers into a JavaScript number. * Returns 0 if the value is not numeric. */ function At(t) { // TODO(bjornick): Handle int64 greater than 53 bits. return "number" == typeof t ? t : "string" == typeof t ? Number(t) : 0; } /** Converts the possible Proto types for Blobs into a ByteString. */ function Pt(t) { return "string" == typeof t ? Et.fromBase64String(t) : Et.fromUint8Array(t); } /** * @license * Copyright 2020 Google LLC * * 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. */ /** * Represents a locally-applied ServerTimestamp. * * Server Timestamps are backed by MapValues that contain an internal field * `__type__` with a value of `server_timestamp`. The previous value and local * write time are stored in its `__previous_value__` and `__local_write_time__` * fields respectively. * * Notes: * - ServerTimestampValue instances are created as the result of applying a * transform. They can only exist in the local view of a document. Therefore * they do not need to be parsed or serialized. * - When evaluated locally (e.g. for snapshot.data()), they by default * evaluate to `null`. This behavior can be configured by passing custom * FieldValueOptions to value(). * - With respect to other ServerTimestampValues, they sort by their * localWriteTime. */ function Rt(t) { var e, n; return "server_timestamp" === (null === (n = ((null === (e = null == t ? void 0 : t.mapValue) || void 0 === e ? void 0 : e.fields) || {}).__type__) || void 0 === n ? void 0 : n.stringValue); } /** * Returns the value of the field before this ServerTimestamp was set. * * Preserving the previous values allows the user to display the last resoled * value until the backend responds with the timestamp. */ function Vt(t) { const e = t.mapValue.fields.__previous_value__; return Rt(e) ? Vt(e) : e; } /** * Returns the local time at which this timestamp was first set. */ function Nt(t) { const e = It(t.mapValue.fields.__local_write_time__.timestampValue); return new yt(e.seconds, e.nanos); } /** * @license * Copyright 2020 Google LLC * * 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. */ /** Extracts the backend's type order for the provided value. */ function Dt(t) { return "nullValue" in t ? 0 /* NullValue */ : "booleanValue" in t ? 1 /* BooleanValue */ : "integerValue" in t || "doubleValue" in t ? 2 /* NumberValue */ : "timestampValue" in t ? 3 /* TimestampValue */ : "stringValue" in t ? 5 /* StringValue */ : "bytesValue" in t ? 6 /* BlobValue */ : "referenceValue" in t ? 7 /* RefValue */ : "geoPointValue" in t ? 8 /* GeoPointValue */ : "arrayValue" in t ? 9 /* ArrayValue */ : "mapValue" in t ? Rt(t) ? 4 /* ServerTimestampValue */ : 10 /* ObjectValue */ : g(); } /** Tests `left` and `right` for equality based on the backend semantics. */ function $t(t, e) { const n = Dt(t); if (n !== Dt(e)) return !1; switch (n) { case 0 /* NullValue */ : return !0; case 1 /* BooleanValue */ : return t.booleanValue === e.booleanValue; case 4 /* ServerTimestampValue */ : return Nt(t).isEqual(Nt(e)); case 3 /* TimestampValue */ : return function(t, e) { if ("string" == typeof t.timestampValue && "string" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length) // Use string equality for ISO 8601 timestamps return t.timestampValue === e.timestampValue; const n = It(t.timestampValue), r = It(e.timestampValue); return n.seconds === r.seconds && n.nanos === r.nanos; }(t, e); case 5 /* StringValue */ : return t.stringValue === e.stringValue; case 6 /* BlobValue */ : return function(t, e) { return Pt(t.bytesValue).isEqual(Pt(e.bytesValue)); }(t, e); case 7 /* RefValue */ : return t.referenceValue === e.referenceValue; case 8 /* GeoPointValue */ : return function(t, e) { return At(t.geoPointValue.latitude) === At(e.geoPointValue.latitude) && At(t.geoPointValue.longitude) === At(e.geoPointValue.longitude); }(t, e); case 2 /* NumberValue */ : return function(t, e) { if ("integerValue" in t && "integerValue" in e) return At(t.integerValue) === At(e.integerValue); if ("doubleValue" in t && "doubleValue" in e) { const n = At(t.doubleValue), r = At(e.doubleValue); return n === r ? ut(n) === ut(r) : isNaN(n) && isNaN(r); } return !1; }(t, e); case 9 /* ArrayValue */ : return pt(t.arrayValue.values || [], e.arrayValue.values || [], $t); case 10 /* ObjectValue */ : return function(t, e) { const n = t.mapValue.fields || {}, r = e.mapValue.fields || {}; if (gt(n) !== gt(r)) return !1; for (const t in n) if (n.hasOwnProperty(t) && (void 0 === r[t] || !$t(n[t], r[t]))) return !1; return !0; } /** Returns true if the ArrayValue contains the specified element. */ (t, e); default: return g(); } } function Ft(t, e) { return void 0 !== (t.values || []).find((t => $t(t, e))); } function St(t, e) { const n = Dt(t), r = Dt(e); if (n !== r) return mt(n, r); switch (n) { case 0 /* NullValue */ : return 0; case 1 /* BooleanValue */ : return mt(t.booleanValue, e.booleanValue); case 2 /* NumberValue */ : return function(t, e) { const n = At(t.integerValue || t.doubleValue), r = At(e.integerValue || e.doubleValue); return n < r ? -1 : n > r ? 1 : n === r ? 0 : // one or both are NaN. isNaN(n) ? isNaN(r) ? 0 : -1 : 1; }(t, e); case 3 /* TimestampValue */ : return qt(t.timestampValue, e.timestampValue); case 4 /* ServerTimestampValue */ : return qt(Nt(t), Nt(e)); case 5 /* StringValue */ : return mt(t.stringValue, e.stringValue); case 6 /* BlobValue */ : return function(t, e) { const n = Pt(t), r = Pt(e); return n.compareTo(r); }(t.bytesValue, e.bytesValue); case 7 /* RefValue */ : return function(t, e) { const n = t.split("/"), r = e.split("/"); for (let t = 0; t < n.length && t < r.length; t++) { const e = mt(n[t], r[t]); if (0 !== e) return e; } return mt(n.length, r.length); }(t.referenceValue, e.referenceValue); case 8 /* GeoPointValue */ : return function(t, e) { const n = mt(At(t.latitude), At(e.latitude)); if (0 !== n) return n; return mt(At(t.longitude), At(e.longitude)); }(t.geoPointValue, e.geoPointValue); case 9 /* ArrayValue */ : return function(t, e) { const n = t.values || [], r = e.values || []; for (let t = 0; t < n.length && t < r.length; ++t) { const e = St(n[t], r[t]); if (e) return e; } return mt(n.length, r.length); }(t.arrayValue, e.arrayValue); case 10 /* ObjectValue */ : return function(t, e) { const n = t.fields || {}, r = Object.keys(n), s = e.fields || {}, i = Object.keys(s); // Even though MapValues are likely sorted correctly based on their insertion // order (e.g. when received from the backend), local modifications can bring // elements out of order. We need to re-sort the elements to ensure that // canonical IDs are independent of insertion order. r.sort(), i.sort(); for (let t = 0; t < r.length && t < i.length; ++t) { const e = mt(r[t], i[t]); if (0 !== e) return e; const o = St(n[r[t]], s[i[t]]); if (0 !== o) return o; } return mt(r.length, i.length); } /** Returns a reference value for the provided database and key. */ (t.mapValue, e.mapValue); default: throw g(); } } function qt(t, e) { if ("string" == typeof t && "string" == typeof e && t.length === e.length) return mt(t, e); const n = It(t), r = It(e), s = mt(n.seconds, r.seconds); return 0 !== s ? s : mt(n.nanos, r.nanos); } function xt(t, e) { return { referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}` }; } /** Returns true if `value` is an ArrayValue. */ function Ot(t) { return !!t && "arrayValue" in t; } /** Returns true if `value` is a NullValue. */ function Ct(t) { return !!t && "nullValue" in t; } /** Returns true if `value` is NaN. */ function Lt(t) { return !!t && "doubleValue" in t && isNaN(Number(t.doubleValue)); } /** Returns true if `value` is a MapValue. */ function Ut(t) { return !!t && "mapValue" in t; } /** Creates a deep copy of `source`. */ function kt(t) { if (t.geoPointValue) return { geoPointValue: Object.assign({}, t.geoPointValue) }; if (t.timestampValue && "object" == typeof t.timestampValue) return { timestampValue: Object.assign({}, t.timestampValue) }; if (t.mapValue) { const e = { mapValue: { fields: {} } }; return vt(t.mapValue.fields, ((t, n) => e.mapValue.fields[t] = kt(n))), e; } if (t.arrayValue) { const e = { arrayValue: { values: [] } }; for (let n = 0; n < (t.arrayValue.values || []).length; ++n) e.arrayValue.values[n] = kt(t.arrayValue.values[n]); return e; } return Object.assign({}, t); } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * An ObjectValue represents a MapValue in the Firestore Proto and offers the * ability to add and remove fields (via the ObjectValueBuilder). */ class jt { constructor(t) { this.value = t; } static empty() { return new jt({ mapValue: {} }); } /** * Returns the value at the given path or null. * * @param path - the path to search * @returns The value at the path or null if the path is not set. */ field(t) { if (t.isEmpty()) return this.value; { let e = this.value; for (let n = 0; n < t.length - 1; ++n) if (e = (e.mapValue.fields || {})[t.get(n)], !Ut(e)) return null; return e = (e.mapValue.fields || {})[t.lastSegment()], e || null; } } /** * Sets the field to the provided value. * * @param path - The field path to set. * @param value - The value to set. */ set(t, e) { this.getFieldsMap(t.popLast())[t.lastSegment()] = kt(e); } /** * Sets the provided fields to the provided values. * * @param data - A map of fields to values (or null for deletes). */ setAll(t) { let e = Z.emptyPath(), n = {}, r = []; t.forEach(((t, s) => { if (!e.isImmediateParentOf(s)) { // Insert the accumulated changes at this parent location const t = this.getFieldsMap(e); this.applyChanges(t, n, r), n = {}, r = [], e = s.popLast(); } t ? n[s.lastSegment()] = kt(t) : r.push(s.lastSegment()); })); const s = this.getFieldsMap(e); this.applyChanges(s, n, r); } /** * Removes the field at the specified path. If there is no field at the * specified path, nothing is changed. * * @param path - The field path to remove. */ delete(t) { const e = this.field(t.popLast()); Ut(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()]; } isEqual(t) { return $t(this.value, t.value); } /** * Returns the map that contains the leaf element of `path`. If the parent * entry does not yet exist, or if it is not a map, a new map will be created. */ getFieldsMap(t) { let e = this.value; e.mapValue.fields || (e.mapValue = { fields: {} }); for (let n = 0; n < t.length; ++n) { let r = e.mapValue.fields[t.get(n)]; Ut(r) && r.mapValue.fields || (r = { mapValue: { fields: {} } }, e.mapValue.fields[t.get(n)] = r), e = r; } return e.mapValue.fields; } /** * Modifies `fieldsMap` by adding, replacing or deleting the specified * entries. */ applyChanges(t, e, n) { vt(e, ((e, n) => t[e] = n)); for (const e of n) delete t[e]; } clone() { return new jt(kt(this.value)); } } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Represents a document in Firestore with a key, version, data and whether it * has local mutations applied to it. * * Documents can transition between states via `convertToFoundDocument()`, * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does * not transition to one of these states even after all mutations have been * applied, `isValidDocument()` returns false and the document should be removed * from all views. */ class Mt { constructor(t, e, n, r, s) { this.key = t, this.documentType = e, this.version = n, this.data = r, this.documentState = s; } /** * Creates a document with no known version or data, but which can serve as * base document for mutations. */ static newInvalidDocument(t) { return new Mt(t, 0 /* INVALID */ , _t.min(), jt.empty(), 0 /* SYNCED */); } /** * Creates a new document that is known to exist with the given data at the * given version. */ static newFoundDocument(t, e, n) { return new Mt(t, 1 /* FOUND_DOCUMENT */ , e, n, 0 /* SYNCED */); } /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(t, e) { return new Mt(t, 2 /* NO_DOCUMENT */ , e, jt.empty(), 0 /* SYNCED */); } /** * Creates a new document that is known to exist at the given version but * whose data is not known (e.g. a document that was updated without a known * base document). */ static newUnknownDocument(t, e) { return new Mt(t, 3 /* UNKNOWN_DOCUMENT */ , e, jt.empty(), 2 /* HAS_COMMITTED_MUTATIONS */); } /** * Changes the document type to indicate that it exists and that its version * and data are known. */ convertToFoundDocument(t, e) { return this.version = t, this.documentType = 1 /* FOUND_DOCUMENT */ , this.data = e, this.documentState = 0 /* SYNCED */ , this; } /** * Changes the document type to indicate that it doesn't exist at the given * version. */ convertToNoDocument(t) { return this.version = t, this.documentType = 2 /* NO_DOCUMENT */ , this.data = jt.empty(), this.documentState = 0 /* SYNCED */ , this; } /** * Changes the document type to indicate that it exists at a given version but * that its data is not known (e.g. a document that was updated without a known * base document). */ convertToUnknownDocument(t) { return this.version = t, this.documentType = 3 /* UNKNOWN_DOCUMENT */ , this.data = jt.empty(), this.documentState = 2 /* HAS_COMMITTED_MUTATIONS */ , this; } setHasCommittedMutations() { return this.documentState = 2 /* HAS_COMMITTED_MUTATIONS */ , this; } setHasLocalMutations() { return this.documentState = 1 /* HAS_LOCAL_MUTATIONS */ , this; } get hasLocalMutations() { return 1 /* HAS_LOCAL_MUTATIONS */ === this.documentState; } get hasCommittedMutations() { return 2 /* HAS_COMMITTED_MUTATIONS */ === this.documentState; } get hasPendingWrites() { return this.hasLocalMutations || this.hasCommittedMutations; } isValidDocument() { return 0 /* INVALID */ !== this.documentType; } isFoundDocument() { return 1 /* FOUND_DOCUMENT */ === this.documentType; } isNoDocument() { return 2 /* NO_DOCUMENT */ === this.documentType; } isUnknownDocument() { return 3 /* UNKNOWN_DOCUMENT */ === this.documentType; } isEqual(t) { return t instanceof Mt && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.documentType === t.documentType && this.documentState === t.documentState && this.data.isEqual(t.data); } clone() { return new Mt(this.key, this.documentType, this.version, this.data.clone(), this.documentState); } toString() { return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`; } } /** * @license * Copyright 2019 Google LLC * * 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. */ // Visible for testing class Bt { constructor(t, e = null, n = [], r = [], s = null, i = null, o = null) { this.path = t, this.collectionGroup = e, this.orderBy = n, this.filters = r, this.limit = s, this.startAt = i, this.endAt = o, this.D = null; } } /** * Initializes a Target with a path and optional additional query constraints. * Path must currently be empty if this is a collection group query. * * NOTE: you should always construct `Target` from `Query.toTarget` instead of * using this factory method, because `Query` provides an implicit `orderBy` * property. */ function Qt(t, e = null, n = [], r = [], s = null, i = null, o = null) { return new Bt(t, e, n, r, s, i, o); } class zt extends class {} { constructor(t, e, n) { super(), this.field = t, this.op = e, this.value = n; } /** * Creates a filter based on the provided arguments. */ static create(t, e, n) { return t.isKeyField() ? "in" /* IN */ === e || "not-in" /* NOT_IN */ === e ? this.$(t, e, n) : new Wt(t, e, n) : "array-contains" /* ARRAY_CONTAINS */ === e ? new Kt(t, n) : "in" /* IN */ === e ? new Jt(t, n) : "not-in" /* NOT_IN */ === e ? new Zt(t, n) : "array-contains-any" /* ARRAY_CONTAINS_ANY */ === e ? new Xt(t, n) : new zt(t, e, n); } static $(t, e, n) { return "in" /* IN */ === e ? new Gt(t, n) : new Ht(t, n); } matches(t) { const e = t.data.field(this.field); // Types do not have to match in NOT_EQUAL filters. return "!=" /* NOT_EQUAL */ === this.op ? null !== e && this.F(St(e, this.value)) : null !== e && Dt(this.value) === Dt(e) && this.F(St(e, this.value)); // Only compare types with matching backend order (such as double and int). } F(t) { switch (this.op) { case "<" /* LESS_THAN */ : return t < 0; case "<=" /* LESS_THAN_OR_EQUAL */ : return t <= 0; case "==" /* EQUAL */ : return 0 === t; case "!=" /* NOT_EQUAL */ : return 0 !== t; case ">" /* GREATER_THAN */ : return t > 0; case ">=" /* GREATER_THAN_OR_EQUAL */ : return t >= 0; default: return g(); } } S() { return [ "<" /* LESS_THAN */ , "<=" /* LESS_THAN_OR_EQUAL */ , ">" /* GREATER_THAN */ , ">=" /* GREATER_THAN_OR_EQUAL */ , "!=" /* NOT_EQUAL */ , "not-in" /* NOT_IN */ ].indexOf(this.op) >= 0; } } /** Filter that matches on key fields (i.e. '__name__'). */ class Wt extends zt { constructor(t, e, n) { super(t, e, n), this.key = X.fromName(n.referenceValue); } matches(t) { const e = X.comparator(t.key, this.key); return this.F(e); } } /** Filter that matches on key fields within an array. */ class Gt extends zt { constructor(t, e) { super(t, "in" /* IN */ , e), this.keys = Yt("in" /* IN */ , e); } matches(t) { return this.keys.some((e => e.isEqual(t.key))); } } /** Filter that matches on key fields not present within an array. */ class Ht extends zt { constructor(t, e) { super(t, "not-in" /* NOT_IN */ , e), this.keys = Yt("not-in" /* NOT_IN */ , e); } matches(t) { return !this.keys.some((e => e.isEqual(t.key))); } } function Yt(t, e) { var n; return ((null === (n = e.arrayValue) || void 0 === n ? void 0 : n.values) || []).map((t => X.fromName(t.referenceValue))); } /** A Filter that implements the array-contains operator. */ class Kt extends zt { constructor(t, e) { super(t, "array-contains" /* ARRAY_CONTAINS */ , e); } matches(t) { const e = t.data.field(this.field); return Ot(e) && Ft(e.arrayValue, this.value); } } /** A Filter that implements the IN operator. */ class Jt extends zt { constructor(t, e) { super(t, "in" /* IN */ , e); } matches(t) { const e = t.data.field(this.field); return null !== e && Ft(this.value.arrayValue, e); } } /** A Filter that implements the not-in operator. */ class Zt extends zt { constructor(t, e) { super(t, "not-in" /* NOT_IN */ , e); } matches(t) { if (Ft(this.value.arrayValue, { nullValue: "NULL_VALUE" })) return !1; const e = t.data.field(this.field); return null !== e && !Ft(this.value.arrayValue, e); } } /** A Filter that implements the array-contains-any operator. */ class Xt extends zt { constructor(t, e) { super(t, "array-contains-any" /* ARRAY_CONTAINS_ANY */ , e); } matches(t) { const e = t.data.field(this.field); return !(!Ot(e) || !e.arrayValue.values) && e.arrayValue.values.some((t => Ft(this.value.arrayValue, t))); } } /** * Represents a bound of a query. * * The bound is specified with the given components representing a position and * whether it's just before or just after the position (relative to whatever the * query order is). * * The position represents a logical index position for a query. It's a prefix * of values for the (potentially implicit) order by clauses of a query. * * Bound provides a function to determine whether a document comes before or * after a bound. This is influenced by whether the position is just before or * just after the provided values. */ class te { constructor(t, e) { this.position = t, this.before = e; } } /** * An ordering on a field, in some Direction. Direction defaults to ASCENDING. */ class ee { constructor(t, e = "asc" /* ASCENDING */) { this.field = t, this.dir = e; } } function ne(t, e) { return t.dir === e.dir && t.field.isEqual(e.field); } function re(t, e) { if (null === t) return null === e; if (null === e) return !1; if (t.before !== e.before || t.position.length !== e.position.length) return !1; for (let n = 0; n < t.position.length; n++) { if (!$t(t.position[n], e.position[n])) return !1; } return !0; } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Query encapsulates all the query attributes we support in the SDK. It can * be run against the LocalStore, as well as be converted to a `Target` to * query the RemoteStore results. * * Visible for testing. */ class se { /** * Initializes a Query with a path and optional additional query constraints. * Path must currently be empty if this is a collection group query. */ constructor(t, e = null, n = [], r = [], s = null, i = "F" /* First */ , o = null, u = null) { this.path = t, this.collectionGroup = e, this.explicitOrderBy = n, this.filters = r, this.limit = s, this.limitType = i, this.startAt = o, this.endAt = u, this.q = null, // The corresponding `Target` of this `Query` instance. this.O = null, this.startAt, this.endAt; } } /** Creates a new Query for a query that matches all documents at `path` */ function ie(t) { return !ot(t.limit) && "L" /* Last */ === t.limitType; } function oe(t) { return t.explicitOrderBy.length > 0 ? t.explicitOrderBy[0].field : null; } function ue(t) { for (const e of t.filters) if (e.S()) return e.field; return null; } /** * Checks if any of the provided Operators are included in the query and * returns the first one that is, or null if none are. */ /** * Returns whether the query matches a collection group rather than a specific * collection. */ function ce(t) { return null !== t.collectionGroup; } /** * Returns the implicit order by constraint that is used to execute the Query, * which can be different from the order by constraints the user provided (e.g. * the SDK and backend always orders by `__name__`). */ function ae(t) { const e = b(t); if (null === e.q) { e.q = []; const t = ue(e), n = oe(e); if (null !== t && null === n) // In order to implicitly add key ordering, we must also add the // inequality filter field for it to be a valid query. // Note that the default inequality field and key ordering is ascending. t.isKeyField() || e.q.push(new ee(t)), e.q.push(new ee(Z.keyField(), "asc" /* ASCENDING */)); else { let t = !1; for (const n of e.explicitOrderBy) e.q.push(n), n.field.isKeyField() && (t = !0); if (!t) { // The order of the implicit key ordering always matches the last // explicit order by const t = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : "asc" /* ASCENDING */; e.q.push(new ee(Z.keyField(), t)); } } } return e.q; } /** * Converts this `Query` instance to it's corresponding `Target` representation. */ function he(t) { const e = b(t); if (!e.O) if ("F" /* First */ === e.limitType) e.O = Qt(e.path, e.collectionGroup, ae(e), e.filters, e.limit, e.startAt, e.endAt); else { // Flip the orderBy directions since we want the last results const t = []; for (const n of ae(e)) { const e = "desc" /* DESCENDING */ === n.dir ? "asc" /* ASCENDING */ : "desc" /* DESCENDING */; t.push(new ee(n.field, e)); } // We need to swap the cursors to match the now-flipped query ordering. const n = e.endAt ? new te(e.endAt.position, !e.endAt.before) : null, r = e.startAt ? new te(e.startAt.position, !e.startAt.before) : null; // Now return as a LimitType.First query. e.O = Qt(e.path, e.collectionGroup, t, e.filters, e.limit, n, r); } return e.O; } function le(t, e) { return function(t, e) { if (t.limit !== e.limit) return !1; if (t.orderBy.length !== e.orderBy.length) return !1; for (let n = 0; n < t.orderBy.length; n++) if (!ne(t.orderBy[n], e.orderBy[n])) return !1; if (t.filters.length !== e.filters.length) return !1; for (let s = 0; s < t.filters.length; s++) if (n = t.filters[s], r = e.filters[s], n.op !== r.op || !n.field.isEqual(r.field) || !$t(n.value, r.value)) return !1; var n, r; return t.collectionGroup === e.collectionGroup && !!t.path.isEqual(e.path) && !!re(t.startAt, e.startAt) && re(t.endAt, e.endAt); }(he(t), he(e)) && t.limitType === e.limitType; } /** * @license * Copyright 2020 Google LLC * * 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. */ /** * Returns an DoubleValue for `value` that is encoded based the serializer's * `useProto3Json` setting. */ /** * Returns a value for a number that's appropriate to put into a proto. * The return value is an IntegerValue if it can safely represent the value, * otherwise a DoubleValue is returned. */ function fe(t, e) { return function(t) { return "number" == typeof t && Number.isInteger(t) && !ut(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER; }(e) ? /** * Returns an IntegerValue for `value`. */ function(t) { return { integerValue: "" + t }; }(e) : function(t, e) { if (t.C) { if (isNaN(e)) return { doubleValue: "NaN" }; if (e === 1 / 0) return { doubleValue: "Infinity" }; if (e === -1 / 0) return { doubleValue: "-Infinity" }; } return { doubleValue: ut(e) ? "-0" : e }; }(t, e); } /** * @license * Copyright 2018 Google LLC * * 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. */ /** Used to represent a field transform on a mutation. */ class de { constructor() { // Make sure that the structural type of `TransformOperation` is unique. // See https://github.com/microsoft/TypeScript/issues/5451 this._ = void 0; } } /** Transforms a value into a server-generated timestamp. */ class we extends de {} /** Transforms an array value via a union operation. */ class me extends de { constructor(t) { super(), this.elements = t; } } /** Transforms an array value via a remove operation. */ class pe extends de { constructor(t) { super(), this.elements = t; } } /** * Implements the backend semantics for locally computed NUMERIC_ADD (increment) * transforms. Converts all field values to integers or doubles, but unlike the * backend does not cap integer values at 2^63. Instead, JavaScript number * arithmetic is used and precision loss can occur for values greater than 2^53. */ class ye extends de { constructor(t, e) { super(), this.L = t, this.U = e; } } /** * @license * Copyright 2017 Google LLC * * 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. */ /** A field path and the TransformOperation to perform upon it. */ class _e { constructor(t, e) { this.field = t, this.transform = e; } } /** * Encodes a precondition for a mutation. This follows the model that the * backend accepts with the special case of an explicit "empty" precondition * (meaning no precondition). */ class ge { constructor(t, e) { this.updateTime = t, this.exists = e; } /** Creates a new empty Precondition. */ static none() { return new ge; } /** Creates a new Precondition with an exists flag. */ static exists(t) { return new ge(void 0, t); } /** Creates a new Precondition based on a version a document exists at. */ static updateTime(t) { return new ge(t); } /** Returns whether this Precondition is empty. */ get isNone() { return void 0 === this.updateTime && void 0 === this.exists; } isEqual(t) { return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime); } } /** * A mutation describes a self-contained change to a document. Mutations can * create, replace, delete, and update subsets of documents. * * Mutations not only act on the value of the document but also its version. * * For local mutations (mutations that haven't been committed yet), we preserve * the existing version for Set and Patch mutations. For Delete mutations, we * reset the version to 0. * * Here's the expected transition table. * * MUTATION APPLIED TO RESULTS IN * * SetMutation Document(v3) Document(v3) * SetMutation NoDocument(v3) Document(v0) * SetMutation InvalidDocument(v0) Document(v0) * PatchMutation Document(v3) Document(v3) * PatchMutation NoDocument(v3) NoDocument(v3) * PatchMutation InvalidDocument(v0) UnknownDocument(v3) * DeleteMutation Document(v3) NoDocument(v0) * DeleteMutation NoDocument(v3) NoDocument(v0) * DeleteMutation InvalidDocument(v0) NoDocument(v0) * * For acknowledged mutations, we use the updateTime of the WriteResponse as * the resulting version for Set and Patch mutations. As deletes have no * explicit update time, we use the commitTime of the WriteResponse for * Delete mutations. * * If a mutation is acknowledged by the backend but fails the precondition check * locally, we transition to an `UnknownDocument` and rely on Watch to send us * the updated version. * * Field transforms are used only with Patch and Set Mutations. We use the * `updateTransforms` message to store transforms, rather than the `transforms`s * messages. * * ## Subclassing Notes * * Every type of mutation needs to implement its own applyToRemoteDocument() and * applyToLocalView() to implement the actual behavior of applying the mutation * to some source document (see `applySetMutationToRemoteDocument()` for an * example). */ class ve {} /** * A mutation that creates or replaces the document at the given key with the * object value contents. */ class be extends ve { constructor(t, e, n, r = []) { super(), this.key = t, this.value = e, this.precondition = n, this.fieldTransforms = r, this.type = 0 /* Set */; } } /** * A mutation that modifies fields of the document at the given key with the * given values. The values are applied through a field mask: * * * When a field is in both the mask and the values, the corresponding field * is updated. * * When a field is in neither the mask nor the values, the corresponding * field is unmodified. * * When a field is in the mask but not in the values, the corresponding field * is deleted. * * When a field is not in the mask but is in the values, the values map is * ignored. */ class Ee extends ve { constructor(t, e, n, r, s = []) { super(), this.key = t, this.data = e, this.fieldMask = n, this.precondition = r, this.fieldTransforms = s, this.type = 1 /* Patch */; } } /** A mutation that deletes the document at the given key. */ class Te extends ve { constructor(t, e) { super(), this.key = t, this.precondition = e, this.type = 2 /* Delete */ , this.fieldTransforms = []; } } /** * A mutation that verifies the existence of the document at the given key with * the provided precondition. * * The `verify` operation is only used in Transactions, and this class serves * primarily to facilitate serialization into protos. */ class Ie extends ve { constructor(t, e) { super(), this.key = t, this.precondition = e, this.type = 3 /* Verify */ , this.fieldTransforms = []; } } /** * @license * Copyright 2017 Google LLC * * 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. */ const Ae = (() => { const t = { asc: "ASCENDING", desc: "DESCENDING" }; return t; })(), Pe = (() => { const t = { "<": "LESS_THAN", "<=": "LESS_THAN_OR_EQUAL", ">": "GREATER_THAN", ">=": "GREATER_THAN_OR_EQUAL", "==": "EQUAL", "!=": "NOT_EQUAL", "array-contains": "ARRAY_CONTAINS", in: "IN", "not-in": "NOT_IN", "array-contains-any": "ARRAY_CONTAINS_ANY" }; return t; })(); /** * This class generates JsonObject values for the Datastore API suitable for * sending to either GRPC stub methods or via the JSON/HTTP REST API. * * The serializer supports both Protobuf.js and Proto3 JSON formats. By * setting `useProto3Json` to true, the serializer will use the Proto3 JSON * format. * * For a description of the Proto3 JSON format check * https://developers.google.com/protocol-buffers/docs/proto3#json * * TODO(klimt): We can remove the databaseId argument if we keep the full * resource name in documents. */ class Re { constructor(t, e) { this.databaseId = t, this.C = e; } } /** * Returns a value for a number (or null) that's appropriate to put into * a google.protobuf.Int32Value proto. * DO NOT USE THIS FOR ANYTHING ELSE. * This method cheats. It's typed as returning "number" because that's what * our generated proto interfaces say Int32Value must be. But GRPC actually * expects a { value: <number> } struct. */ /** * Returns a value for a Date that's appropriate to put into a proto. */ function Ve(t, e) { if (t.C) { return `${new Date(1e3 * e.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + e.nanoseconds).slice(-9)}Z`; } return { seconds: "" + e.seconds, nanos: e.nanoseconds }; } /** * Returns a value for bytes that's appropriate to put in a proto. * * Visible for testing. */ function Ne(t, e) { return t.C ? e.toBase64() : e.toUint8Array(); } function De(t, e) { return Ve(t, e.toTimestamp()); } function $e(t) { return v(!!t), _t.fromTimestamp(function(t) { const e = It(t); return new yt(e.seconds, e.nanos); }(t)); } function Fe(t, e) { return function(t) { return new K([ "projects", t.projectId, "databases", t.database ]); }(t).child("documents").child(e).canonicalString(); } function Se(t, e) { return Fe(t.databaseId, e.path); } function qe(t, e) { const n = function(t) { const e = K.fromString(t); return v(We(e)), e; }(e); if (n.get(1) !== t.databaseId.projectId) throw new U(A, "Tried to deserialize key from different project: " + n.get(1) + " vs " + t.databaseId.projectId); if (n.get(3) !== t.databaseId.database) throw new U(A, "Tried to deserialize key from different database: " + n.get(3) + " vs " + t.databaseId.database); return new X((v((r = n).length > 4 && "documents" === r.get(4)), r.popFirst(5))); var r; /** Creates a Document proto from key and fields (but no create/update time) */} function xe(t, e) { return Fe(t.databaseId, e); } function Oe(t) { return new K([ "projects", t.databaseId.projectId, "databases", t.databaseId.database ]).canonicalString(); } function Ce(t, e, n) { return { name: Se(t, e), fields: n.value.mapValue.fields }; } function Le(t, e) { return "found" in e ? function(t, e) { v(!!e.found), e.found.name, e.found.updateTime; const n = qe(t, e.found.name), r = $e(e.found.updateTime), s = new jt({ mapValue: { fields: e.found.fields } }); return Mt.newFoundDocument(n, r, s); }(t, e) : "missing" in e ? function(t, e) { v(!!e.missing), v(!!e.readTime); const n = qe(t, e.missing), r = $e(e.readTime); return Mt.newNoDocument(n, r); }(t, e) : g(); } function Ue(t, e) { let n; if (e instanceof be) n = { update: Ce(t, e.key, e.value) }; else if (e instanceof Te) n = { delete: Se(t, e.key) }; else if (e instanceof Ee) n = { update: Ce(t, e.key, e.data), updateMask: ze(e.fieldMask) }; else { if (!(e instanceof Ie)) return g(); n = { verify: Se(t, e.key) }; } return e.fieldTransforms.length > 0 && (n.updateTransforms = e.fieldTransforms.map((t => function(t, e) { const n = e.transform; if (n instanceof we) return { fieldPath: e.field.canonicalString(), setToServerValue: "REQUEST_TIME" }; if (n instanceof me) return { fieldPath: e.field.canonicalString(), appendMissingElements: { values: n.elements } }; if (n instanceof pe) return { fieldPath: e.field.canonicalString(), removeAllFromArray: { values: n.elements } }; if (n instanceof ye) return { fieldPath: e.field.canonicalString(), increment: n.U }; throw g(); }(0, t)))), e.precondition.isNone || (n.currentDocument = function(t, e) { return void 0 !== e.updateTime ? { updateTime: De(t, e.updateTime) } : void 0 !== e.exists ? { exists: e.exists } : g(); }(t, e.precondition)), n; } function ke(t, e) { // Dissect the path into parent, collectionId, and optional key filter. const n = { structuredQuery: {} }, r = e.path; null !== e.collectionGroup ? (n.parent = xe(t, r), n.structuredQuery.from = [ { collectionId: e.collectionGroup, allDescendants: !0 } ]) : (n.parent = xe(t, r.popLast()), n.structuredQuery.from = [ { collectionId: r.lastSegment() } ]); const s = function(t) { if (0 === t.length) return; const e = t.map((t => // visible for testing function(t) { if ("==" /* EQUAL */ === t.op) { if (Lt(t.value)) return { unaryFilter: { field: Qe(t.field), op: "IS_NAN" } }; if (Ct(t.value)) return { unaryFilter: { field: Qe(t.field), op: "IS_NULL" } }; } else if ("!=" /* NOT_EQUAL */ === t.op) { if (Lt(t.value)) return { unaryFilter: { field: Qe(t.field), op: "IS_NOT_NAN" } }; if (Ct(t.value)) return { unaryFilter: { field: Qe(t.field), op: "IS_NOT_NULL" } }; } return { fieldFilter: { field: Qe(t.field), op: Be(t.op), value: t.value } }; }(t))); if (1 === e.length) return e[0]; return { compositeFilter: { op: "AND", filters: e } }; }(e.filters); s && (n.structuredQuery.where = s); const i = function(t) { if (0 === t.length) return; return t.map((t => // visible for testing function(t) { return { field: Qe(t.field), direction: Me(t.dir) }; }(t))); }(e.orderBy); i && (n.structuredQuery.orderBy = i); const o = function(t, e) { return t.C || ot(e) ? e : { value: e }; }(t, e.limit); return null !== o && (n.structuredQuery.limit = o), e.startAt && (n.structuredQuery.startAt = je(e.startAt)), e.endAt && (n.structuredQuery.endAt = je(e.endAt)), n; } function je(t) { return { before: t.before, values: t.position }; } // visible for testing function Me(t) { return Ae[t]; } // visible for testing function Be(t) { return Pe[t]; } function Qe(t) { return { fieldPath: t.canonicalString() }; } function ze(t) { const e = []; return t.fields.forEach((t => e.push(t.canonicalString()))), { fieldPaths: e }; } function We(t) { // Resource names have at least 4 components (project ID, database ID) return t.length >= 4 && "projects" === t.get(0) && "databases" === t.get(2); } /** * @license * Copyright 2020 Google LLC * * 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. */ function Ge(t) { return new Re(t, /* useProto3Json= */ !0); } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * A helper for running delayed tasks following an exponential backoff curve * between attempts. * * Each delay is made up of a "base" delay which follows the exponential * backoff curve, and a +/- 50% "jitter" that is calculated and added to the * base delay. This prevents clients from accidentally synchronizing their * delays causing spikes of load to the backend. */ class He { constructor( /** * The AsyncQueue to run backoff operations on. */ t, /** * The ID to use when scheduling backoff operations on the AsyncQueue. */ e, /** * The initial delay (used as the base delay on the first retry attempt). * Note that jitter will still be applied, so the actual delay could be as * little as 0.5*initialDelayMs. */ n = 1e3 /** * The multiplier to use to determine the extended base delay after each * attempt. */ , r = 1.5 /** * The maximum base delay after which no further backoff is performed. * Note that jitter will still be applied, so the actual delay could be as * much as 1.5*maxDelayMs. */ , s = 6e4) { this.k = t, this.timerId = e, this.j = n, this.M = r, this.B = s, this.W = 0, this.G = null, /** The last backoff attempt, as epoch milliseconds. */ this.H = Date.now(), this.reset(); } /** * Resets the backoff delay. * * The very next backoffAndWait() will have no delay. If it is called again * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and * subsequent ones will increase according to the backoffFactor. */ reset() { this.W = 0; } /** * Resets the backoff delay to the maximum delay (e.g. for use after a * RESOURCE_EXHAUSTED error). */ Y() { this.W = this.B; } /** * Returns a promise that resolves after currentDelayMs, and increases the * delay for any subsequent attempts. If there was a pending backoff operation * already, it will be canceled. */ K(t) { // Cancel any pending backoff operation. this.cancel(); // First schedule using the current base (which may be 0 and should be // honored as such). const e = Math.floor(this.W + this.J()), n = Math.max(0, Date.now() - this.H), r = Math.max(0, e - n); // Guard against lastAttemptTime being in the future due to a clock change. r > 0 && m("ExponentialBackoff", `Backing off for ${r} ms (base delay: ${this.W} ms, delay with jitter: ${e} ms, last attempt: ${n} ms ago)`), this.G = this.k.enqueueAfterDelay(this.timerId, r, (() => (this.H = Date.now(), t()))), // Apply backoff factor to determine next delay and ensure it is within // bounds. this.W *= this.M, this.W < this.j && (this.W = this.j), this.W > this.B && (this.W = this.B); } Z() { null !== this.G && (this.G.skipDelay(), this.G = null); } cancel() { null !== this.G && (this.G.cancel(), this.G = null); } /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ J() { return (Math.random() - .5) * this.W; } } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Datastore and its related methods are a wrapper around the external Google * Cloud Datastore grpc API, which provides an interface that is more convenient * for the rest of the client SDK architecture to consume. */ /** * An implementation of Datastore that exposes additional state for internal * consumption. */ class Ye extends class {} { constructor(t, e, n) { super(), this.credentials = t, this.X = e, this.L = n, this.tt = !1; } et() { if (this.tt) throw new U(F, "The client has already been terminated."); } /** Gets an auth token and invokes the provided RPC. */ v(t, e, n) { return this.et(), this.credentials.getToken().then((r => this.X.v(t, e, n, r))).catch((t => { throw "FirebaseError" === t.name ? (t.code === D && this.credentials.invalidateToken(), t) : new U(I, t.toString()); })); } /** Gets an auth token and invokes the provided RPC with streamed results. */ P(t, e, n) { return this.et(), this.credentials.getToken().then((r => this.X.P(t, e, n, r))).catch((t => { throw "FirebaseError" === t.name ? (t.code === D && this.credentials.invalidateToken(), t) : new U(I, t.toString()); })); } terminate() { this.tt = !0; } } // TODO(firestorexp): Make sure there is only one Datastore instance per // firestore-exp client. async function Ke(t, e) { const n = b(t), r = Oe(n.L) + "/documents", s = { writes: e.map((t => Ue(n.L, t))) }; await n.v("Commit", r, s); } async function Je(t, e) { const n = b(t), r = Oe(n.L) + "/documents", s = { documents: e.map((t => Se(n.L, t))) }, i = await n.P("BatchGetDocuments", r, s), o = new Map; i.forEach((t => { const e = Le(n.L, t); o.set(e.key.toString(), e); })); const u = []; return e.forEach((t => { const e = o.get(t.toString()); v(!!e), u.push(e); })), u; } async function Ze(t, e) { const n = b(t), r = ke(n.L, he(e)); return (await n.P("RunQuery", r.parent, { structuredQuery: r.structuredQuery })).filter((t => !!t.document)).map((t => function(t, e, n) { const r = qe(t, e.name), s = $e(e.updateTime), i = new jt({ mapValue: { fields: e.fields } }), o = Mt.newFoundDocument(r, s, i); return n && o.setHasCommittedMutations(), n ? o.setHasCommittedMutations() : o; }(n.L, t.document, void 0))); } /** * @license * Copyright 2020 Google LLC * * 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. */ const Xe = new Map; /** * An instance map that ensures only one Datastore exists per Firestore * instance. */ /** * Returns an initialized and started Datastore for the given Firestore * instance. Callers must invoke removeComponents() when the Firestore * instance is terminated. */ function tn(t) { if (t._terminated) throw new U(F, "The client has already been terminated."); if (!Xe.has(t)) { m("ComponentProvider", "Initializing Datastore"); const i = function(t) { return new ft(t, fetch.bind(null)); }((e = t._databaseId, n = t.app.options.appId || "", r = t._persistenceKey, s = t._freezeSettings(), new G(e, n, r, s.host, s.ssl, s.experimentalForceLongPolling, s.experimentalAutoDetectLongPolling, s.useFetchStreams))), o = Ge(t._databaseId), u = function(t, e, n) { return new Ye(t, e, n); }(t._credentials, i, o); Xe.set(t, u); } var e, n, r, s; /** * @license * Copyright 2018 Google LLC * * 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. */ return Xe.get(t); } /** * Removes all components associated with the provided instance. Must be called * when the `Firestore` instance is terminated. */ /** * A concrete type describing all the values that can be applied via a * user-supplied firestore.Settings object. This is a separate type so that * defaults can be supplied and the value can be checked for equality. */ class en { constructor(t) { var e; if (void 0 === t.host) { if (void 0 !== t.ssl) throw new U(A, "Can't provide ssl option if host option is not set"); this.host = "firestore.googleapis.com", this.ssl = true; } else this.host = t.host, this.ssl = null === (e = t.ssl) || void 0 === e || e; if (this.credentials = t.credentials, this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties, void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else { if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < 1048576) throw new U(A, "cacheSizeBytes must be at least 1048576"); this.cacheSizeBytes = t.cacheSizeBytes; } this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling, this.useFetchStreams = !!t.useFetchStreams, function(t, e, n, r) { if (!0 === e && !0 === r) throw new U(A, `${t} and ${n} cannot be used together.`); }("experimentalForceLongPolling", t.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", t.experimentalAutoDetectLongPolling); } isEqual(t) { return this.host === t.host && this.ssl === t.ssl && this.credentials === t.credentials && this.cacheSizeBytes === t.cacheSizeBytes && this.experimentalForceLongPolling === t.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === t.experimentalAutoDetectLongPolling && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams; } } /** * @license * Copyright 2020 Google LLC * * 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. */ /** * The Cloud Firestore service interface. * * Do not call this constructor directly. Instead, use {@link getFirestore}. */ class nn { /** @hideconstructor */ constructor(t, e) { /** * Whether it's a Firestore or Firestore Lite instance. */ this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new en({}), this._settingsFrozen = !1, t instanceof H ? (this._databaseId = t, this._credentials = new M) : (this._app = t, this._databaseId = function(t) { if (!Object.prototype.hasOwnProperty.apply(t.options, [ "projectId" ])) throw new U(A, '"projectId" not provided in firebase.initializeApp.'); return new H(t.options.projectId); } /** * Initializes a new instance of Cloud Firestore with the provided settings. * Can only be called before any other functions, including * {@link getFirestore}. If the custom settings are empty, this function is * equivalent to calling {@link getFirestore}. * * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will * be associated. * @param settings - A settings object to configure the `Firestore` instance. * @returns A newly initialized Firestore instance. */ (t), this._credentials = new Q(e)); } /** * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service * instance. */ get app() { if (!this._app) throw new U(F, "Firestore was not initialized using the Firebase SDK. 'app' is not available"); return this._app; } get _initialized() { return this._settingsFrozen; } get _terminated() { return void 0 !== this._terminateTask; } _setSettings(t) { if (this._settingsFrozen) throw new U(F, "Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object."); this._settings = new en(t), void 0 !== t.credentials && (this._credentials = function(t) { if (!t) return new M; switch (t.type) { case "gapi": const e = t.client; // Make sure this really is a Gapi client. return v(!("object" != typeof e || null === e || !e.auth || !e.auth.getAuthHeaderValueForFirstParty)), new W(e, t.sessionIndex || "0", t.iamToken || null); case "provider": return t.client; default: throw new U(A, "makeCredentialsProvider failed due to invalid credential type"); } }(t.credentials)); } _getSettings() { return this._settings; } _freezeSettings() { return this._settingsFrozen = !0, this._settings; } _delete() { return this._terminateTask || (this._terminateTask = this._terminate()), this._terminateTask; } /** Returns a JSON-serializable representation of this Firestore instance. */ toJSON() { return { app: this._app, databaseId: this._databaseId, settings: this._settings }; } /** * Terminates all components used by this client. Subclasses can override * this method to clean up their own dependencies, but must also call this * method. * * Only ever called once. */ _terminate() { return function(t) { const e = Xe.get(t); e && (m("ComponentProvider", "Removing Datastore"), Xe.delete(t), e.terminate()); }(this), Promise.resolve(); } } function rn(e, n) { const r = t(e, "firestore/lite"); if (r.isInitialized()) throw new U(F, "Firestore can only be initialized once per app."); return r.initialize({ options: n }); } /** * Returns the existing instance of Firestore that is associated with the * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new * instance with default settings. * * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Firestore * instance is associated with. * @returns The `Firestore` instance of the provided app. */ function sn(n = e()) { return t(n, "firestore/lite").getImmediate(); } /** * Modify this instance to communicate with the Cloud Firestore emulator. * * Note: This must be called before this instance has been used to do any * operations. * * @param firestore - The Firestore instance to configure to connect to the * emulator. * @param host - the emulator host (ex: localhost). * @param port - the emulator port (ex: 9000). * @param options.mockUserToken - the mock auth token to use for unit testing * Security Rules. */ function on(t, e, n, r = {}) { var s; const i = (t = st(t, nn))._getSettings(); if ("firestore.googleapis.com" !== i.host && i.host !== e && y("Host has been set in both settings() and useEmulator(), emulator host will be used"), t._setSettings(Object.assign(Object.assign({}, i), { host: `${e}:${n}`, ssl: !1 })), r.mockUserToken) { let e, n; if ("string" == typeof r.mockUserToken) e = r.mockUserToken, n = f.MOCK_USER; else { // Let createMockUserToken validate first (catches common mistakes like // invalid field "uid" and missing field "sub" / "user_id".) e = u(r.mockUserToken, null === (s = t._app) || void 0 === s ? void 0 : s.options.projectId); const i = r.mockUserToken.sub || r.mockUserToken.user_id; if (!i) throw new U(A, "mockUserToken must contain 'sub' or 'user_id' field!"); n = new f(i); } t._credentials = new B(new j(e, n)); } } /** * Terminates the provided Firestore instance. * * After calling `terminate()` only the `clearIndexedDbPersistence()` functions * may be used. Any other function will throw a `FirestoreError`. Termination * does not cancel any pending writes, and any promises that are awaiting a * response from the server will not be resolved. * * To restart after termination, create a new instance of FirebaseFirestore with * {@link getFirestore}. * * Note: Under normal circumstances, calling `terminate()` is not required. This * function is useful only when you want to force this instance to release all of * its resources or in combination with {@link clearIndexedDbPersistence} to * ensure that all local state is destroyed between test runs. * * @param firestore - The Firestore instance to terminate. * @returns A promise that is resolved when the instance has been successfully * terminated. */ function un(t) { return t = st(t, nn), n(t.app, "firestore/lite"), t._delete(); } /** * @license * Copyright 2020 Google LLC * * 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. */ /** * @license * Copyright 2020 Google LLC * * 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. */ /** * A `DocumentReference` refers to a document location in a Firestore database * and can be used to write, read, or listen to the location. The document at * the referenced location may or may not exist. */ class cn { /** @hideconstructor */ constructor(t, /** * If provided, the `FirestoreDataConverter` associated with this instance. */ e, n) { this.converter = e, this._key = n, /** The type of this Firestore reference. */ this.type = "document", this.firestore = t; } get _path() { return this._key.path; } /** * The document's identifier within its collection. */ get id() { return this._key.path.lastSegment(); } /** * A string representing the path of the referenced document (relative * to the root of the database). */ get path() { return this._key.path.canonicalString(); } /** * The collection this `DocumentReference` belongs to. */ get parent() { return new hn(this.firestore, this.converter, this._key.path.popLast()); } withConverter(t) { return new cn(this.firestore, t, this._key); } } /** * A `Query` refers to a Query which you can read or listen to. You can also * construct refined `Query` objects by adding filters and ordering. */ class an { // This is the lite version of the Query class in the main SDK. /** @hideconstructor protected */ constructor(t, /** * If provided, the `FirestoreDataConverter` associated with this instance. */ e, n) { this.converter = e, this._query = n, /** The type of this Firestore reference. */ this.type = "query", this.firestore = t; } withConverter(t) { return new an(this.firestore, t, this._query); } } /** * A `CollectionReference` object can be used for adding documents, getting * document references, and querying for documents (using {@link query}). */ class hn extends an { /** @hideconstructor */ constructor(t, e, n) { super(t, e, new se(n)), this._path = n, /** The type of this Firestore reference. */ this.type = "collection"; } /** The collection's identifier. */ get id() { return this._query.path.lastSegment(); } /** * A string representing the path of the referenced collection (relative * to the root of the database). */ get path() { return this._query.path.canonicalString(); } /** * A reference to the containing `DocumentReference` if this is a * subcollection. If this isn't a subcollection, the reference is null. */ get parent() { const t = this._path.popLast(); return t.isEmpty() ? null : new cn(this.firestore, /* converter= */ null, new X(t)); } withConverter(t) { return new hn(this.firestore, t, this._path); } } function ln(t, e, ...n) { if (t = c(t), tt("collection", "path", e), t instanceof nn) { const r = K.fromString(e, ...n); return nt(r), new hn(t, /* converter= */ null, r); } { if (!(t instanceof cn || t instanceof hn)) throw new U(A, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); const r = K.fromString(t.path, ...n).child(K.fromString(e)); return nt(r), new hn(t.firestore, /* converter= */ null, r); } } // TODO(firestorelite): Consider using ErrorFactory - // https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106 /** * Creates and returns a new `Query` instance that includes all documents in the * database that are contained in a collection or subcollection with the * given `collectionId`. * * @param firestore - A reference to the root Firestore instance. * @param collectionId - Identifies the collections to query over. Every * collection or subcollection with this ID as the last segment of its path * will be included. Cannot contain a slash. * @returns The created `Query`. */ function fn(t, e) { if (t = st(t, nn), tt("collectionGroup", "collection id", e), e.indexOf("/") >= 0) throw new U(A, `Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`); return new an(t, /* converter= */ null, /** * Creates a new Query for a collection group query that matches all documents * within the provided collection group. */ function(t) { return new se(K.emptyPath(), t); }(e)); } function dn(t, e, ...n) { if (t = c(t), // We allow omission of 'pathString' but explicitly prohibit passing in both // 'undefined' and 'null'. 1 === arguments.length && (e = wt.N()), tt("doc", "path", e), t instanceof nn) { const r = K.fromString(e, ...n); return et(r), new cn(t, /* converter= */ null, new X(r)); } { if (!(t instanceof cn || t instanceof hn)) throw new U(A, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); const r = t._path.child(K.fromString(e, ...n)); return et(r), new cn(t.firestore, t instanceof hn ? t.converter : null, new X(r)); } } /** * Returns true if the provided references are equal. * * @param left - A reference to compare. * @param right - A reference to compare. * @returns true if the references point to the same location in the same * Firestore database. */ function wn(t, e) { return t = c(t), e = c(e), (t instanceof cn || t instanceof hn) && (e instanceof cn || e instanceof hn) && (t.firestore === e.firestore && t.path === e.path && t.converter === e.converter); } /** * Returns true if the provided queries point to the same collection and apply * the same constraints. * * @param left - A `Query` to compare. * @param right - A `Query` to compare. * @returns true if the references point to the same location in the same * Firestore database. */ function mn(t, e) { return t = c(t), e = c(e), t instanceof an && e instanceof an && (t.firestore === e.firestore && le(t._query, e._query) && t.converter === e.converter); } /** * @license * Copyright 2020 Google LLC * * 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. */ /** * A `FieldPath` refers to a field in a document. The path may consist of a * single field name (referring to a top-level field in the document), or a * list of field names (referring to a nested field in the document). * * Create a `FieldPath` by providing field names. If more than one field * name is provided, the path will point to a nested field in a document. */ class pn { /** * Creates a FieldPath from the provided field names. If more than one field * name is provided, the path will point to a nested field in a document. * * @param fieldNames - A list of field names. */ constructor(...t) { for (let e = 0; e < t.length; ++e) if (0 === t[e].length) throw new U(A, "Invalid field name at argument $(i + 1). Field names must not be empty."); this._internalPath = new Z(t); } /** * Returns true if this `FieldPath` is equal to the provided one. * * @param other - The `FieldPath` to compare against. * @returns true if this `FieldPath` is equal to the provided one. */ isEqual(t) { return this._internalPath.isEqual(t._internalPath); } } /** * Returns a special sentinel `FieldPath` to refer to the ID of a document. * It can be used in queries to sort or filter by the document ID. */ function yn() { return new pn("__name__"); } /** * @license * Copyright 2020 Google LLC * * 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. */ /** * An immutable object representing an array of bytes. */ class _n { /** @hideconstructor */ constructor(t) { this._byteString = t; } /** * Creates a new `Bytes` object from the given Base64 string, converting it to * bytes. * * @param base64 - The Base64 string used to create the `Bytes` object. */ static fromBase64String(t) { try { return new _n(Et.fromBase64String(t)); } catch (t) { throw new U(A, "Failed to construct data from Base64 string: " + t); } } /** * Creates a new `Bytes` object from the given Uint8Array. * * @param array - The Uint8Array used to create the `Bytes` object. */ static fromUint8Array(t) { return new _n(Et.fromUint8Array(t)); } /** * Returns the underlying bytes as a Base64-encoded string. * * @returns The Base64-encoded string created from the `Bytes` object. */ toBase64() { return this._byteString.toBase64(); } /** * Returns the underlying bytes in a new `Uint8Array`. * * @returns The Uint8Array created from the `Bytes` object. */ toUint8Array() { return this._byteString.toUint8Array(); } /** * Returns a string representation of the `Bytes` object. * * @returns A string representation of the `Bytes` object. */ toString() { return "Bytes(base64: " + this.toBase64() + ")"; } /** * Returns true if this `Bytes` object is equal to the provided one. * * @param other - The `Bytes` object to compare against. * @returns true if this `Bytes` object is equal to the provided one. */ isEqual(t) { return this._byteString.isEqual(t._byteString); } } /** * @license * Copyright 2020 Google LLC * * 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. */ /** * Sentinel values that can be used when writing document fields with `set()` * or `update()`. */ class gn { /** * @param _methodName - The public API endpoint that returns this class. * @hideconstructor */ constructor(t) { this._methodName = t; } } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * An immutable object representing a geographic location in Firestore. The * location is represented as latitude/longitude pair. * * Latitude values are in the range of [-90, 90]. * Longitude values are in the range of [-180, 180]. */ class vn { /** * Creates a new immutable `GeoPoint` object with the provided latitude and * longitude values. * @param latitude - The latitude as number between -90 and 90. * @param longitude - The longitude as number between -180 and 180. */ constructor(t, e) { if (!isFinite(t) || t < -90 || t > 90) throw new U(A, "Latitude must be a number between -90 and 90, but was: " + t); if (!isFinite(e) || e < -180 || e > 180) throw new U(A, "Longitude must be a number between -180 and 180, but was: " + e); this._lat = t, this._long = e; } /** * The latitude of this `GeoPoint` instance. */ get latitude() { return this._lat; } /** * The longitude of this `GeoPoint` instance. */ get longitude() { return this._long; } /** * Returns true if this `GeoPoint` is equal to the provided one. * * @param other - The `GeoPoint` to compare against. * @returns true if this `GeoPoint` is equal to the provided one. */ isEqual(t) { return this._lat === t._lat && this._long === t._long; } /** Returns a JSON-serializable representation of this GeoPoint. */ toJSON() { return { latitude: this._lat, longitude: this._long }; } /** * Actually private to JS consumers of our API, so this function is prefixed * with an underscore. */ _compareTo(t) { return mt(this._lat, t._lat) || mt(this._long, t._long); } } /** * @license * Copyright 2017 Google LLC * * 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. */ const bn = /^__.*__$/; /** The result of parsing document data (e.g. for a setData call). */ class En { constructor(t, e, n) { this.data = t, this.fieldMask = e, this.fieldTransforms = n; } toMutation(t, e) { return null !== this.fieldMask ? new Ee(t, this.data, this.fieldMask, e, this.fieldTransforms) : new be(t, this.data, e, this.fieldTransforms); } } /** The result of parsing "update" data (i.e. for an updateData call). */ class Tn { constructor(t, // The fieldMask does not include document transforms. e, n) { this.data = t, this.fieldMask = e, this.fieldTransforms = n; } toMutation(t, e) { return new Ee(t, this.data, this.fieldMask, e, this.fieldTransforms); } } function In(t) { switch (t) { case 0 /* Set */ : // fall through case 2 /* MergeSet */ : // fall through case 1 /* Update */ : return !0; case 3 /* Argument */ : case 4 /* ArrayArgument */ : return !1; default: throw g(); } } /** A "context" object passed around while parsing user data. */ class An { /** * Initializes a ParseContext with the given source and path. * * @param settings - The settings for the parser. * @param databaseId - The database ID of the Firestore instance. * @param serializer - The serializer to use to generate the Value proto. * @param ignoreUndefinedProperties - Whether to ignore undefined properties * rather than throw. * @param fieldTransforms - A mutable list of field transforms encountered * while parsing the data. * @param fieldMask - A mutable list of field paths encountered while parsing * the data. * * TODO(b/34871131): We don't support array paths right now, so path can be * null to indicate the context represents any location within an array (in * which case certain features will not work and errors will be somewhat * compromised). */ constructor(t, e, n, r, s, i) { this.settings = t, this.databaseId = e, this.L = n, this.ignoreUndefinedProperties = r, // Minor hack: If fieldTransforms is undefined, we assume this is an // external call and we need to validate the entire path. void 0 === s && this.nt(), this.fieldTransforms = s || [], this.fieldMask = i || []; } get path() { return this.settings.path; } get rt() { return this.settings.rt; } /** Returns a new context with the specified settings overwritten. */ st(t) { return new An(Object.assign(Object.assign({}, this.settings), t), this.databaseId, this.L, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask); } it(t) { var e; const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), r = this.st({ path: n, ot: !1 }); return r.ut(t), r; } ct(t) { var e; const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), r = this.st({ path: n, ot: !1 }); return r.nt(), r; } at(t) { // TODO(b/34871131): We don't support array paths right now; so make path // undefined. return this.st({ path: void 0, ot: !0 }); } ht(t) { return zn(t, this.settings.methodName, this.settings.lt || !1, this.path, this.settings.ft); } /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(t) { return void 0 !== this.fieldMask.find((e => t.isPrefixOf(e))) || void 0 !== this.fieldTransforms.find((e => t.isPrefixOf(e.field))); } nt() { // TODO(b/34871131): Remove null check once we have proper paths for fields // within arrays. if (this.path) for (let t = 0; t < this.path.length; t++) this.ut(this.path.get(t)); } ut(t) { if (0 === t.length) throw this.ht("Document fields must not be empty"); if (In(this.rt) && bn.test(t)) throw this.ht('Document fields cannot begin and end with "__"'); } } /** * Helper for parsing raw user input (provided via the API) into internal model * classes. */ class Pn { constructor(t, e, n) { this.databaseId = t, this.ignoreUndefinedProperties = e, this.L = n || Ge(t); } /** Creates a new top-level parse context. */ dt(t, e, n, r = !1) { return new An({ rt: t, methodName: e, ft: n, path: Z.emptyPath(), ot: !1, lt: r }, this.databaseId, this.L, this.ignoreUndefinedProperties); } } function Rn(t) { const e = t._freezeSettings(), n = Ge(t._databaseId); return new Pn(t._databaseId, !!e.ignoreUndefinedProperties, n); } /** Parse document data from a set() call. */ function Vn(t, e, n, r, s, i = {}) { const o = t.dt(i.merge || i.mergeFields ? 2 /* MergeSet */ : 0 /* Set */ , e, n, s); jn("Data must be an object, but it was:", o, r); const u = Un(r, o); let c, a; if (i.merge) c = new bt(o.fieldMask), a = o.fieldTransforms; else if (i.mergeFields) { const t = []; for (const r of i.mergeFields) { const s = Mn(e, r, n); if (!o.contains(s)) throw new U(A, `Field '${s}' is specified in your field mask but missing from your input data.`); Wn(t, s) || t.push(s); } c = new bt(t), a = o.fieldTransforms.filter((t => c.covers(t.field))); } else c = null, a = o.fieldTransforms; return new En(new jt(u), c, a); } class Nn extends gn { _toFieldTransform(t) { if (2 /* MergeSet */ !== t.rt) throw 1 /* Update */ === t.rt ? t.ht(`${this._methodName}() can only appear at the top level of your update data`) : t.ht(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`); // No transform to add for a delete, but we need to add it to our // fieldMask so it gets deleted. return t.fieldMask.push(t.path), null; } isEqual(t) { return t instanceof Nn; } } /** * Creates a child context for parsing SerializableFieldValues. * * This is different than calling `ParseContext.contextWith` because it keeps * the fieldTransforms and fieldMask separate. * * The created context has its `dataSource` set to `UserDataSource.Argument`. * Although these values are used with writes, any elements in these FieldValues * are not considered writes since they cannot contain any FieldValue sentinels, * etc. * * @param fieldValue - The sentinel FieldValue for which to create a child * context. * @param context - The parent context. * @param arrayElement - Whether or not the FieldValue has an array. */ function Dn(t, e, n) { return new An({ rt: 3 /* Argument */ , ft: e.settings.ft, methodName: t._methodName, ot: n }, e.databaseId, e.L, e.ignoreUndefinedProperties); } class $n extends gn { _toFieldTransform(t) { return new _e(t.path, new we); } isEqual(t) { return t instanceof $n; } } class Fn extends gn { constructor(t, e) { super(t), this.wt = e; } _toFieldTransform(t) { const e = Dn(this, t, /*array=*/ !0), n = this.wt.map((t => Ln(t, e))), r = new me(n); return new _e(t.path, r); } isEqual(t) { // TODO(mrschmidt): Implement isEquals return this === t; } } class Sn extends gn { constructor(t, e) { super(t), this.wt = e; } _toFieldTransform(t) { const e = Dn(this, t, /*array=*/ !0), n = this.wt.map((t => Ln(t, e))), r = new pe(n); return new _e(t.path, r); } isEqual(t) { // TODO(mrschmidt): Implement isEquals return this === t; } } class qn extends gn { constructor(t, e) { super(t), this.yt = e; } _toFieldTransform(t) { const e = new ye(t.L, fe(t.L, this.yt)); return new _e(t.path, e); } isEqual(t) { // TODO(mrschmidt): Implement isEquals return this === t; } } /** Parse update data from an update() call. */ function xn(t, e, n, r) { const s = t.dt(1 /* Update */ , e, n); jn("Data must be an object, but it was:", s, r); const i = [], o = jt.empty(); vt(r, ((t, r) => { const u = Qn(e, t, n); // For Compat types, we have to "extract" the underlying types before // performing validation. r = c(r); const a = s.ct(u); if (r instanceof Nn) // Add it to the field mask, but don't add anything to updateData. i.push(u); else { const t = Ln(r, a); null != t && (i.push(u), o.set(u, t)); } })); const u = new bt(i); return new Tn(o, u, s.fieldTransforms); } /** Parse update data from a list of field/value arguments. */ function On(t, e, n, r, s, i) { const o = t.dt(1 /* Update */ , e, n), u = [ Mn(e, r, n) ], a = [ s ]; if (i.length % 2 != 0) throw new U(A, `Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`); for (let t = 0; t < i.length; t += 2) u.push(Mn(e, i[t])), a.push(i[t + 1]); const h = [], l = jt.empty(); // We iterate in reverse order to pick the last value for a field if the // user specified the field multiple times. for (let t = u.length - 1; t >= 0; --t) if (!Wn(h, u[t])) { const e = u[t]; let n = a[t]; // For Compat types, we have to "extract" the underlying types before // performing validation. n = c(n); const r = o.ct(e); if (n instanceof Nn) // Add it to the field mask, but don't add anything to updateData. h.push(e); else { const t = Ln(n, r); null != t && (h.push(e), l.set(e, t)); } } const f = new bt(h); return new Tn(l, f, o.fieldTransforms); } /** * Parse a "query value" (e.g. value in a where filter or a value in a cursor * bound). * * @param allowArrays - Whether the query value is an array that may directly * contain additional arrays (e.g. the operand of an `in` query). */ function Cn(t, e, n, r = !1) { return Ln(n, t.dt(r ? 4 /* ArrayArgument */ : 3 /* Argument */ , e)); } /** * Parses user data to Protobuf Values. * * @param input - Data to be parsed. * @param context - A context object representing the current path being parsed, * the source of the data being parsed, etc. * @returns The parsed value, or null if the value was a FieldValue sentinel * that should not be included in the resulting parsed data. */ function Ln(t, e) { if (kn( // Unwrap the API type from the Compat SDK. This will return the API type // from firestore-exp. t = c(t))) return jn("Unsupported field value:", e, t), Un(t, e); if (t instanceof gn) // FieldValues usually parse into transforms (except FieldValue.delete()) // in which case we do not want to include this field in our parsed data // (as doing so will overwrite the field directly prior to the transform // trying to transform it). So we don't add this location to // context.fieldMask and we return null as our parsing result. /** * "Parses" the provided FieldValueImpl, adding any necessary transforms to * context.fieldTransforms. */ return function(t, e) { // Sentinels are only supported with writes, and not within arrays. if (!In(e.rt)) throw e.ht(`${t._methodName}() can only be used with update() and set()`); if (!e.path) throw e.ht(`${t._methodName}() is not currently supported inside arrays`); const n = t._toFieldTransform(e); n && e.fieldTransforms.push(n); } /** * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue) * * @returns The parsed value */ (t, e), null; if (void 0 === t && e.ignoreUndefinedProperties) // If the input is undefined it can never participate in the fieldMask, so // don't handle this below. If `ignoreUndefinedProperties` is false, // `parseScalarValue` will reject an undefined value. return null; if ( // If context.path is null we are inside an array and we don't support // field mask paths more granular than the top-level array. e.path && e.fieldMask.push(e.path), t instanceof Array) { // TODO(b/34871131): Include the path containing the array in the error // message. // In the case of IN queries, the parsed data is an array (representing // the set of values to be included for the IN query) that may directly // contain additional arrays (each representing an individual field // value), so we disable this validation. if (e.settings.ot && 4 /* ArrayArgument */ !== e.rt) throw e.ht("Nested arrays are not supported"); return function(t, e) { const n = []; let r = 0; for (const s of t) { let t = Ln(s, e.at(r)); null == t && ( // Just include nulls in the array for fields being replaced with a // sentinel. t = { nullValue: "NULL_VALUE" }), n.push(t), r++; } return { arrayValue: { values: n } }; }(t, e); } return function(t, e) { if (null === (t = c(t))) return { nullValue: "NULL_VALUE" }; if ("number" == typeof t) return fe(e.L, t); if ("boolean" == typeof t) return { booleanValue: t }; if ("string" == typeof t) return { stringValue: t }; if (t instanceof Date) { const n = yt.fromDate(t); return { timestampValue: Ve(e.L, n) }; } if (t instanceof yt) { // Firestore backend truncates precision down to microseconds. To ensure // offline mode works the same with regards to truncation, perform the // truncation immediately without waiting for the backend to do that. const n = new yt(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3)); return { timestampValue: Ve(e.L, n) }; } if (t instanceof vn) return { geoPointValue: { latitude: t.latitude, longitude: t.longitude } }; if (t instanceof _n) return { bytesValue: Ne(e.L, t._byteString) }; if (t instanceof cn) { const n = e.databaseId, r = t.firestore._databaseId; if (!r.isEqual(n)) throw e.ht(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`); return { referenceValue: Fe(t.firestore._databaseId || e.databaseId, t._key.path) }; } throw e.ht(`Unsupported field value: ${rt(t)}`); } /** * Checks whether an object looks like a JSON object that should be converted * into a struct. Normal class/prototype instances are considered to look like * JSON objects since they should be converted to a struct value. Arrays, Dates, * GeoPoints, etc. are not considered to look like JSON objects since they map * to specific FieldValue types other than ObjectValue. */ (t, e); } function Un(t, e) { const n = {}; return !function(t) { for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1; return !0; }(t) ? vt(t, ((t, r) => { const s = Ln(r, e.it(t)); null != s && (n[t] = s); })) : // If we encounter an empty object, we explicitly add it to the update // mask to ensure that the server creates a map entry. e.path && e.path.length > 0 && e.fieldMask.push(e.path), { mapValue: { fields: n } }; } function kn(t) { return !("object" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof yt || t instanceof vn || t instanceof _n || t instanceof cn || t instanceof gn); } function jn(t, e, n) { if (!kn(n) || !function(t) { return "object" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t)); }(n)) { const r = rt(n); throw "an object" === r ? e.ht(t + " a custom object") : e.ht(t + " " + r); } } /** * Helper that calls fromDotSeparatedString() but wraps any error thrown. */ function Mn(t, e, n) { if (( // If required, replace the FieldPath Compat class with with the firestore-exp // FieldPath. e = c(e)) instanceof pn) return e._internalPath; if ("string" == typeof e) return Qn(t, e); throw zn("Field path arguments must be of type string or FieldPath.", t, /* hasConverter= */ !1, /* path= */ void 0, n); } /** * Matches any characters in a field path string that are reserved. */ const Bn = new RegExp("[~\\*/\\[\\]]"); /** * Wraps fromDotSeparatedString with an error message about the method that * was thrown. * @param methodName - The publicly visible method name * @param path - The dot-separated string form of a field path which will be * split on dots. * @param targetDoc - The document against which the field path will be * evaluated. */ function Qn(t, e, n) { if (e.search(Bn) >= 0) throw zn(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t, /* hasConverter= */ !1, /* path= */ void 0, n); try { return new pn(...e.split("."))._internalPath; } catch (r) { throw zn(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t, /* hasConverter= */ !1, /* path= */ void 0, n); } } function zn(t, e, n, r, s) { const i = r && !r.isEmpty(), o = void 0 !== s; let u = `Function ${e}() called with invalid data`; n && (u += " (via `toFirestore()`)"), u += ". "; let c = ""; return (i || o) && (c += " (found", i && (c += ` in field ${r}`), o && (c += ` in document ${s}`), c += ")"), new U(A, u + t + c); } /** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function Wn(t, e) { return t.some((t => t.isEqual(e))); } /** * @license * Copyright 2020 Google LLC * * 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. */ /** * A `DocumentSnapshot` contains data read from a document in your Firestore * database. The data can be extracted with `.data()` or `.get(<field>)` to * get a specific field. * * For a `DocumentSnapshot` that points to a non-existing document, any data * access will return 'undefined'. You can use the `exists()` method to * explicitly verify a document's existence. */ class Gn { // Note: This class is stripped down version of the DocumentSnapshot in // the legacy SDK. The changes are: // - No support for SnapshotMetadata. // - No support for SnapshotOptions. /** @hideconstructor protected */ constructor(t, e, n, r, s) { this._firestore = t, this._userDataWriter = e, this._key = n, this._document = r, this._converter = s; } /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() { return this._key.path.lastSegment(); } /** * The `DocumentReference` for the document included in the `DocumentSnapshot`. */ get ref() { return new cn(this._firestore, this._converter, this._key); } /** * Signals whether or not the document at the snapshot's location exists. * * @returns true if the document exists. */ exists() { return null !== this._document; } /** * Retrieves all fields in the document as an `Object`. Returns `undefined` if * the document doesn't exist. * * @returns An `Object` containing all fields in the document or `undefined` * if the document doesn't exist. */ data() { if (this._document) { if (this._converter) { // We only want to use the converter and create a new DocumentSnapshot // if a converter has been provided. const t = new Hn(this._firestore, this._userDataWriter, this._key, this._document, /* converter= */ null); return this._converter.fromFirestore(t); } return this._userDataWriter.convertValue(this._document.data.value); } } /** * Retrieves the field specified by `fieldPath`. Returns `undefined` if the * document or field doesn't exist. * * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific * field. * @returns The data at the specified field location or undefined if no such * field exists in the document. */ // We are using `any` here to avoid an explicit cast by our users. // eslint-disable-next-line @typescript-eslint/no-explicit-any get(t) { if (this._document) { const e = this._document.data.field(Jn("DocumentSnapshot.get", t)); if (null !== e) return this._userDataWriter.convertValue(e); } } } /** * A `QueryDocumentSnapshot` contains data read from a document in your * Firestore database as part of a query. The document is guaranteed to exist * and its data can be extracted with `.data()` or `.get(<field>)` to get a * specific field. * * A `QueryDocumentSnapshot` offers the same API surface as a * `DocumentSnapshot`. Since query results contain only existing documents, the * `exists` property will always be true and `data()` will never return * 'undefined'. */ class Hn extends Gn { /** * Retrieves all fields in the document as an `Object`. * * @override * @returns An `Object` containing all fields in the document. */ data() { return super.data(); } } /** * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects * representing the results of a query. The documents can be accessed as an * array via the `docs` property or enumerated using the `forEach` method. The * number of documents can be determined via the `empty` and `size` * properties. */ class Yn { /** @hideconstructor */ constructor(t, e) { this._docs = e, this.query = t; } /** An array of all the documents in the `QuerySnapshot`. */ get docs() { return [ ...this._docs ]; } /** The number of documents in the `QuerySnapshot`. */ get size() { return this.docs.length; } /** True if there are no documents in the `QuerySnapshot`. */ get empty() { return 0 === this.docs.length; } /** * Enumerates all of the documents in the `QuerySnapshot`. * * @param callback - A callback to be called with a `QueryDocumentSnapshot` for * each document in the snapshot. * @param thisArg - The `this` binding for the callback. */ forEach(t, e) { this._docs.forEach(t, e); } } /** * Returns true if the provided snapshots are equal. * * @param left - A snapshot to compare. * @param right - A snapshot to compare. * @returns true if the snapshots are equal. */ function Kn(t, e) { return t = c(t), e = c(e), t instanceof Gn && e instanceof Gn ? t._firestore === e._firestore && t._key.isEqual(e._key) && (null === t._document ? null === e._document : t._document.isEqual(e._document)) && t._converter === e._converter : t instanceof Yn && e instanceof Yn && (mn(t.query, e.query) && pt(t.docs, e.docs, Kn)); } /** * Helper that calls fromDotSeparatedString() but wraps any error thrown. */ function Jn(t, e) { return "string" == typeof e ? Qn(t, e) : e instanceof pn ? e._internalPath : e._delegate._internalPath; } /** * @license * Copyright 2020 Google LLC * * 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. */ /** * A `QueryConstraint` is used to narrow the set of documents returned by a * Firestore query. `QueryConstraint`s are created by invoking {@link where}, * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link * endBefore:1}, {@link (endAt:1)}, {@link limit} or {@link limitToLast} and * can then be passed to {@link query} to create a new query instance that * also contains this `QueryConstraint`. */ class Zn {} /** * Creates a new immutable instance of `Query` that is extended to also include * additional query constraints. * * @param query - The Query instance to use as a base for the new constraints. * @param queryConstraints - The list of `QueryConstraint`s to apply. * @throws if any of the provided query constraints cannot be combined with the * existing or new constraints. */ function Xn(t, ...e) { for (const n of e) t = n._apply(t); return t; } class tr extends Zn { constructor(t, e, n) { super(), this._t = t, this.gt = e, this.vt = n, this.type = "where"; } _apply(t) { const e = Rn(t.firestore), n = function(t, e, n, r, s, i, o) { let u; if (s.isKeyField()) { if ("array-contains" /* ARRAY_CONTAINS */ === i || "array-contains-any" /* ARRAY_CONTAINS_ANY */ === i) throw new U(A, `Invalid Query. You can't perform '${i}' queries on FieldPath.documentId().`); if ("in" /* IN */ === i || "not-in" /* NOT_IN */ === i) { mr(o, i); const e = []; for (const n of o) e.push(wr(r, t, n)); u = { arrayValue: { values: e } }; } else u = wr(r, t, o); } else "in" /* IN */ !== i && "not-in" /* NOT_IN */ !== i && "array-contains-any" /* ARRAY_CONTAINS_ANY */ !== i || mr(o, i), u = Cn(n, e, o, /* allowArrays= */ "in" /* IN */ === i || "not-in" /* NOT_IN */ === i); const c = zt.create(s, i, u); return function(t, e) { if (e.S()) { const n = ue(t); if (null !== n && !n.isEqual(e.field)) throw new U(A, `Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${n.toString()}' and '${e.field.toString()}'`); const r = oe(t); null !== r && pr(t, e.field, r); } const n = function(t, e) { for (const n of t.filters) if (e.indexOf(n.op) >= 0) return n.op; return null; }(t, /** * Given an operator, returns the set of operators that cannot be used with it. * * Operators in a query must adhere to the following set of rules: * 1. Only one array operator is allowed. * 2. Only one disjunctive operator is allowed. * 3. NOT_EQUAL cannot be used with another NOT_EQUAL operator. * 4. NOT_IN cannot be used with array, disjunctive, or NOT_EQUAL operators. * * Array operators: ARRAY_CONTAINS, ARRAY_CONTAINS_ANY * Disjunctive operators: IN, ARRAY_CONTAINS_ANY, NOT_IN */ function(t) { switch (t) { case "!=" /* NOT_EQUAL */ : return [ "!=" /* NOT_EQUAL */ , "not-in" /* NOT_IN */ ]; case "array-contains" /* ARRAY_CONTAINS */ : return [ "array-contains" /* ARRAY_CONTAINS */ , "array-contains-any" /* ARRAY_CONTAINS_ANY */ , "not-in" /* NOT_IN */ ]; case "in" /* IN */ : return [ "array-contains-any" /* ARRAY_CONTAINS_ANY */ , "in" /* IN */ , "not-in" /* NOT_IN */ ]; case "array-contains-any" /* ARRAY_CONTAINS_ANY */ : return [ "array-contains" /* ARRAY_CONTAINS */ , "array-contains-any" /* ARRAY_CONTAINS_ANY */ , "in" /* IN */ , "not-in" /* NOT_IN */ ]; case "not-in" /* NOT_IN */ : return [ "array-contains" /* ARRAY_CONTAINS */ , "array-contains-any" /* ARRAY_CONTAINS_ANY */ , "in" /* IN */ , "not-in" /* NOT_IN */ , "!=" /* NOT_EQUAL */ ]; default: return []; } }(e.op)); if (null !== n) // Special case when it's a duplicate op to give a slightly clearer error message. throw n === e.op ? new U(A, `Invalid query. You cannot use more than one '${e.op.toString()}' filter.`) : new U(A, `Invalid query. You cannot use '${e.op.toString()}' filters with '${n.toString()}' filters.`); }(t, c), c; }(t._query, "where", e, t.firestore._databaseId, this._t, this.gt, this.vt); return new an(t.firestore, t.converter, function(t, e) { const n = t.filters.concat([ e ]); return new se(t.path, t.collectionGroup, t.explicitOrderBy.slice(), n, t.limit, t.limitType, t.startAt, t.endAt); }(t._query, n)); } } /** * Creates a `QueryConstraint` that enforces that documents must contain the * specified field and that the value should satisfy the relation constraint * provided. * * @param fieldPath - The path to compare * @param opStr - The operation string (e.g "&lt;", "&lt;=", "==", "&lt;", * "&lt;=", "!="). * @param value - The value for comparison * @returns The created `Query`. */ function er(t, e, n) { const r = e, s = Jn("where", t); return new tr(s, r, n); } class nr extends Zn { constructor(t, e) { super(), this._t = t, this.bt = e, this.type = "orderBy"; } _apply(t) { const e = function(t, e, n) { if (null !== t.startAt) throw new U(A, "Invalid query. You must not call startAt() or startAfter() before calling orderBy()."); if (null !== t.endAt) throw new U(A, "Invalid query. You must not call endAt() or endBefore() before calling orderBy()."); const r = new ee(e, n); return function(t, e) { if (null === oe(t)) { // This is the first order by. It must match any inequality. const n = ue(t); null !== n && pr(t, n, e.field); } }(t, r), r; } /** * Create a Bound from a query and a document. * * Note that the Bound will always include the key of the document * and so only the provided document will compare equal to the returned * position. * * Will throw if the document does not contain all fields of the order by * of the query or if any of the fields in the order by are an uncommitted * server timestamp. */ (t._query, this._t, this.bt); return new an(t.firestore, t.converter, function(t, e) { // TODO(dimond): validate that orderBy does not list the same key twice. const n = t.explicitOrderBy.concat([ e ]); return new se(t.path, t.collectionGroup, n, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt); }(t._query, e)); } } /** * Creates a `QueryConstraint` that sorts the query result by the * specified field, optionally in descending order instead of ascending. * * @param fieldPath - The field to sort by. * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If * not specified, order will be ascending. * @returns The created `Query`. */ function rr(t, e = "asc") { const n = e, r = Jn("orderBy", t); return new nr(r, n); } class sr extends Zn { constructor(t, e, n) { super(), this.type = t, this.Et = e, this.Tt = n; } _apply(t) { return new an(t.firestore, t.converter, function(t, e, n) { return new se(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, n, t.startAt, t.endAt); }(t._query, this.Et, this.Tt)); } } /** * Creates a `QueryConstraint` that only returns the first matching documents. * * @param limit - The maximum number of items to return. * @returns The created `Query`. */ function ir(t) { return it("limit", t), new sr("limit", t, "F" /* First */); } /** * Creates a `QueryConstraint` that only returns the last matching documents. * * You must specify at least one `orderBy` clause for `limitToLast` queries, * otherwise an exception will be thrown during execution. * * @param limit - The maximum number of items to return. * @returns The created `Query`. */ function or(t) { return it("limitToLast", t), new sr("limitToLast", t, "L" /* Last */); } class ur extends Zn { constructor(t, e, n) { super(), this.type = t, this.It = e, this.At = n; } _apply(t) { const e = dr(t, this.type, this.It, this.At); return new an(t.firestore, t.converter, function(t, e) { return new se(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt); }(t._query, e)); } } function cr(...t) { return new ur("startAt", t, /*before=*/ !0); } function ar(...t) { return new ur("startAfter", t, /*before=*/ !1); } class hr extends Zn { constructor(t, e, n) { super(), this.type = t, this.It = e, this.At = n; } _apply(t) { const e = dr(t, this.type, this.It, this.At); return new an(t.firestore, t.converter, function(t, e) { return new se(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e); }(t._query, e)); } } function lr(...t) { return new hr("endBefore", t, /*before=*/ !0); } function fr(...t) { return new hr("endAt", t, /*before=*/ !1); } /** Helper function to create a bound from a document or fields */ function dr(t, e, n, r) { if (n[0] = c(n[0]), n[0] instanceof Gn) return function(t, e, n, r, s) { if (!r) throw new U(R, `Can't use a DocumentSnapshot that doesn't exist for ${n}().`); const i = []; // Because people expect to continue/end a query at the exact document // provided, we need to use the implicit sort order rather than the explicit // sort order, because it's guaranteed to contain the document key. That way // the position becomes unambiguous and the query continues/ends exactly at // the provided document. Without the key (by using the explicit sort // orders), multiple documents could match the position, yielding duplicate // results. for (const n of ae(t)) if (n.field.isKeyField()) i.push(xt(e, r.key)); else { const t = r.data.field(n.field); if (Rt(t)) throw new U(A, 'Invalid query. You are trying to start or end a query using a document for which the field "' + n.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)'); if (null === t) { const t = n.field.canonicalString(); throw new U(A, `Invalid query. You are trying to start or end a query using a document for which the field '${t}' (used as the orderBy) does not exist.`); } i.push(t); } return new te(i, s); } /** * Converts a list of field values to a Bound for the given query. */ (t._query, t.firestore._databaseId, e, n[0]._document, r); { const s = Rn(t.firestore); return function(t, e, n, r, s, i) { // Use explicit order by's because it has to match the query the user made const o = t.explicitOrderBy; if (s.length > o.length) throw new U(A, `Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`); const u = []; for (let i = 0; i < s.length; i++) { const c = s[i]; if (o[i].field.isKeyField()) { if ("string" != typeof c) throw new U(A, `Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof c}`); if (!ce(t) && -1 !== c.indexOf("/")) throw new U(A, `Invalid query. When querying a collection and ordering by FieldPath.documentId(), the value passed to ${r}() must be a plain document ID, but '${c}' contains a slash.`); const n = t.path.child(K.fromString(c)); if (!X.isDocumentKey(n)) throw new U(A, `Invalid query. When querying a collection group and ordering by FieldPath.documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`); const s = new X(n); u.push(xt(e, s)); } else { const t = Cn(n, r, c); u.push(t); } } return new te(u, i); } /** * Parses the given documentIdValue into a ReferenceValue, throwing * appropriate errors if the value is anything other than a DocumentReference * or String, or if the string is malformed. */ (t._query, t.firestore._databaseId, s, e, n, r); } } function wr(t, e, n) { if ("string" == typeof (n = c(n))) { if ("" === n) throw new U(A, "Invalid query. When querying with FieldPath.documentId(), you must provide a valid document ID, but it was an empty string."); if (!ce(e) && -1 !== n.indexOf("/")) throw new U(A, `Invalid query. When querying a collection by FieldPath.documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`); const r = e.path.child(K.fromString(n)); if (!X.isDocumentKey(r)) throw new U(A, `Invalid query. When querying a collection group by FieldPath.documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`); return xt(t, new X(r)); } if (n instanceof cn) return xt(t, n._key); throw new U(A, `Invalid query. When querying with FieldPath.documentId(), you must provide a valid string or a DocumentReference, but it was: ${rt(n)}.`); } /** * Validates that the value passed into a disjunctive filter satisfies all * array requirements. */ function mr(t, e) { if (!Array.isArray(t) || 0 === t.length) throw new U(A, `Invalid Query. A non-empty array is required for '${e.toString()}' filters.`); if (t.length > 10) throw new U(A, `Invalid Query. '${e.toString()}' filters support a maximum of 10 elements in the value array.`); } function pr(t, e, n) { if (!n.isEqual(e)) throw new U(A, `Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${e.toString()}' and so you must also use '${e.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`); } /** * @license * Copyright 2020 Google LLC * * 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. */ /** * Converts Firestore's internal types to the JavaScript types that we expose * to the user. * * @internal */ /** * @license * Copyright 2020 Google LLC * * 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. */ /** * Converts custom model object of type T into DocumentData by applying the * converter if it exists. * * This function is used when converting user objects to DocumentData * because we want to provide the user with a more specific error message if * their set() or fails due to invalid data originating from a toFirestore() * call. */ function yr(t, e, n) { let r; // Cast to `any` in order to satisfy the union type constraint on // toFirestore(). // eslint-disable-next-line @typescript-eslint/no-explicit-any return r = t ? n && (n.merge || n.mergeFields) ? t.toFirestore(e, n) : t.toFirestore(e) : e, r; } class _r extends class { convertValue(t, e = "none") { switch (Dt(t)) { case 0 /* NullValue */ : return null; case 1 /* BooleanValue */ : return t.booleanValue; case 2 /* NumberValue */ : return At(t.integerValue || t.doubleValue); case 3 /* TimestampValue */ : return this.convertTimestamp(t.timestampValue); case 4 /* ServerTimestampValue */ : return this.convertServerTimestamp(t, e); case 5 /* StringValue */ : return t.stringValue; case 6 /* BlobValue */ : return this.convertBytes(Pt(t.bytesValue)); case 7 /* RefValue */ : return this.convertReference(t.referenceValue); case 8 /* GeoPointValue */ : return this.convertGeoPoint(t.geoPointValue); case 9 /* ArrayValue */ : return this.convertArray(t.arrayValue, e); case 10 /* ObjectValue */ : return this.convertObject(t.mapValue, e); default: throw g(); } } convertObject(t, e) { const n = {}; return vt(t.fields, ((t, r) => { n[t] = this.convertValue(r, e); })), n; } convertGeoPoint(t) { return new vn(At(t.latitude), At(t.longitude)); } convertArray(t, e) { return (t.values || []).map((t => this.convertValue(t, e))); } convertServerTimestamp(t, e) { switch (e) { case "previous": const n = Vt(t); return null == n ? null : this.convertValue(n, e); case "estimate": return this.convertTimestamp(Nt(t)); default: return null; } } convertTimestamp(t) { const e = It(t); return new yt(e.seconds, e.nanos); } convertDocumentKey(t, e) { const n = K.fromString(t); v(We(n)); const r = new H(n.get(1), n.get(3)), s = new X(n.popFirst(5)); return r.isEqual(e) || // TODO(b/64130202): Somehow support foreign references. p(`Document ${s} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`), s; } } { constructor(t) { super(), this.firestore = t; } convertBytes(t) { return new _n(t); } convertReference(t) { const e = this.convertDocumentKey(t, this.firestore._databaseId); return new cn(this.firestore, /* converter= */ null, e); } } /** * Reads the document referred to by the specified document reference. * * All documents are directly fetched from the server, even if the document was * previously read or modified. Recent modifications are only reflected in the * retrieved `DocumentSnapshot` if they have already been applied by the * backend. If the client is offline, the read fails. If you like to use * caching or see local modifications, please use the full Firestore SDK. * * @param reference - The reference of the document to fetch. * @returns A Promise resolved with a `DocumentSnapshot` containing the current * document contents. */ function gr(t) { const e = tn((t = st(t, cn)).firestore), n = new _r(t.firestore); return Je(e, [ t._key ]).then((e => { v(1 === e.length); const r = e[0]; return new Gn(t.firestore, n, t._key, r.isFoundDocument() ? r : null, t.converter); })); } /** * Executes the query and returns the results as a {@link QuerySnapshot}. * * All queries are executed directly by the server, even if the the query was * previously executed. Recent modifications are only reflected in the retrieved * results if they have already been applied by the backend. If the client is * offline, the operation fails. To see previously cached result and local * modifications, use the full Firestore SDK. * * @param query - The `Query` to execute. * @returns A Promise that will be resolved with the results of the query. */ function vr(t) { !function(t) { if (ie(t) && 0 === t.explicitOrderBy.length) throw new U(x, "limitToLast() queries require specifying at least one orderBy() clause"); }((t = st(t, an))._query); const e = tn(t.firestore), n = new _r(t.firestore); return Ze(e, t._query).then((e => { const r = e.map((e => new Hn(t.firestore, n, e.key, e, t.converter))); return ie(t._query) && // Limit to last queries reverse the orderBy constraint that was // specified by the user. As such, we need to reverse the order of the // results to return the documents in the expected order. r.reverse(), new Yn(t, r); })); } function br(t, e, n) { const r = yr((t = st(t, cn)).converter, e, n), s = Vn(Rn(t.firestore), "setDoc", t._key, r, null !== t.converter, n); return Ke(tn(t.firestore), [ s.toMutation(t._key, ge.none()) ]); } function Er(t, e, n, ...r) { const s = Rn((t = st(t, cn)).firestore); // For Compat types, we have to "extract" the underlying types before // performing validation. let i; i = "string" == typeof (e = c(e)) || e instanceof pn ? On(s, "updateDoc", t._key, e, n, r) : xn(s, "updateDoc", t._key, e); return Ke(tn(t.firestore), [ i.toMutation(t._key, ge.exists(!0)) ]); } /** * Deletes the document referred to by the specified `DocumentReference`. * * The deletion will only be reflected in document reads that occur after the * returned Promise resolves. If the client is offline, the * delete fails. If you would like to see local modifications or buffer writes * until the client is online, use the full Firestore SDK. * * @param reference - A reference to the document to delete. * @returns A Promise resolved once the document has been successfully * deleted from the backend. */ function Tr(t) { return Ke(tn((t = st(t, cn)).firestore), [ new Te(t._key, ge.none()) ]); } /** * Add a new document to specified `CollectionReference` with the given data, * assigning it a document ID automatically. * * The result of this write will only be reflected in document reads that occur * after the returned Promise resolves. If the client is offline, the * write fails. If you would like to see local modifications or buffer writes * until the client is online, use the full Firestore SDK. * * @param reference - A reference to the collection to add this document to. * @param data - An Object containing the data for the new document. * @returns A Promise resolved with a `DocumentReference` pointing to the * newly created document after it has been written to the backend. */ function Ir(t, e) { const n = dn(t = st(t, hn)), r = yr(t.converter, e), s = Vn(Rn(t.firestore), "addDoc", n._key, r, null !== n.converter, {}); return Ke(tn(t.firestore), [ s.toMutation(n._key, ge.exists(!1)) ]).then((() => n)); } /** * @license * Copyright 2020 Google LLC * * 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. */ /** * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. */ function Ar() { return new Nn("deleteField"); } /** * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to * include a server-generated timestamp in the written data. */ function Pr() { return new $n("serverTimestamp"); } /** * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array * value that already exists on the server. Each specified element that doesn't * already exist in the array will be added to the end. If the field being * modified is not already an array it will be overwritten with an array * containing exactly the specified elements. * * @param elements - The elements to union into the array. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or * `updateDoc()`. */ function Rr(...t) { // NOTE: We don't actually parse the data until it's used in set() or // update() since we'd need the Firestore instance to do this. return new Fn("arrayUnion", t); } /** * Returns a special value that can be used with {@link (setDoc:1)} or {@link * updateDoc:1} that tells the server to remove the given elements from any * array value that already exists on the server. All instances of each element * specified will be removed from the array. If the field being modified is not * already an array it will be overwritten with an empty array. * * @param elements - The elements to remove from the array. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or * `updateDoc()` */ function Vr(...t) { // NOTE: We don't actually parse the data until it's used in set() or // update() since we'd need the Firestore instance to do this. return new Sn("arrayRemove", t); } /** * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by * the given value. * * If either the operand or the current field value uses floating point * precision, all arithmetic follows IEEE 754 semantics. If both values are * integers, values outside of JavaScript's safe number range * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to * precision loss. Furthermore, once processed by the Firestore backend, all * integer operations are capped between -2^63 and 2^63-1. * * If the current field value is not of type `number`, or if the field does not * yet exist, the transformation sets the field to the given value. * * @param n - The value to increment by. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or * `updateDoc()` */ function Nr(t) { return new qn("increment", t); } /** * @license * Copyright 2020 Google LLC * * 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. */ /** * A write batch, used to perform multiple writes as a single atomic unit. * * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It * provides methods for adding writes to the write batch. None of the writes * will be committed (or visible locally) until {@link WriteBatch.commit} is * called. */ class Dr { /** @hideconstructor */ constructor(t, e) { this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1, this._dataReader = Rn(t); } set(t, e, n) { this._verifyNotCommitted(); const r = $r(t, this._firestore), s = yr(r.converter, e, n), i = Vn(this._dataReader, "WriteBatch.set", r._key, s, null !== r.converter, n); return this._mutations.push(i.toMutation(r._key, ge.none())), this; } update(t, e, n, ...r) { this._verifyNotCommitted(); const s = $r(t, this._firestore); // For Compat types, we have to "extract" the underlying types before // performing validation. let i; return i = "string" == typeof (e = c(e)) || e instanceof pn ? On(this._dataReader, "WriteBatch.update", s._key, e, n, r) : xn(this._dataReader, "WriteBatch.update", s._key, e), this._mutations.push(i.toMutation(s._key, ge.exists(!0))), this; } /** * Deletes the document referred to by the provided {@link DocumentReference}. * * @param documentRef - A reference to the document to be deleted. * @returns This `WriteBatch` instance. Used for chaining method calls. */ delete(t) { this._verifyNotCommitted(); const e = $r(t, this._firestore); return this._mutations = this._mutations.concat(new Te(e._key, ge.none())), this; } /** * Commits all of the writes in this write batch as a single atomic unit. * * The result of these writes will only be reflected in document reads that * occur after the returned Promise resolves. If the client is offline, the * write fails. If you would like to see local modifications or buffer writes * until the client is online, use the full Firestore SDK. * * @returns A Promise resolved once all of the writes in the batch have been * successfully written to the backend as an atomic unit (note that it won't * resolve while you're offline). */ commit() { return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve(); } _verifyNotCommitted() { if (this._committed) throw new U(F, "A write batch can no longer be used after commit() has been called."); } } function $r(t, e) { if ((t = c(t)).firestore !== e) throw new U(A, "Provided document reference is from a different Firestore instance."); return t; } /** * Creates a write batch, used for performing multiple writes as a single * atomic operation. The maximum number of writes allowed in a single WriteBatch * is 500. * * The result of these writes will only be reflected in document reads that * occur after the returned Promise resolves. If the client is offline, the * write fails. If you would like to see local modifications or buffer writes * until the client is online, use the full Firestore SDK. * * @returns A `WriteBatch` that can be used to atomically execute multiple * writes. */ function Fr(t) { const e = tn(t = st(t, nn)); return new Dr(t, (t => Ke(e, t))); } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Internal transaction object responsible for accumulating the mutations to * perform and the base versions for any documents read. */ class Sr { constructor(t) { this.datastore = t, // The version of each document that was read during this transaction. this.readVersions = new Map, this.mutations = [], this.committed = !1, /** * A deferred usage error that occurred previously in this transaction that * will cause the transaction to fail once it actually commits. */ this.lastWriteError = null, /** * Set of documents that have been written in the transaction. * * When there's more than one write to the same key in a transaction, any * writes after the first are handled differently. */ this.writtenDocs = new Set; } async lookup(t) { if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw new U(A, "Firestore transactions require all reads to be executed before all writes."); const e = await Je(this.datastore, t); return e.forEach((t => this.recordVersion(t))), e; } set(t, e) { this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString()); } update(t, e) { try { this.write(e.toMutation(t, this.preconditionForUpdate(t))); } catch (t) { this.lastWriteError = t; } this.writtenDocs.add(t.toString()); } delete(t) { this.write(new Te(t, this.precondition(t))), this.writtenDocs.add(t.toString()); } async commit() { if (this.ensureCommitNotCalled(), this.lastWriteError) throw this.lastWriteError; const t = this.readVersions; // For each mutation, note that the doc was written. this.mutations.forEach((e => { t.delete(e.key.toString()); })), // For each document that was read but not written to, we want to perform // a `verify` operation. t.forEach(((t, e) => { const n = X.fromPath(e); this.mutations.push(new Ie(n, this.precondition(n))); })), await Ke(this.datastore, this.mutations), this.committed = !0; } recordVersion(t) { let e; if (t.isFoundDocument()) e = t.version; else { if (!t.isNoDocument()) throw g(); // For deleted docs, we must use baseVersion 0 when we overwrite them. e = _t.min(); } const n = this.readVersions.get(t.key.toString()); if (n) { if (!e.isEqual(n)) // This transaction will fail no matter what. throw new U(S, "Document version changed between two reads."); } else this.readVersions.set(t.key.toString(), e); } /** * Returns the version of this document when it was read in this transaction, * as a precondition, or no precondition if it was not read. */ precondition(t) { const e = this.readVersions.get(t.toString()); return !this.writtenDocs.has(t.toString()) && e ? ge.updateTime(e) : ge.none(); } /** * Returns the precondition for a document if the operation is an update. */ preconditionForUpdate(t) { const e = this.readVersions.get(t.toString()); // The first time a document is written, we want to take into account the // read time and existence if (!this.writtenDocs.has(t.toString()) && e) { if (e.isEqual(_t.min())) // The document doesn't exist, so fail the transaction. // This has to be validated locally because you can't send a // precondition that a document does not exist without changing the // semantics of the backend write to be an insert. This is the reverse // of what we want, since we want to assert that the document doesn't // exist but then send the update and have it fail. Since we can't // express that to the backend, we have to validate locally. // Note: this can change once we can send separate verify writes in the // transaction. throw new U(A, "Can't update a document that doesn't exist."); // Document exists, base precondition on document update time. return ge.updateTime(e); } // Document was not read, so we just use the preconditions for a blind // update. return ge.exists(!0); } write(t) { this.ensureCommitNotCalled(), this.mutations.push(t); } ensureCommitNotCalled() {} } /** * @license * Copyright 2019 Google LLC * * 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. */ /** * TransactionRunner encapsulates the logic needed to run and retry transactions * with backoff. */ class qr { constructor(t, e, n, r) { this.asyncQueue = t, this.datastore = e, this.updateFunction = n, this.deferred = r, this.Pt = 5, this.Rt = new He(this.asyncQueue, "transaction_retry" /* TransactionRetry */); } /** Runs the transaction and sets the result on deferred. */ run() { this.Pt -= 1, this.Vt(); } Vt() { this.Rt.K((async () => { const t = new Sr(this.datastore), e = this.Nt(t); e && e.then((e => { this.asyncQueue.enqueueAndForget((() => t.commit().then((() => { this.deferred.resolve(e); })).catch((t => { this.Dt(t); })))); })).catch((t => { this.Dt(t); })); })); } Nt(t) { try { const e = this.updateFunction(t); return !ot(e) && e.catch && e.then ? e : (this.deferred.reject(Error("Transaction callback must return a Promise")), null); } catch (t) { // Do not retry errors thrown by user provided updateFunction. return this.deferred.reject(t), null; } } Dt(t) { this.Pt > 0 && this.$t(t) ? (this.Pt -= 1, this.asyncQueue.enqueueAndForget((() => (this.Vt(), Promise.resolve())))) : this.deferred.reject(t); } $t(t) { if ("FirebaseError" === t.name) { // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and // non-matching document versions with ABORTED. These errors should be retried. const e = t.code; return "aborted" === e || "failed-precondition" === e || ! /** * Determines whether an error code represents a permanent error when received * in response to a non-write operation. * * See isPermanentWriteError for classifying write errors. */ function(t) { switch (t) { case E: return g(); case T: case I: case P: case $: case O: case C: // Unauthenticated means something went wrong with our token and we need // to retry with new credentials which will happen automatically. case D: return !1; case A: case R: case V: case N: case F: // Aborted might be retried in some scenarios, but that is dependant on // the context and should handled individually by the calling code. // See https://cloud.google.com/apis/design/errors. case S: case q: case x: case L: return !0; default: return g(); } }(e); } return !1; } } /** * @license * Copyright 2020 Google LLC * * 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. */ /** The Platform's 'document' implementation or null if not available. */ function xr() { // `document` is not always available, e.g. in ReactNative and WebWorkers. // eslint-disable-next-line no-restricted-globals return "undefined" != typeof document ? document : null; } /** * @license * Copyright 2017 Google LLC * * 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. */ /** * Represents an operation scheduled to be run in the future on an AsyncQueue. * * It is created via DelayedOperation.createAndSchedule(). * * Supports cancellation (via cancel()) and early execution (via skipDelay()). * * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type * in newer versions of TypeScript defines `finally`, which is not available in * IE. */ class Or { constructor(t, e, n, r, s) { this.asyncQueue = t, this.timerId = e, this.targetTimeMs = n, this.op = r, this.removalCallback = s, this.deferred = new k, this.then = this.deferred.promise.then.bind(this.deferred.promise), // It's normal for the deferred promise to be canceled (due to cancellation) // and so we attach a dummy catch callback to avoid // 'UnhandledPromiseRejectionWarning' log spam. this.deferred.promise.catch((t => {})); } /** * Creates and returns a DelayedOperation that has been scheduled to be * executed on the provided asyncQueue after the provided delayMs. * * @param asyncQueue - The queue to schedule the operation on. * @param id - A Timer ID identifying the type of operation this is. * @param delayMs - The delay (ms) before the operation should be scheduled. * @param op - The operation to run. * @param removalCallback - A callback to be called synchronously once the * operation is executed or canceled, notifying the AsyncQueue to remove it * from its delayedOperations list. * PORTING NOTE: This exists to prevent making removeDelayedOperation() and * the DelayedOperation class public. */ static createAndSchedule(t, e, n, r, s) { const i = Date.now() + n, o = new Or(t, e, i, r, s); return o.start(n), o; } /** * Starts the timer. This is called immediately after construction by * createAndSchedule(). */ start(t) { this.timerHandle = setTimeout((() => this.handleDelayElapsed()), t); } /** * Queues the operation to run immediately (if it hasn't already been run or * canceled). */ skipDelay() { return this.handleDelayElapsed(); } /** * Cancels the operation if it hasn't already been executed or canceled. The * promise will be rejected. * * As long as the operation has not yet been run, calling cancel() provides a * guarantee that the operation will not be run. */ cancel(t) { null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new U(T, "Operation cancelled" + (t ? ": " + t : "")))); } handleDelayElapsed() { this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(), this.op().then((t => this.deferred.resolve(t)))) : Promise.resolve())); } clearTimeout() { null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), this.timerHandle = null); } } /** * @license * Copyright 2020 Google LLC * * 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. */ class Cr { constructor() { // The last promise in the queue. this.Ft = Promise.resolve(), // A list of retryable operations. Retryable operations are run in order and // retried with backoff. this.St = [], // Is this AsyncQueue being shut down? Once it is set to true, it will not // be changed again. this.qt = !1, // Operations scheduled to be queued in the future. Operations are // automatically removed after they are run or canceled. this.xt = [], // visible for testing this.Ot = null, // Flag set while there's an outstanding AsyncQueue operation, used for // assertion sanity-checks. this.Ct = !1, // Enabled during shutdown on Safari to prevent future access to IndexedDB. this.Lt = !1, // List of TimerIds to fast-forward delays for. this.Ut = [], // Backoff timer used to schedule retries for retryable operations this.Rt = new He(this, "async_queue_retry" /* AsyncQueueRetry */), // Visibility handler that triggers an immediate retry of all retryable // operations. Meant to speed up recovery when we regain file system access // after page comes into foreground. this.kt = () => { const t = xr(); t && m("AsyncQueue", "Visibility state changed to " + t.visibilityState), this.Rt.Z(); }; const t = xr(); t && "function" == typeof t.addEventListener && t.addEventListener("visibilitychange", this.kt); } get isShuttingDown() { return this.qt; } /** * Adds a new operation to the queue without waiting for it to complete (i.e. * we ignore the Promise result). */ enqueueAndForget(t) { // eslint-disable-next-line @typescript-eslint/no-floating-promises this.enqueue(t); } enqueueAndForgetEvenWhileRestricted(t) { this.jt(), // eslint-disable-next-line @typescript-eslint/no-floating-promises this.Mt(t); } enterRestrictedMode(t) { if (!this.qt) { this.qt = !0, this.Lt = t || !1; const e = xr(); e && "function" == typeof e.removeEventListener && e.removeEventListener("visibilitychange", this.kt); } } enqueue(t) { if (this.jt(), this.qt) // Return a Promise which never resolves. return new Promise((() => {})); // Create a deferred Promise that we can return to the callee. This // allows us to return a "hanging Promise" only to the callee and still // advance the queue even when the operation is not run. const e = new k; return this.Mt((() => this.qt && this.Lt ? Promise.resolve() : (t().then(e.resolve, e.reject), e.promise))).then((() => e.promise)); } enqueueRetryable(t) { this.enqueueAndForget((() => (this.St.push(t), this.Bt()))); } /** * Runs the next operation from the retryable queue. If the operation fails, * reschedules with backoff. */ async Bt() { if (0 !== this.St.length) { try { await this.St[0](), this.St.shift(), this.Rt.reset(); } catch (t) { if (! /** * @license * Copyright 2017 Google LLC * * 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. */ /** Verifies whether `e` is an IndexedDbTransactionError. */ function(t) { // Use name equality, as instanceof checks on errors don't work with errors // that wrap other errors. return "IndexedDbTransactionError" === t.name; } /** * @license * Copyright 2020 Google LLC * * 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. */ (t)) throw t; // Failure will be handled by AsyncQueue m("AsyncQueue", "Operation failed with retryable error: " + t); } this.St.length > 0 && // If there are additional operations, we re-schedule `retryNextOp()`. // This is necessary to run retryable operations that failed during // their initial attempt since we don't know whether they are already // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1` // needs to be re-run, we will run `op1`, `op1`, `op2` using the // already enqueued calls to `retryNextOp()`. `op3()` will then run in the // call scheduled here. // Since `backoffAndRun()` cancels an existing backoff and schedules a // new backoff on every call, there is only ever a single additional // operation in the queue. this.Rt.K((() => this.Bt())); } } Mt(t) { const e = this.Ft.then((() => (this.Ct = !0, t().catch((t => { this.Ot = t, this.Ct = !1; // Re-throw the error so that this.tail becomes a rejected Promise and // all further attempts to chain (via .then) will just short-circuit // and return the rejected Promise. throw p("INTERNAL UNHANDLED ERROR: ", /** * Chrome includes Error.message in Error.stack. Other browsers do not. * This returns expected output of message + stack when available. * @param error - Error or FirestoreError */ function(t) { let e = t.message || ""; t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack); return e; } /** * @license * Copyright 2020 Google LLC * * 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. */ // TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the // legacy SDK. /** * A reference to a transaction. * * The `Transaction` object passed to a transaction's `updateFunction` provides * the methods to read and write data within the transaction context. See * {@link runTransaction}. */ (t)), t; })).then((t => (this.Ct = !1, t)))))); return this.Ft = e, e; } enqueueAfterDelay(t, e, n) { this.jt(), // Fast-forward delays for timerIds that have been overriden. this.Ut.indexOf(t) > -1 && (e = 0); const r = Or.createAndSchedule(this, t, e, n, (t => this.Qt(t))); return this.xt.push(r), r; } jt() { this.Ot && g(); } verifyOperationInProgress() {} /** * Waits until all currently queued tasks are finished executing. Delayed * operations are not run. */ async zt() { // Operations in the queue prior to draining may have enqueued additional // operations. Keep draining the queue until the tail is no longer advanced, // which indicates that no more new operations were enqueued and that all // operations were executed. let t; do { t = this.Ft, await t; } while (t !== this.Ft); } /** * For Tests: Determine if a delayed operation with a particular TimerId * exists. */ Wt(t) { for (const e of this.xt) if (e.timerId === t) return !0; return !1; } /** * For Tests: Runs some or all delayed operations early. * * @param lastTimerId - Delayed operations up to and including this TimerId * will be drained. Pass TimerId.All to run all delayed operations. * @returns a Promise that resolves once all operations have been run. */ Gt(t) { // Note that draining may generate more delayed ops, so we do that first. return this.zt().then((() => { // Run ops in the same order they'd run if they ran naturally. this.xt.sort(((t, e) => t.targetTimeMs - e.targetTimeMs)); for (const e of this.xt) if (e.skipDelay(), "all" /* All */ !== t && e.timerId === t) break; return this.zt(); })); } /** * For Tests: Skip all subsequent delays for a timer id. */ Ht(t) { this.Ut.push(t); } /** Called once a DelayedOperation is run or canceled. */ Qt(t) { // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small. const e = this.xt.indexOf(t); this.xt.splice(e, 1); } } class Lr { /** @hideconstructor */ constructor(t, e) { this._firestore = t, this._transaction = e, this._dataReader = Rn(t); } /** * Reads the document referenced by the provided {@link DocumentReference}. * * @param documentRef - A reference to the document to be read. * @returns A `DocumentSnapshot` with the read data. */ get(t) { const e = $r(t, this._firestore), n = new _r(this._firestore); return this._transaction.lookup([ e._key ]).then((t => { if (!t || 1 !== t.length) return g(); const r = t[0]; if (r.isFoundDocument()) return new Gn(this._firestore, n, r.key, r, e.converter); if (r.isNoDocument()) return new Gn(this._firestore, n, e._key, null, e.converter); throw g(); })); } set(t, e, n) { const r = $r(t, this._firestore), s = yr(r.converter, e, n), i = Vn(this._dataReader, "Transaction.set", r._key, s, null !== r.converter, n); return this._transaction.set(r._key, i), this; } update(t, e, n, ...r) { const s = $r(t, this._firestore); // For Compat types, we have to "extract" the underlying types before // performing validation. let i; return i = "string" == typeof (e = c(e)) || e instanceof pn ? On(this._dataReader, "Transaction.update", s._key, e, n, r) : xn(this._dataReader, "Transaction.update", s._key, e), this._transaction.update(s._key, i), this; } /** * Deletes the document referred to by the provided {@link DocumentReference}. * * @param documentRef - A reference to the document to be deleted. * @returns This `Transaction` instance. Used for chaining method calls. */ delete(t) { const e = $r(t, this._firestore); return this._transaction.delete(e._key), this; } } /** * Executes the given `updateFunction` and then attempts to commit the changes * applied within the transaction. If any document read within the transaction * has changed, Cloud Firestore retries the `updateFunction`. If it fails to * commit after 5 attempts, the transaction fails. * * The maximum number of writes allowed in a single transaction is 500. * * @param firestore - A reference to the Firestore database to run this * transaction against. * @param updateFunction - The function to execute within the transaction * context. * @returns If the transaction completed successfully or was explicitly aborted * (the `updateFunction` returned a failed promise), the promise returned by the * `updateFunction `is returned here. Otherwise, if the transaction failed, a * rejected promise with the corresponding failure error is returned. */ function Ur(t, e) { const n = tn(t = st(t, nn)), r = new k; return new qr(new Cr, n, (n => e(new Lr(t, n))), r).run(), r.promise; } /** * Firestore Lite * * @remarks Firestore Lite is a small online-only SDK that allows read * and write access to your Firestore database. All operations connect * directly to the backend, and `onSnapshot()` APIs are not supported. * @packageDocumentation */ !function(t) { l = t; }(`${i}_lite`), r(new o("firestore/lite", ((t, {options: e}) => { const n = t.getProvider("app-exp").getImmediate(), r = new nn(n, t.getProvider("auth-internal")); return e && r._setSettings(e), r; }), "PUBLIC" /* PUBLIC */)), s("firestore-lite", "2.4.0", "node"); export { _n as Bytes, hn as CollectionReference, cn as DocumentReference, Gn as DocumentSnapshot, pn as FieldPath, gn as FieldValue, nn as Firestore, U as FirestoreError, vn as GeoPoint, an as Query, Zn as QueryConstraint, Hn as QueryDocumentSnapshot, Yn as QuerySnapshot, yt as Timestamp, Lr as Transaction, Dr as WriteBatch, Ir as addDoc, Vr as arrayRemove, Rr as arrayUnion, ln as collection, fn as collectionGroup, on as connectFirestoreEmulator, Tr as deleteDoc, Ar as deleteField, dn as doc, yn as documentId, fr as endAt, lr as endBefore, gr as getDoc, vr as getDocs, sn as getFirestore, Nr as increment, rn as initializeFirestore, ir as limit, or as limitToLast, rr as orderBy, Xn as query, mn as queryEqual, wn as refEqual, Ur as runTransaction, Pr as serverTimestamp, br as setDoc, w as setLogLevel, Kn as snapshotEqual, ar as startAfter, cr as startAt, un as terminate, Er as updateDoc, er as where, Fr as writeBatch }; //# sourceMappingURL=index.browser.esm2017.js.map
// Makes sure animations has ended required for animate.css $.fn.extend({ animateCss: function (animationName, callback) { var animationEnd = (function (el) { var animations = { animation: 'animationend', OAnimation: 'oAnimationEnd', MozAnimation: 'mozAnimationEnd', WebkitAnimation: 'webkitAnimationEnd', }; for (var t in animations) { if (el.style[t] !== undefined) { return animations[t]; } } })(document.createElement('div')); this.addClass('animated ' + animationName).one(animationEnd, function () { $(this).removeClass('animated ' + animationName); if (typeof callback === 'function') callback(); }); return this; }, }); if (Storage) { let items = JSON.parse(localStorage.getItem("listitems")); if (items && items.length > 0) { for (let c = 0; c < items.length; c++) { if (isStorageItemExpired(items[c].lastUpdated)) { storageItemDelete(items[c].task); continue; } let newItem = `<li class=\"todoitems\"> <button class=\"donebtn\"> <i class=\"fas fa-check fa-lg\"></i> </button>\ <span class="items`; if (items[c].finished === true) { newItem += " completedtask\" contenteditable=\"false\">"; } else { newItem += "\" contenteditable=\"true\">"; } newItem += items[c].task + `</span> <button class="delbtn">\ <i class="fas fa-times fa-lg"></i>\ </button>\ </li>`; $('.ullist').prepend(newItem); } } } // Get's current date and display's it to the user let date = new Date(); let day = $('#day').text(["Sunday,", "Monday,", "Tuesday,", "Wednesday,", "Thursday,", "Friday,", "Saturday,"][(new Date()).getDay()]); let currentday = $('#dayofweek').text(date.getDate()); let month = $('#month').text(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][(new Date()).getDay()]); let currentYear = $('#year').text(date.getFullYear()); // Get's the current time let hours = date.getHours(); // Set's the background according to the time of day if (hours < 6 || hours > 19) { if (!$('.bodyhead').hasClass('nightbg')) $('.bodyhead').addClass('nightbg'); if ($('.bodyhead').hasClass('daybg')) $('.bodyhead').removeClass('daybg'); } else { if ($('.bodyhead').hasClass('nightbg')) $('.bodyhead').removeClass('nightbg'); if (!$('.bodyhead').hasClass('daybg')) $('.bodyhead').addClass('daybg'); } $("#listinput").keyup(function(event) { if (event.keyCode === 13) { $("#additembtn").click(); } }); // Disable the add button if input isn't focused $(document).ready(function (e) { $('#additembtn').prop('disabled', true); $('#listinput').keyup(function () { let inputVal = $('#listinput').val(); $('#additembtn').prop('disabled', !inputVal || inputVal.length < 2 ? true : false); }); // adds items to the list $('#additembtn').click(function (e) { let inputValue = $('#listinput').val(); if (!inputValue || inputValue.length < 2) return; let dataArray = []; if (localStorage.getItem('listitems')) { let oldData = JSON.parse(localStorage.getItem('listitems')); for (let i = 0; i < oldData.length; i++) { dataArray.push(oldData[i]); } } dataArray.push({ finished: false, task: inputValue, lastUpdated: getUnixTime() }); localStorage.setItem('listitems', JSON.stringify(dataArray)); $('.ullist').prepend('\ <li class="todoitems">\ <button class="donebtn">\ <i class="fas fa-check fa-lg"></i>\ </button>\ <span class="items" contenteditable="true">' + $('#listinput').val() + '</span>\ <button class="delbtn">\ <i class="fas fa-times fa-lg"></i>\ </button>\ </li>\ ') $('li:first').animateCss('fadeInDown'); $('#listinput').focus(); $('#listinput').val(''); $('#additembtn').prop('disabled', true); }); }); // Removes items on the list $(document).on('click', '.delbtn', function () { let self = this; $(self).parent().animateCss('fadeOutLeft', function () { storageItemDelete($(self).parent().children('.items').text()); $(self).parent().remove(); }); }); // Marks the list item done $(document).on('click', '.donebtn', function () { let self = this; if ($(self).parent().children('.items').hasClass('completedtask')) { storageToggleStatus($(self).parent().children('.items').text()); $(self).parent().children('.items').removeClass('completedtask'); $(self).removeClass('donebtncomplete'); $(self).parent().children('.items').prop('contenteditable', true); } else { storageToggleStatus($(self).parent().children('.items').text()); $(self).parent().children('.items').addClass('completedtask'); $(self).addClass('donebtncomplete'); $(self).parent().children('.items').prop('contenteditable', false); } }); /** * Checks if a storage item has expired and should be deleted. * @param {uinteger} lastUpdated * @param {uinteger} expiration */ function isStorageItemExpired(lastUpdated, expiration = 7) { return getUnixTime() > lastUpdated + secondsInDays(expiration); } /** * Get amount of seconds from a number of days */ function secondsInDays(days) { return 60 * 60 * 24 * days; } /** * Gets the current unix timestamp */ function getUnixTime() { return Math.floor(Date.now() / 1000); } /** * Toggles the completed status of the storage item. * @param {string} taskText */ function storageToggleStatus(taskText) { let storedItems = JSON.parse(localStorage.getItem('listitems')); if (storedItems && storedItems.length <= 0) return; let newItems = []; for (let i = 0; i < storedItems.length; i++) { if (storedItems[i].task == taskText) { storedItems[i].finished = !storedItems[i].finished; storedItems[i].lastUpdated = getUnixTime(); for (let a = 0; a < storedItems.length; a++) { newItems.push(storedItems[a]); } localStorage.setItem('listitems', JSON.stringify(newItems)); break; } } } /** * Deletes the storage item by its task text. * @param {string} taskText */ function storageItemDelete(taskText) { let storedItems = JSON.parse(localStorage.getItem('listitems')); let newItems = []; if (storedItems && storedItems.length > 0) { for (let i = 0; i < storedItems.length; i++) { if (storedItems[i].task == taskText) continue; newItems.push(storedItems[i]); } } localStorage.setItem('listitems', JSON.stringify(newItems)); }
const path = require('path'); module.exports = (node, scope) => { const [libName, ident, type] = node.tree; if (typeof ident === 'string' && scope.variables.has(ident)) { throw error(node, 'REDECLARATION', ident); } else if (Array.isArray(ident)) { for (const [, importID] of ident) { if (scope.variables.has(importID)) { throw error(node, 'REDECLARATION', importID); } } } const libPath = type === 'std' ? scope.program.constructor.getSTDLibPath() : scope.program.getModulesPath(); const imports = scope.program.importModule(node, path.join(libPath, libName)); if (Array.isArray(ident)) { for (const [id, importID] of ident) { if (!imports.has(id)) { throw error(node, 'EXPORT_NOT_EXIST', id); } scope.variables.set(importID, imports.get(id)); scope.constants.add(importID); } return null; } if (ident === undefined) { for (const [key, value] of imports) { scope.variables.set(key, value); scope.constants.add(key); } return null; } const value = new StrexpDictionary(imports); value.frozen = true; scope.variables.set(ident, value); scope.constants.add(ident); return value; }; const error = require('../../Errors'); const StrexpDictionary = require('../../types/StrexpDictionary');
describe('Chart.controllers.bar', function() { describe('auto', jasmine.specsFromFixtures('controller.bar')); it('should be constructed', function() { var chart = window.acquireChart({ type: 'bar', data: { datasets: [ {data: []}, {data: []} ], labels: [] } }); var meta = chart.getDatasetMeta(1); expect(meta.type).toEqual('bar'); expect(meta.data).toEqual([]); expect(meta.hidden).toBe(null); expect(meta.controller).not.toBe(undefined); expect(meta.controller.index).toBe(1); expect(meta.xAxisID).not.toBe(null); expect(meta.yAxisID).not.toBe(null); meta.controller.updateIndex(0); expect(meta.controller.index).toBe(0); }); it('should use the first scale IDs if the dataset does not specify them', function() { var chart = window.acquireChart({ type: 'bar', data: { datasets: [ {data: []}, {data: []} ], labels: [] }, options: { scales: { xAxes: [{ id: 'firstXScaleID' }], yAxes: [{ id: 'firstYScaleID' }] } } }); var meta = chart.getDatasetMeta(1); expect(meta.xAxisID).toBe('firstXScaleID'); expect(meta.yAxisID).toBe('firstYScaleID'); }); it('should correctly count the number of stacks ignoring datasets of other types and hidden datasets', function() { [ 'bar', 'horizontalBar' ].forEach(function(barType) { var chart = window.acquireChart({ type: barType, data: { datasets: [ {data: [], type: 'line'}, {data: [], hidden: true}, {data: []}, {data: []} ], labels: [] } }); var meta = chart.getDatasetMeta(1); expect(meta.controller.getStackCount()).toBe(2); }); }); it('should correctly count the number of stacks when a group is not specified', function() { [ 'bar', 'horizontalBar' ].forEach(function(barType) { var chart = window.acquireChart({ type: barType, data: { datasets: [ {data: []}, {data: []}, {data: []}, {data: []} ], labels: [] } }); var meta = chart.getDatasetMeta(1); expect(meta.controller.getStackCount()).toBe(4); }); }); it('should correctly count the number of stacks when a group is not specified and the scale is stacked', function() { [ 'bar', 'horizontalBar' ].forEach(function(barType) { var chart = window.acquireChart({ type: barType, data: { datasets: [ {data: []}, {data: []}, {data: []}, {data: []} ], labels: [] }, options: { scales: { xAxes: [{ stacked: true }], yAxes: [{ stacked: true }] } } }); var meta = chart.getDatasetMeta(1); expect(meta.controller.getStackCount()).toBe(1); }); }); it('should correctly count the number of stacks when a group is not specified and the scale is not stacked', function() { [ 'bar', 'horizontalBar' ].forEach(function(barType) { var chart = window.acquireChart({ type: barType, data: { datasets: [ {data: []}, {data: []}, {data: []}, {data: []} ], labels: [] }, options: { scales: { xAxes: [{ stacked: false }], yAxes: [{ stacked: false }] } } }); var meta = chart.getDatasetMeta(1); expect(meta.controller.getStackCount()).toBe(4); }); }); it('should correctly count the number of stacks when a group is specified for some', function() { [ 'bar', 'horizontalBar' ].forEach(function(barType) { var chart = window.acquireChart({ type: barType, data: { datasets: [ {data: [], stack: 'stack1'}, {data: [], stack: 'stack1'}, {data: []}, {data: []} ], labels: [] } }); var meta = chart.getDatasetMeta(3); expect(meta.controller.getStackCount()).toBe(3); }); }); it('should correctly count the number of stacks when a group is specified for some and the scale is stacked', function() { [ 'bar', 'horizontalBar' ].forEach(function(barType) { var chart = window.acquireChart({ type: barType, data: { datasets: [ {data: [], stack: 'stack1'}, {data: [], stack: 'stack1'}, {data: []}, {data: []} ], labels: [] }, options: { scales: { xAxes: [{ stacked: true }], yAxes: [{ stacked: true }] } } }); var meta = chart.getDatasetMeta(3); expect(meta.controller.getStackCount()).toBe(2); }); }); it('should correctly count the number of stacks when a group is specified for some and the scale is not stacked', function() { [ 'bar', 'horizontalBar' ].forEach(function(barType) { var chart = window.acquireChart({ type: barType, data: { datasets: [ {data: [], stack: 'stack1'}, {data: [], stack: 'stack1'}, {data: []}, {data: []} ], labels: [] }, options: { scales: { xAxes: [{ stacked: false }], yAxes: [{ stacked: false }] } } }); var meta = chart.getDatasetMeta(3); expect(meta.controller.getStackCount()).toBe(4); }); }); it('should correctly count the number of stacks when a group is specified for all', function() { [ 'bar', 'horizontalBar' ].forEach(function(barType) { var chart = window.acquireChart({ type: barType, data: { datasets: [ {data: [], stack: 'stack1'}, {data: [], stack: 'stack1'}, {data: [], stack: 'stack2'}, {data: [], stack: 'stack2'} ], labels: [] } }); var meta = chart.getDatasetMeta(3); expect(meta.controller.getStackCount()).toBe(2); }); }); it('should correctly count the number of stacks when a group is specified for all and the scale is stacked', function() { [ 'bar', 'horizontalBar' ].forEach(function(barType) { var chart = window.acquireChart({ type: barType, data: { datasets: [ {data: [], stack: 'stack1'}, {data: [], stack: 'stack1'}, {data: [], stack: 'stack2'}, {data: [], stack: 'stack2'} ], labels: [] }, options: { scales: { xAxes: [{ stacked: true }], yAxes: [{ stacked: true }] } } }); var meta = chart.getDatasetMeta(3); expect(meta.controller.getStackCount()).toBe(2); }); }); it('should correctly count the number of stacks when a group is specified for all and the scale is not stacked', function() { [ 'bar', 'horizontalBar' ].forEach(function(barType) { var chart = window.acquireChart({ type: barType, data: { datasets: [ {data: [], stack: 'stack1'}, {data: [], stack: 'stack1'}, {data: [], stack: 'stack2'}, {data: [], stack: 'stack2'} ], labels: [] }, options: { scales: { xAxes: [{ stacked: false }], yAxes: [{ stacked: false }] } } }); var meta = chart.getDatasetMeta(3); expect(meta.controller.getStackCount()).toBe(4); }); }); it('should correctly get the stack index accounting for datasets of other types and hidden datasets', function() { [ 'bar', 'horizontalBar' ].forEach(function(barType) { var chart = window.acquireChart({ type: barType, data: { datasets: [ {data: []}, {data: [], hidden: true}, {data: [], type: 'line'}, {data: []} ], labels: [] } }); var meta = chart.getDatasetMeta(1); expect(meta.controller.getStackIndex(0)).toBe(0); expect(meta.controller.getStackIndex(3)).toBe(1); }); }); it('should correctly get the stack index when a group is not specified', function() { [ 'bar', 'horizontalBar' ].forEach(function(barType) { var chart = window.acquireChart({ type: barType, data: { datasets: [ {data: []}, {data: []}, {data: []}, {data: []} ], labels: [] } }); var meta = chart.getDatasetMeta(1); expect(meta.controller.getStackIndex(0)).toBe(0); expect(meta.controller.getStackIndex(1)).toBe(1); expect(meta.controller.getStackIndex(2)).toBe(2); expect(meta.controller.getStackIndex(3)).toBe(3); }); }); it('should correctly get the stack index when a group is not specified and the scale is stacked', function() { [ 'bar', 'horizontalBar' ].forEach(function(barType) { var chart = window.acquireChart({ type: barType, data: { datasets: [ {data: []}, {data: []}, {data: []}, {data: []} ], labels: [] }, options: { scales: { xAxes: [{ stacked: true }], yAxes: [{ stacked: true }] } } }); var meta = chart.getDatasetMeta(1); expect(meta.controller.getStackIndex(0)).toBe(0); expect(meta.controller.getStackIndex(1)).toBe(0); expect(meta.controller.getStackIndex(2)).toBe(0); expect(meta.controller.getStackIndex(3)).toBe(0); }); }); it('should correctly get the stack index when a group is not specified and the scale is not stacked', function() { [ 'bar', 'horizontalBar' ].forEach(function(barType) { var chart = window.acquireChart({ type: barType, data: { datasets: [ {data: []}, {data: []}, {data: []}, {data: []} ], labels: [] }, options: { scales: { xAxes: [{ stacked: false }], yAxes: [{ stacked: false }] } } }); var meta = chart.getDatasetMeta(1); expect(meta.controller.getStackIndex(0)).toBe(0); expect(meta.controller.getStackIndex(1)).toBe(1); expect(meta.controller.getStackIndex(2)).toBe(2); expect(meta.controller.getStackIndex(3)).toBe(3); }); }); it('should correctly get the stack index when a group is specified for some', function() { [ 'bar', 'horizontalBar' ].forEach(function(barType) { var chart = window.acquireChart({ type: barType, data: { datasets: [ {data: [], stack: 'stack1'}, {data: [], stack: 'stack1'}, {data: []}, {data: []} ], labels: [] } }); var meta = chart.getDatasetMeta(1); expect(meta.controller.getStackIndex(0)).toBe(0); expect(meta.controller.getStackIndex(1)).toBe(0); expect(meta.controller.getStackIndex(2)).toBe(1); expect(meta.controller.getStackIndex(3)).toBe(2); }); }); it('should correctly get the stack index when a group is specified for some and the scale is stacked', function() { [ 'bar', 'horizontalBar' ].forEach(function(barType) { var chart = window.acquireChart({ type: barType, data: { datasets: [ {data: [], stack: 'stack1'}, {data: [], stack: 'stack1'}, {data: []}, {data: []} ], labels: [] }, options: { scales: { xAxes: [{ stacked: true }], yAxes: [{ stacked: true }] } } }); var meta = chart.getDatasetMeta(1); expect(meta.controller.getStackIndex(0)).toBe(0); expect(meta.controller.getStackIndex(1)).toBe(0); expect(meta.controller.getStackIndex(2)).toBe(1); expect(meta.controller.getStackIndex(3)).toBe(1); }); }); it('should correctly get the stack index when a group is specified for some and the scale is not stacked', function() { [ 'bar', 'horizontalBar' ].forEach(function(barType) { var chart = window.acquireChart({ type: barType, data: { datasets: [ {data: [], stack: 'stack1'}, {data: [], stack: 'stack1'}, {data: []}, {data: []} ], labels: [] }, options: { scales: { xAxes: [{ stacked: false }], yAxes: [{ stacked: false }] } } }); var meta = chart.getDatasetMeta(1); expect(meta.controller.getStackIndex(0)).toBe(0); expect(meta.controller.getStackIndex(1)).toBe(1); expect(meta.controller.getStackIndex(2)).toBe(2); expect(meta.controller.getStackIndex(3)).toBe(3); }); }); it('should correctly get the stack index when a group is specified for all', function() { [ 'bar', 'horizontalBar' ].forEach(function(barType) { var chart = window.acquireChart({ type: barType, data: { datasets: [ {data: [], stack: 'stack1'}, {data: [], stack: 'stack1'}, {data: [], stack: 'stack2'}, {data: [], stack: 'stack2'} ], labels: [] } }); var meta = chart.getDatasetMeta(1); expect(meta.controller.getStackIndex(0)).toBe(0); expect(meta.controller.getStackIndex(1)).toBe(0); expect(meta.controller.getStackIndex(2)).toBe(1); expect(meta.controller.getStackIndex(3)).toBe(1); }); }); it('should correctly get the stack index when a group is specified for all and the scale is stacked', function() { [ 'bar', 'horizontalBar' ].forEach(function(barType) { var chart = window.acquireChart({ type: barType, data: { datasets: [ {data: [], stack: 'stack1'}, {data: [], stack: 'stack1'}, {data: [], stack: 'stack2'}, {data: [], stack: 'stack2'} ], labels: [] }, options: { scales: { xAxes: [{ stacked: true }], yAxes: [{ stacked: true }] } } }); var meta = chart.getDatasetMeta(1); expect(meta.controller.getStackIndex(0)).toBe(0); expect(meta.controller.getStackIndex(1)).toBe(0); expect(meta.controller.getStackIndex(2)).toBe(1); expect(meta.controller.getStackIndex(3)).toBe(1); }); }); it('should correctly get the stack index when a group is specified for all and the scale is not stacked', function() { [ 'bar', 'horizontalBar' ].forEach(function(barType) { var chart = window.acquireChart({ type: barType, data: { datasets: [ {data: [], stack: 'stack1'}, {data: [], stack: 'stack1'}, {data: [], stack: 'stack2'}, {data: [], stack: 'stack2'} ], labels: [] }, options: { scales: { xAxes: [{ stacked: false }], yAxes: [{ stacked: false }] } } }); var meta = chart.getDatasetMeta(1); expect(meta.controller.getStackIndex(0)).toBe(0); expect(meta.controller.getStackIndex(1)).toBe(1); expect(meta.controller.getStackIndex(2)).toBe(2); expect(meta.controller.getStackIndex(3)).toBe(3); }); }); it('should create rectangle elements for each data item during initialization', function() { var chart = window.acquireChart({ type: 'bar', data: { datasets: [ {data: []}, {data: [10, 15, 0, -4]} ], labels: [] } }); var meta = chart.getDatasetMeta(1); expect(meta.data.length).toBe(4); // 4 rectangles created expect(meta.data[0] instanceof Chart.elements.Rectangle).toBe(true); expect(meta.data[1] instanceof Chart.elements.Rectangle).toBe(true); expect(meta.data[2] instanceof Chart.elements.Rectangle).toBe(true); expect(meta.data[3] instanceof Chart.elements.Rectangle).toBe(true); }); it('should update elements when modifying data', function() { var chart = window.acquireChart({ type: 'bar', data: { datasets: [{ data: [1, 2], label: 'dataset1' }, { data: [10, 15, 0, -4], label: 'dataset2', borderColor: 'blue' }], labels: ['label1', 'label2', 'label3', 'label4'] }, options: { legend: false, title: false, elements: { rectangle: { backgroundColor: 'red', borderSkipped: 'top', borderColor: 'green', borderWidth: 2, } }, scales: { xAxes: [{ id: 'firstXScaleID', type: 'category', display: false }], yAxes: [{ id: 'firstYScaleID', type: 'linear', display: false }] } } }); var meta = chart.getDatasetMeta(1); expect(meta.data.length).toBe(4); chart.data.datasets[1].data = [1, 2]; // remove 2 items chart.data.datasets[1].borderWidth = 1; chart.update(); expect(meta.data.length).toBe(2); [ {x: 89, y: 512}, {x: 217, y: 0} ].forEach(function(expected, i) { expect(meta.data[i]._datasetIndex).toBe(1); expect(meta.data[i]._index).toBe(i); expect(meta.data[i]._xScale).toBe(chart.scales.firstXScaleID); expect(meta.data[i]._yScale).toBe(chart.scales.firstYScaleID); expect(meta.data[i]._model.x).toBeCloseToPixel(expected.x); expect(meta.data[i]._model.y).toBeCloseToPixel(expected.y); expect(meta.data[i]._model.base).toBeCloseToPixel(1024); expect(meta.data[i]._model.width).toBeCloseToPixel(46); expect(meta.data[i]._model).toEqual(jasmine.objectContaining({ datasetLabel: chart.data.datasets[1].label, label: chart.data.labels[i], backgroundColor: 'red', borderSkipped: 'top', borderColor: 'blue', borderWidth: 1 })); }); chart.data.datasets[1].data = [1, 2, 3]; // add 1 items chart.update(); expect(meta.data.length).toBe(3); // should add a new meta data item }); it('should get the correct bar points when datasets of different types exist', function() { var chart = window.acquireChart({ type: 'bar', data: { datasets: [{ data: [1, 2], label: 'dataset1' }, { type: 'line', data: [4, 6], label: 'dataset2' }, { data: [8, 10], label: 'dataset3' }], labels: ['label1', 'label2'] }, options: { legend: false, title: false, scales: { xAxes: [{ type: 'category', display: false }], yAxes: [{ type: 'linear', display: false }] } } }); var meta = chart.getDatasetMeta(2); expect(meta.data.length).toBe(2); var bar1 = meta.data[0]; var bar2 = meta.data[1]; expect(bar1._model.x).toBeCloseToPixel(179); expect(bar1._model.y).toBeCloseToPixel(114); expect(bar2._model.x).toBeCloseToPixel(435); expect(bar2._model.y).toBeCloseToPixel(0); }); it('should update elements when the scales are stacked', function() { var chart = window.acquireChart({ type: 'bar', data: { datasets: [{ data: [10, -10, 10, -10], label: 'dataset1' }, { data: [10, 15, 0, -4], label: 'dataset2' }], labels: ['label1', 'label2', 'label3', 'label4'] }, options: { legend: false, title: false, scales: { xAxes: [{ type: 'category', display: false }], yAxes: [{ type: 'linear', display: false, stacked: true }] } } }); var meta0 = chart.getDatasetMeta(0); [ {b: 293, w: 92 / 2, x: 38, y: 146}, {b: 293, w: 92 / 2, x: 166, y: 439}, {b: 293, w: 92 / 2, x: 295, y: 146}, {b: 293, w: 92 / 2, x: 422, y: 439} ].forEach(function(values, i) { expect(meta0.data[i]._model.base).toBeCloseToPixel(values.b); expect(meta0.data[i]._model.width).toBeCloseToPixel(values.w); expect(meta0.data[i]._model.x).toBeCloseToPixel(values.x); expect(meta0.data[i]._model.y).toBeCloseToPixel(values.y); }); var meta1 = chart.getDatasetMeta(1); [ {b: 146, w: 92 / 2, x: 89, y: 0}, {b: 293, w: 92 / 2, x: 217, y: 73}, {b: 146, w: 92 / 2, x: 345, y: 146}, {b: 439, w: 92 / 2, x: 473, y: 497} ].forEach(function(values, i) { expect(meta1.data[i]._model.base).toBeCloseToPixel(values.b); expect(meta1.data[i]._model.width).toBeCloseToPixel(values.w); expect(meta1.data[i]._model.x).toBeCloseToPixel(values.x); expect(meta1.data[i]._model.y).toBeCloseToPixel(values.y); }); }); it('should update elements when the scales are stacked and the y axis has a user defined minimum', function() { var chart = window.acquireChart({ type: 'bar', data: { datasets: [{ data: [50, 20, 10, 100], label: 'dataset1' }, { data: [50, 80, 90, 0], label: 'dataset2' }], labels: ['label1', 'label2', 'label3', 'label4'] }, options: { legend: false, title: false, scales: { xAxes: [{ type: 'category', display: false }], yAxes: [{ type: 'linear', display: false, stacked: true, ticks: { min: 50, max: 100 } }] } } }); var meta0 = chart.getDatasetMeta(0); [ {b: 1024, w: 92 / 2, x: 38, y: 512}, {b: 1024, w: 92 / 2, x: 166, y: 819}, {b: 1024, w: 92 / 2, x: 294, y: 922}, {b: 1024, w: 92 / 2, x: 422.5, y: 0} ].forEach(function(values, i) { expect(meta0.data[i]._model.base).toBeCloseToPixel(values.b); expect(meta0.data[i]._model.width).toBeCloseToPixel(values.w); expect(meta0.data[i]._model.x).toBeCloseToPixel(values.x); expect(meta0.data[i]._model.y).toBeCloseToPixel(values.y); }); var meta1 = chart.getDatasetMeta(1); [ {b: 512, w: 92 / 2, x: 89, y: 0}, {b: 819, w: 92 / 2, x: 217, y: 0}, {b: 922, w: 92 / 2, x: 345, y: 0}, {b: 0, w: 92 / 2, x: 473.5, y: 0} ].forEach(function(values, i) { expect(meta1.data[i]._model.base).toBeCloseToPixel(values.b); expect(meta1.data[i]._model.width).toBeCloseToPixel(values.w); expect(meta1.data[i]._model.x).toBeCloseToPixel(values.x); expect(meta1.data[i]._model.y).toBeCloseToPixel(values.y); }); }); it('should update elements when only the category scale is stacked', function() { var chart = window.acquireChart({ type: 'bar', data: { datasets: [{ data: [20, -10, 10, -10], label: 'dataset1' }, { data: [10, 15, 0, -14], label: 'dataset2' }], labels: ['label1', 'label2', 'label3', 'label4'] }, options: { legend: false, title: false, scales: { xAxes: [{ type: 'category', display: false, stacked: true }], yAxes: [{ type: 'linear', display: false }] } } }); var meta0 = chart.getDatasetMeta(0); [ {b: 293, w: 92, x: 64, y: 0}, {b: 293, w: 92, x: 192, y: 439}, {b: 293, w: 92, x: 320, y: 146}, {b: 293, w: 92, x: 448, y: 439} ].forEach(function(values, i) { expect(meta0.data[i]._model.base).toBeCloseToPixel(values.b); expect(meta0.data[i]._model.width).toBeCloseToPixel(values.w); expect(meta0.data[i]._model.x).toBeCloseToPixel(values.x); expect(meta0.data[i]._model.y).toBeCloseToPixel(values.y); }); var meta1 = chart.getDatasetMeta(1); [ {b: 293, w: 92, x: 64, y: 146}, {b: 293, w: 92, x: 192, y: 73}, {b: 293, w: 92, x: 320, y: 293}, {b: 293, w: 92, x: 448, y: 497} ].forEach(function(values, i) { expect(meta1.data[i]._model.base).toBeCloseToPixel(values.b); expect(meta1.data[i]._model.width).toBeCloseToPixel(values.w); expect(meta1.data[i]._model.x).toBeCloseToPixel(values.x); expect(meta1.data[i]._model.y).toBeCloseToPixel(values.y); }); }); it('should update elements when the scales are stacked and data is strings', function() { var chart = window.acquireChart({ type: 'bar', data: { datasets: [{ data: ['10', '-10', '10', '-10'], label: 'dataset1' }, { data: ['10', '15', '0', '-4'], label: 'dataset2' }], labels: ['label1', 'label2', 'label3', 'label4'] }, options: { legend: false, title: false, scales: { xAxes: [{ type: 'category', display: false }], yAxes: [{ type: 'linear', display: false, stacked: true }] } } }); var meta0 = chart.getDatasetMeta(0); [ {b: 293, w: 92 / 2, x: 38, y: 146}, {b: 293, w: 92 / 2, x: 166, y: 439}, {b: 293, w: 92 / 2, x: 295, y: 146}, {b: 293, w: 92 / 2, x: 422, y: 439} ].forEach(function(values, i) { expect(meta0.data[i]._model.base).toBeCloseToPixel(values.b); expect(meta0.data[i]._model.width).toBeCloseToPixel(values.w); expect(meta0.data[i]._model.x).toBeCloseToPixel(values.x); expect(meta0.data[i]._model.y).toBeCloseToPixel(values.y); }); var meta1 = chart.getDatasetMeta(1); [ {b: 146, w: 92 / 2, x: 89, y: 0}, {b: 293, w: 92 / 2, x: 217, y: 73}, {b: 146, w: 92 / 2, x: 345, y: 146}, {b: 439, w: 92 / 2, x: 473, y: 497} ].forEach(function(values, i) { expect(meta1.data[i]._model.base).toBeCloseToPixel(values.b); expect(meta1.data[i]._model.width).toBeCloseToPixel(values.w); expect(meta1.data[i]._model.x).toBeCloseToPixel(values.x); expect(meta1.data[i]._model.y).toBeCloseToPixel(values.y); }); }); it('should get the correct bar points for grouped stacked chart if the group name is same', function() { var chart = window.acquireChart({ type: 'bar', data: { datasets: [{ data: [10, -10, 10, -10], label: 'dataset1', stack: 'stack1' }, { data: [10, 15, 0, -4], label: 'dataset2', stack: 'stack1' }], labels: ['label1', 'label2', 'label3', 'label4'] }, options: { legend: false, title: false, scales: { xAxes: [{ type: 'category', display: false }], yAxes: [{ type: 'linear', display: false, stacked: true }] } } }); var meta0 = chart.getDatasetMeta(0); [ {b: 293, w: 92, x: 64, y: 146}, {b: 293, w: 92, x: 192, y: 439}, {b: 293, w: 92, x: 320, y: 146}, {b: 293, w: 92, x: 448, y: 439} ].forEach(function(values, i) { expect(meta0.data[i]._model.base).toBeCloseToPixel(values.b); expect(meta0.data[i]._model.width).toBeCloseToPixel(values.w); expect(meta0.data[i]._model.x).toBeCloseToPixel(values.x); expect(meta0.data[i]._model.y).toBeCloseToPixel(values.y); }); var meta = chart.getDatasetMeta(1); [ {b: 146, w: 92, x: 64, y: 0}, {b: 293, w: 92, x: 192, y: 73}, {b: 146, w: 92, x: 320, y: 146}, {b: 439, w: 92, x: 448, y: 497} ].forEach(function(values, i) { expect(meta.data[i]._model.base).toBeCloseToPixel(values.b); expect(meta.data[i]._model.width).toBeCloseToPixel(values.w); expect(meta.data[i]._model.x).toBeCloseToPixel(values.x); expect(meta.data[i]._model.y).toBeCloseToPixel(values.y); }); }); it('should get the correct bar points for grouped stacked chart if the group name is different', function() { var chart = window.acquireChart({ type: 'bar', data: { datasets: [{ data: [1, 2], stack: 'stack1' }, { data: [1, 2], stack: 'stack2' }], labels: ['label1', 'label2', 'label3', 'label4'] }, options: { legend: false, title: false, scales: { xAxes: [{ type: 'category', display: false }], yAxes: [{ type: 'linear', display: false, stacked: true, }] } } }); var meta = chart.getDatasetMeta(1); [ {x: 89, y: 256}, {x: 217, y: 0} ].forEach(function(values, i) { expect(meta.data[i]._model.base).toBeCloseToPixel(512); expect(meta.data[i]._model.width).toBeCloseToPixel(46); expect(meta.data[i]._model.x).toBeCloseToPixel(values.x); expect(meta.data[i]._model.y).toBeCloseToPixel(values.y); }); }); it('should get the correct bar points for grouped stacked chart', function() { var chart = window.acquireChart({ type: 'bar', data: { datasets: [{ data: [1, 2], stack: 'stack1' }, { data: [0.5, 1], stack: 'stack2' }, { data: [0.5, 1], stack: 'stack2' }], labels: ['label1', 'label2', 'label3', 'label4'] }, options: { legend: false, title: false, scales: { xAxes: [{ type: 'category', display: false }], yAxes: [{ type: 'linear', display: false, stacked: true }] } } }); var meta = chart.getDatasetMeta(2); [ {b: 384, x: 89, y: 256}, {b: 256, x: 217, y: 0} ].forEach(function(values, i) { expect(meta.data[i]._model.base).toBeCloseToPixel(values.b); expect(meta.data[i]._model.width).toBeCloseToPixel(46); expect(meta.data[i]._model.x).toBeCloseToPixel(values.x); expect(meta.data[i]._model.y).toBeCloseToPixel(values.y); }); }); it('should update elements when the scales are stacked and the y axis is logarithmic', function() { var chart = window.acquireChart({ type: 'bar', data: { datasets: [{ data: [10, 100, 10, 100], label: 'dataset1' }, { data: [100, 10, 0, 100], label: 'dataset2' }], labels: ['label1', 'label2', 'label3', 'label4'] }, options: { legend: false, title: false, scales: { xAxes: [{ type: 'category', display: false, stacked: true, barPercentage: 1, }], yAxes: [{ type: 'logarithmic', display: false, stacked: true }] } } }); var meta0 = chart.getDatasetMeta(0); [ {b: 512, w: 102, x: 64, y: 512}, {b: 512, w: 102, x: 192, y: 118}, {b: 512, w: 102, x: 320, y: 512}, {b: 512, w: 102, x: 449, y: 118} ].forEach(function(values, i) { expect(meta0.data[i]._model.base).toBeCloseToPixel(values.b); expect(meta0.data[i]._model.width).toBeCloseToPixel(values.w); expect(meta0.data[i]._model.x).toBeCloseToPixel(values.x); expect(meta0.data[i]._model.y).toBeCloseToPixel(values.y); }); var meta1 = chart.getDatasetMeta(1); [ {b: 512, w: 102, x: 64, y: 102}, {b: 118, w: 102, x: 192, y: 102}, {b: 512, w: 102, x: 320, y: 512}, {b: 118, w: 102, x: 449, y: 0} ].forEach(function(values, i) { expect(meta1.data[i]._model.base).toBeCloseToPixel(values.b); expect(meta1.data[i]._model.width).toBeCloseToPixel(values.w); expect(meta1.data[i]._model.x).toBeCloseToPixel(values.x); expect(meta1.data[i]._model.y).toBeCloseToPixel(values.y); }); }); it('should draw all bars', function() { var chart = window.acquireChart({ type: 'bar', data: { datasets: [{ data: [], }, { data: [10, 15, 0, -4], label: 'dataset2' }], labels: ['label1', 'label2', 'label3', 'label4'] } }); var meta = chart.getDatasetMeta(1); spyOn(meta.data[0], 'draw'); spyOn(meta.data[1], 'draw'); spyOn(meta.data[2], 'draw'); spyOn(meta.data[3], 'draw'); chart.update(); expect(meta.data[0].draw.calls.count()).toBe(1); expect(meta.data[1].draw.calls.count()).toBe(1); expect(meta.data[2].draw.calls.count()).toBe(1); expect(meta.data[3].draw.calls.count()).toBe(1); }); it('should set hover styles on rectangles', function() { var chart = window.acquireChart({ type: 'bar', data: { datasets: [{ data: [], }, { data: [10, 15, 0, -4], label: 'dataset2' }], labels: ['label1', 'label2', 'label3', 'label4'] }, options: { elements: { rectangle: { backgroundColor: 'rgb(255, 0, 0)', borderColor: 'rgb(0, 0, 255)', borderWidth: 2, } } } }); var meta = chart.getDatasetMeta(1); var bar = meta.data[0]; meta.controller.setHoverStyle(bar); expect(bar._model.backgroundColor).toBe('rgb(230, 0, 0)'); expect(bar._model.borderColor).toBe('rgb(0, 0, 230)'); expect(bar._model.borderWidth).toBe(2); // Set a dataset style chart.data.datasets[1].hoverBackgroundColor = 'rgb(128, 128, 128)'; chart.data.datasets[1].hoverBorderColor = 'rgb(0, 0, 0)'; chart.data.datasets[1].hoverBorderWidth = 5; meta.controller.setHoverStyle(bar); expect(bar._model.backgroundColor).toBe('rgb(128, 128, 128)'); expect(bar._model.borderColor).toBe('rgb(0, 0, 0)'); expect(bar._model.borderWidth).toBe(5); // Should work with array styles so that we can set per bar chart.data.datasets[1].hoverBackgroundColor = ['rgb(255, 255, 255)', 'rgb(128, 128, 128)']; chart.data.datasets[1].hoverBorderColor = ['rgb(9, 9, 9)', 'rgb(0, 0, 0)']; chart.data.datasets[1].hoverBorderWidth = [2.5, 5]; meta.controller.setHoverStyle(bar); expect(bar._model.backgroundColor).toBe('rgb(255, 255, 255)'); expect(bar._model.borderColor).toBe('rgb(9, 9, 9)'); expect(bar._model.borderWidth).toBe(2.5); // Should allow a custom style bar.custom = { hoverBackgroundColor: 'rgb(255, 0, 0)', hoverBorderColor: 'rgb(0, 255, 0)', hoverBorderWidth: 1.5 }; meta.controller.setHoverStyle(bar); expect(bar._model.backgroundColor).toBe('rgb(255, 0, 0)'); expect(bar._model.borderColor).toBe('rgb(0, 255, 0)'); expect(bar._model.borderWidth).toBe(1.5); }); it('should remove a hover style from a bar', function() { var chart = window.acquireChart({ type: 'bar', data: { datasets: [{ data: [], }, { data: [10, 15, 0, -4], label: 'dataset2' }], labels: ['label1', 'label2', 'label3', 'label4'] }, options: { elements: { rectangle: { backgroundColor: 'rgb(255, 0, 0)', borderColor: 'rgb(0, 0, 255)', borderWidth: 2, } } } }); var meta = chart.getDatasetMeta(1); var bar = meta.data[0]; var helpers = window.Chart.helpers; // Change default chart.options.elements.rectangle.backgroundColor = 'rgb(128, 128, 128)'; chart.options.elements.rectangle.borderColor = 'rgb(15, 15, 15)'; chart.options.elements.rectangle.borderWidth = 3.14; chart.update(); expect(bar._model.backgroundColor).toBe('rgb(128, 128, 128)'); expect(bar._model.borderColor).toBe('rgb(15, 15, 15)'); expect(bar._model.borderWidth).toBe(3.14); meta.controller.setHoverStyle(bar); expect(bar._model.backgroundColor).toBe(helpers.getHoverColor('rgb(128, 128, 128)')); expect(bar._model.borderColor).toBe(helpers.getHoverColor('rgb(15, 15, 15)')); expect(bar._model.borderWidth).toBe(3.14); meta.controller.removeHoverStyle(bar); expect(bar._model.backgroundColor).toBe('rgb(128, 128, 128)'); expect(bar._model.borderColor).toBe('rgb(15, 15, 15)'); expect(bar._model.borderWidth).toBe(3.14); // Should work with array styles so that we can set per bar chart.data.datasets[1].backgroundColor = ['rgb(255, 255, 255)', 'rgb(128, 128, 128)']; chart.data.datasets[1].borderColor = ['rgb(9, 9, 9)', 'rgb(0, 0, 0)']; chart.data.datasets[1].borderWidth = [2.5, 5]; chart.update(); expect(bar._model.backgroundColor).toBe('rgb(255, 255, 255)'); expect(bar._model.borderColor).toBe('rgb(9, 9, 9)'); expect(bar._model.borderWidth).toBe(2.5); meta.controller.setHoverStyle(bar); expect(bar._model.backgroundColor).toBe(helpers.getHoverColor('rgb(255, 255, 255)')); expect(bar._model.borderColor).toBe(helpers.getHoverColor('rgb(9, 9, 9)')); expect(bar._model.borderWidth).toBe(2.5); meta.controller.removeHoverStyle(bar); expect(bar._model.backgroundColor).toBe('rgb(255, 255, 255)'); expect(bar._model.borderColor).toBe('rgb(9, 9, 9)'); expect(bar._model.borderWidth).toBe(2.5); // Should allow a custom style bar.custom = { backgroundColor: 'rgb(255, 0, 0)', borderColor: 'rgb(0, 255, 0)', borderWidth: 1.5 }; chart.update(); expect(bar._model.backgroundColor).toBe('rgb(255, 0, 0)'); expect(bar._model.borderColor).toBe('rgb(0, 255, 0)'); expect(bar._model.borderWidth).toBe(1.5); meta.controller.setHoverStyle(bar); expect(bar._model.backgroundColor).toBe(helpers.getHoverColor('rgb(255, 0, 0)')); expect(bar._model.borderColor).toBe(helpers.getHoverColor('rgb(0, 255, 0)')); expect(bar._model.borderWidth).toBe(1.5); meta.controller.removeHoverStyle(bar); expect(bar._model.backgroundColor).toBe('rgb(255, 0, 0)'); expect(bar._model.borderColor).toBe('rgb(0, 255, 0)'); expect(bar._model.borderWidth).toBe(1.5); }); describe('Bar width', function() { beforeEach(function() { // 2 datasets this.data = { labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'], datasets: [{ data: [10, 20, 30, 40, 50, 60, 70], }, { data: [10, 20, 30, 40, 50, 60, 70], }] }; }); afterEach(function() { var chart = window.acquireChart(this.config); var meta = chart.getDatasetMeta(0); var xScale = chart.scales[meta.xAxisID]; var categoryPercentage = xScale.options.categoryPercentage; var barPercentage = xScale.options.barPercentage; var stacked = xScale.options.stacked; var totalBarWidth = 0; for (var i = 0; i < chart.data.datasets.length; i++) { var bars = chart.getDatasetMeta(i).data; for (var j = xScale.minIndex; j <= xScale.maxIndex; j++) { totalBarWidth += bars[j]._model.width; } if (stacked) { break; } } var actualValue = totalBarWidth; var expectedValue = xScale.width * categoryPercentage * barPercentage; expect(actualValue).toBeCloseToPixel(expectedValue); }); it('should correctly set bar width when min and max option is set.', function() { this.config = { type: 'bar', data: this.data, options: { scales: { xAxes: [{ ticks: { min: 'March', max: 'May', }, }] } } }; }); it('should correctly set bar width when scale are stacked with min and max options.', function() { this.config = { type: 'bar', data: this.data, options: { scales: { xAxes: [{ ticks: { min: 'March', max: 'May', } }], yAxes: [{ stacked: true }] } } }; }); }); describe('Bar height (horizontalBar type)', function() { beforeEach(function() { // 2 datasets this.data = { labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'], datasets: [{ data: [10, 20, 30, 40, 50, 60, 70], }, { data: [10, 20, 30, 40, 50, 60, 70], }] }; }); afterEach(function() { var chart = window.acquireChart(this.config); var meta = chart.getDatasetMeta(0); var yScale = chart.scales[meta.yAxisID]; var categoryPercentage = yScale.options.categoryPercentage; var barPercentage = yScale.options.barPercentage; var stacked = yScale.options.stacked; var totalBarHeight = 0; for (var i = 0; i < chart.data.datasets.length; i++) { var bars = chart.getDatasetMeta(i).data; for (var j = yScale.minIndex; j <= yScale.maxIndex; j++) { totalBarHeight += bars[j]._model.height; } if (stacked) { break; } } var actualValue = totalBarHeight; var expectedValue = yScale.height * categoryPercentage * barPercentage; expect(actualValue).toBeCloseToPixel(expectedValue); }); it('should correctly set bar height when min and max option is set.', function() { this.config = { type: 'horizontalBar', data: this.data, options: { scales: { yAxes: [{ ticks: { min: 'March', max: 'May', }, }] } } }; }); it('should correctly set bar height when scale are stacked with min and max options.', function() { this.config = { type: 'horizontalBar', data: this.data, options: { scales: { xAxes: [{ stacked: true }], yAxes: [{ ticks: { min: 'March', max: 'May', } }] } } }; }); }); describe('Bar thickness with a category scale', function() { [undefined, 20].forEach(function(barThickness) { describe('When barThickness is ' + barThickness, function() { beforeEach(function() { this.chart = window.acquireChart({ type: 'bar', data: { datasets: [{ data: [1, 2] }, { data: [1, 2] }], labels: ['label1', 'label2', 'label3'] }, options: { legend: false, title: false, scales: { xAxes: [{ id: 'x', type: 'category', barThickness: barThickness }], yAxes: [{ type: 'linear', }] } } }); }); it('should correctly set bar width', function() { var chart = this.chart; var expected, i, ilen, meta; if (barThickness) { expected = barThickness; } else { var scale = chart.scales.x; var options = chart.options.scales.xAxes[0]; var categoryPercentage = options.categoryPercentage; var barPercentage = options.barPercentage; var tickInterval = scale.getPixelForTick(1) - scale.getPixelForTick(0); expected = tickInterval * categoryPercentage / 2 * barPercentage; } for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) { meta = chart.getDatasetMeta(i); expect(meta.data[0]._model.width).toBeCloseToPixel(expected); expect(meta.data[1]._model.width).toBeCloseToPixel(expected); } }); it('should correctly set bar width if maxBarThickness is specified', function() { var chart = this.chart; var options = chart.options.scales.xAxes[0]; var i, ilen, meta; options.maxBarThickness = 10; chart.update(); for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) { meta = chart.getDatasetMeta(i); expect(meta.data[0]._model.width).toBeCloseToPixel(10); expect(meta.data[1]._model.width).toBeCloseToPixel(10); } }); }); }); }); });
/* colpick Color Picker Copyright 2013 Jose Vargas. Licensed under GPL license. Based on Stefan Petre's Color Picker www.eyecon.ro, dual licensed under the MIT and GPL licenses For usage and examples: colpick.com/plugin */ (function ($) { var colpick = function () { var tpl = '<div class="colpick" style="z-index:700;"><div class="colpick_color"><div class="colpick_color_overlay1"><div class="colpick_color_overlay2"><div class="colpick_selector_outer"><div class="colpick_selector_inner"></div></div></div></div></div><div class="colpick_hue"><div class="colpick_hue_arrs"><div class="colpick_hue_larr"></div><div class="colpick_hue_rarr"></div></div></div><div class="colpick_new_color"></div><div class="colpick_current_color"></div><div class="colpick_hex_field"><div class="colpick_field_letter">#</div><input type="text" maxlength="6" size="6" /></div><div class="colpick_rgb_r colpick_field"><div class="colpick_field_letter">R</div><input type="text" maxlength="3" size="3" /><div class="colpick_field_arrs"><div class="colpick_field_uarr"></div><div class="colpick_field_darr"></div></div></div><div class="colpick_rgb_g colpick_field"><div class="colpick_field_letter">G</div><input type="text" maxlength="3" size="3" /><div class="colpick_field_arrs"><div class="colpick_field_uarr"></div><div class="colpick_field_darr"></div></div></div><div class="colpick_rgb_b colpick_field"><div class="colpick_field_letter">B</div><input type="text" maxlength="3" size="3" /><div class="colpick_field_arrs"><div class="colpick_field_uarr"></div><div class="colpick_field_darr"></div></div></div><div class="colpick_hsb_h colpick_field"><div class="colpick_field_letter">H</div><input type="text" maxlength="3" size="3" /><div class="colpick_field_arrs"><div class="colpick_field_uarr"></div><div class="colpick_field_darr"></div></div></div><div class="colpick_hsb_s colpick_field"><div class="colpick_field_letter">S</div><input type="text" maxlength="3" size="3" /><div class="colpick_field_arrs"><div class="colpick_field_uarr"></div><div class="colpick_field_darr"></div></div></div><div class="colpick_hsb_b colpick_field"><div class="colpick_field_letter">B</div><input type="text" maxlength="3" size="3" /><div class="colpick_field_arrs"><div class="colpick_field_uarr"></div><div class="colpick_field_darr"></div></div></div><div class="colpick_submit"></div></div>', defaults = { showEvent: 'click', onShow: function () {}, onBeforeShow: function(){}, onHide: function () {}, onChange: function () {}, onSubmit: function () {}, colorScheme: 'light', color: '3289c7', livePreview: true, flat: false, layout: 'full', submit: 1, submitText: 'OK', height: 156 }, //Fill the inputs of the plugin fillRGBFields = function (hsb, cal) { var rgb = hsbToRgb(hsb); $(cal).data('colpick').fields .eq(1).val(rgb.r).end() .eq(2).val(rgb.g).end() .eq(3).val(rgb.b).end(); }, fillHSBFields = function (hsb, cal) { $(cal).data('colpick').fields .eq(4).val(Math.round(hsb.h)).end() .eq(5).val(Math.round(hsb.s)).end() .eq(6).val(Math.round(hsb.b)).end(); }, fillHexFields = function (hsb, cal) { $(cal).data('colpick').fields.eq(0).val(hsbToHex(hsb)); }, //Set the round selector position setSelector = function (hsb, cal) { $(cal).data('colpick').selector.css('backgroundColor', '#' + hsbToHex({h: hsb.h, s: 100, b: 100})); $(cal).data('colpick').selectorIndic.css({ left: parseInt($(cal).data('colpick').height * hsb.s/100, 10), top: parseInt($(cal).data('colpick').height * (100-hsb.b)/100, 10) }); }, //Set the hue selector position setHue = function (hsb, cal) { $(cal).data('colpick').hue.css('top', parseInt($(cal).data('colpick').height - $(cal).data('colpick').height * hsb.h/360, 10)); }, //Set current and new colors setCurrentColor = function (hsb, cal) { $(cal).data('colpick').currentColor.css('backgroundColor', '#' + hsbToHex(hsb)); }, setNewColor = function (hsb, cal) { $(cal).data('colpick').newColor.css('backgroundColor', '#' + hsbToHex(hsb)); }, //Called when the new color is changed change = function (ev) { var cal = $(this).parent().parent(), col; if (this.parentNode.className.indexOf('_hex') > 0) { cal.data('colpick').color = col = hexToHsb(fixHex(this.value)); fillRGBFields(col, cal.get(0)); fillHSBFields(col, cal.get(0)); } else if (this.parentNode.className.indexOf('_hsb') > 0) { cal.data('colpick').color = col = fixHSB({ h: parseInt(cal.data('colpick').fields.eq(4).val(), 10), s: parseInt(cal.data('colpick').fields.eq(5).val(), 10), b: parseInt(cal.data('colpick').fields.eq(6).val(), 10) }); fillRGBFields(col, cal.get(0)); fillHexFields(col, cal.get(0)); } else { cal.data('colpick').color = col = rgbToHsb(fixRGB({ r: parseInt(cal.data('colpick').fields.eq(1).val(), 10), g: parseInt(cal.data('colpick').fields.eq(2).val(), 10), b: parseInt(cal.data('colpick').fields.eq(3).val(), 10) })); fillHexFields(col, cal.get(0)); fillHSBFields(col, cal.get(0)); } setSelector(col, cal.get(0)); setHue(col, cal.get(0)); setNewColor(col, cal.get(0)); cal.data('colpick').onChange.apply(cal.parent(), [col, hsbToHex(col), hsbToRgb(col), cal.data('colpick').el, 0]); }, //Change style on blur and on focus of inputs blur = function (ev) { $(this).parent().removeClass('colpick_focus'); }, focus = function () { $(this).parent().parent().data('colpick').fields.parent().removeClass('colpick_focus'); $(this).parent().addClass('colpick_focus'); }, //Increment/decrement arrows functions downIncrement = function (ev) { ev.preventDefault ? ev.preventDefault() : ev.returnValue = false; var field = $(this).parent().find('input').focus(); var current = { el: $(this).parent().addClass('colpick_slider'), max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255), y: ev.pageY, field: field, val: parseInt(field.val(), 10), preview: $(this).parent().parent().data('colpick').livePreview }; $(document).mouseup(current, upIncrement); $(document).mousemove(current, moveIncrement); }, moveIncrement = function (ev) { ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val - ev.pageY + ev.data.y, 10)))); if (ev.data.preview) { change.apply(ev.data.field.get(0), [true]); } return false; }, upIncrement = function (ev) { change.apply(ev.data.field.get(0), [true]); ev.data.el.removeClass('colpick_slider').find('input').focus(); $(document).off('mouseup', upIncrement); $(document).off('mousemove', moveIncrement); return false; }, //Hue slider functions downHue = function (ev) { ev.preventDefault ? ev.preventDefault() : ev.returnValue = false; var current = { cal: $(this).parent(), y: $(this).offset().top }; $(document).on('mouseup touchend',current,upHue); $(document).on('mousemove touchmove',current,moveHue); var pageY = ((ev.type == 'touchstart') ? ev.originalEvent.changedTouches[0].pageY : ev.pageY ); change.apply( current.cal.data('colpick') .fields.eq(4).val(parseInt(360*(current.cal.data('colpick').height - (pageY - current.y))/current.cal.data('colpick').height, 10)) .get(0), [current.cal.data('colpick').livePreview] ); return false; }, moveHue = function (ev) { var pageY = ((ev.type == 'touchmove') ? ev.originalEvent.changedTouches[0].pageY : ev.pageY ); change.apply( ev.data.cal.data('colpick') .fields.eq(4).val(parseInt(360*(ev.data.cal.data('colpick').height - Math.max(0,Math.min(ev.data.cal.data('colpick').height,(pageY - ev.data.y))))/ev.data.cal.data('colpick').height, 10)) .get(0), [ev.data.preview] ); return false; }, upHue = function (ev) { fillRGBFields(ev.data.cal.data('colpick').color, ev.data.cal.get(0)); fillHexFields(ev.data.cal.data('colpick').color, ev.data.cal.get(0)); $(document).off('mouseup touchend',upHue); $(document).off('mousemove touchmove',moveHue); return false; }, //Color selector functions downSelector = function (ev) { ev.preventDefault ? ev.preventDefault() : ev.returnValue = false; var current = { cal: $(this).parent(), pos: $(this).offset() }; current.preview = current.cal.data('colpick').livePreview; $(document).on('mouseup touchend',current,upSelector); $(document).on('mousemove touchmove',current,moveSelector); var payeX,pageY; if(ev.type == 'touchstart') { pageX = ev.originalEvent.changedTouches[0].pageX, pageY = ev.originalEvent.changedTouches[0].pageY; } else { pageX = ev.pageX; pageY = ev.pageY; } change.apply( current.cal.data('colpick').fields .eq(6).val(parseInt(100*(current.cal.data('colpick').height - (pageY - current.pos.top))/current.cal.data('colpick').height, 10)).end() .eq(5).val(parseInt(100*(pageX - current.pos.left)/current.cal.data('colpick').height, 10)) .get(0), [current.preview] ); return false; }, moveSelector = function (ev) { var payeX,pageY; if(ev.type == 'touchmove') { pageX = ev.originalEvent.changedTouches[0].pageX, pageY = ev.originalEvent.changedTouches[0].pageY; } else { pageX = ev.pageX; pageY = ev.pageY; } change.apply( ev.data.cal.data('colpick').fields .eq(6).val(parseInt(100*(ev.data.cal.data('colpick').height - Math.max(0,Math.min(ev.data.cal.data('colpick').height,(pageY - ev.data.pos.top))))/ev.data.cal.data('colpick').height, 10)).end() .eq(5).val(parseInt(100*(Math.max(0,Math.min(ev.data.cal.data('colpick').height,(pageX - ev.data.pos.left))))/ev.data.cal.data('colpick').height, 10)) .get(0), [ev.data.preview] ); return false; }, upSelector = function (ev) { fillRGBFields(ev.data.cal.data('colpick').color, ev.data.cal.get(0)); fillHexFields(ev.data.cal.data('colpick').color, ev.data.cal.get(0)); $(document).off('mouseup touchend',upSelector); $(document).off('mousemove touchmove',moveSelector); return false; }, //Submit button clickSubmit = function (ev) { var cal = $(this).parent(); var col = cal.data('colpick').color; cal.data('colpick').origColor = col; setCurrentColor(col, cal.get(0)); cal.data('colpick').onSubmit(col, hsbToHex(col), hsbToRgb(col), cal.data('colpick').el); }, //Show/hide the color picker show = function (ev) { // Prevent the trigger of any direct parent ev.stopPropagation(); var cal = $('#' + $(this).data('colpickId')); cal.data('colpick').onBeforeShow.apply(this, [cal.get(0)]); var pos = $(this).offset(); var top = pos.top + this.offsetHeight; var left = pos.left; var viewPort = getViewport(); var calW = cal.width(); if (left + calW > viewPort.l + viewPort.w) { left -= calW; } cal.css({left: left + 'px', top: top + 'px'}); if (cal.data('colpick').onShow.apply(this, [cal.get(0)]) != false) { cal.show(); } //Hide when user clicks outside $('html').mousedown({cal:cal}, hide); cal.mousedown(function(ev){ev.stopPropagation();}) }, hide = function (ev) { if (ev.data.cal.data('colpick').onHide.apply(this, [ev.data.cal.get(0)]) != false) { ev.data.cal.hide(); } $('html').off('mousedown', hide); }, getViewport = function () { var m = document.compatMode == 'CSS1Compat'; return { l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft), w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth) }; }, //Fix the values if the user enters a negative or high value fixHSB = function (hsb) { return { h: Math.min(360, Math.max(0, hsb.h)), s: Math.min(100, Math.max(0, hsb.s)), b: Math.min(100, Math.max(0, hsb.b)) }; }, fixRGB = function (rgb) { return { r: Math.min(255, Math.max(0, rgb.r)), g: Math.min(255, Math.max(0, rgb.g)), b: Math.min(255, Math.max(0, rgb.b)) }; }, fixHex = function (hex) { var len = 6 - hex.length; if (len > 0) { var o = []; for (var i=0; i<len; i++) { o.push('0'); } o.push(hex); hex = o.join(''); } return hex; }, restoreOriginal = function () { var cal = $(this).parent(); var col = cal.data('colpick').origColor; cal.data('colpick').color = col; fillRGBFields(col, cal.get(0)); fillHexFields(col, cal.get(0)); fillHSBFields(col, cal.get(0)); setSelector(col, cal.get(0)); setHue(col, cal.get(0)); setNewColor(col, cal.get(0)); }; return { init: function (opt) { opt = $.extend({}, defaults, opt||{}); //Set color if (typeof opt.color == 'string') { opt.color = hexToHsb(opt.color); } else if (opt.color.r != undefined && opt.color.g != undefined && opt.color.b != undefined) { opt.color = rgbToHsb(opt.color); } else if (opt.color.h != undefined && opt.color.s != undefined && opt.color.b != undefined) { opt.color = fixHSB(opt.color); } else { return this; } //For each selected DOM element return this.each(function () { //If the element does not have an ID if (!$(this).data('colpickId')) { var options = $.extend({}, opt); options.origColor = opt.color; //Generate and assign a random ID var id = 'collorpicker_' + parseInt(Math.random() * 1000); $(this).data('colpickId', id); //Set the tpl's ID and get the HTML var cal = $(tpl).attr('id', id); //Add class according to layout cal.addClass('colpick_'+options.layout+(options.submit?'':' colpick_'+options.layout+'_ns')); //Add class if the color scheme is not default if(options.colorScheme != 'light') { cal.addClass('colpick_'+options.colorScheme); } //Setup submit button cal.find('div.colpick_submit').html(options.submitText).click(clickSubmit); //Setup input fields options.fields = cal.find('input').change(change).blur(blur).focus(focus); cal.find('div.colpick_field_arrs').mousedown(downIncrement).end().find('div.colpick_current_color').click(restoreOriginal); //Setup hue selector options.selector = cal.find('div.colpick_color').on('mousedown touchstart',downSelector); options.selectorIndic = options.selector.find('div.colpick_selector_outer'); //Store parts of the plugin options.el = this; options.hue = cal.find('div.colpick_hue_arrs'); huebar = options.hue.parent(); //Paint the hue bar var UA = navigator.userAgent.toLowerCase(); var isIE = navigator.appName === 'Microsoft Internet Explorer'; var IEver = isIE ? parseFloat( UA.match( /msie ([0-9]{1,}[\.0-9]{0,})/ )[1] ) : 0; var ngIE = ( isIE && IEver < 10 ); var stops = ['#ff0000','#ff0080','#ff00ff','#8000ff','#0000ff','#0080ff','#00ffff','#00ff80','#00ff00','#80ff00','#ffff00','#ff8000','#ff0000']; if(ngIE) { var i, div; for(i=0; i<=11; i++) { div = $('<div></div>').attr('style','height:8.333333%; filter:progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='+stops[i]+', endColorstr='+stops[i+1]+'); -ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='+stops[i]+', endColorstr='+stops[i+1]+')";'); huebar.append(div); } } else { stopList = stops.join(','); huebar.attr('style','background:-webkit-linear-gradient(top,'+stopList+'); background: -o-linear-gradient(top,'+stopList+'); background: -ms-linear-gradient(top,'+stopList+'); background:-moz-linear-gradient(top,'+stopList+'); -webkit-linear-gradient(top,'+stopList+'); background:linear-gradient(to bottom,'+stopList+'); '); } cal.find('div.colpick_hue').on('mousedown touchstart',downHue); options.newColor = cal.find('div.colpick_new_color'); options.currentColor = cal.find('div.colpick_current_color'); //Store options and fill with default color cal.data('colpick', options); fillRGBFields(options.color, cal.get(0)); fillHSBFields(options.color, cal.get(0)); fillHexFields(options.color, cal.get(0)); setHue(options.color, cal.get(0)); setSelector(options.color, cal.get(0)); setCurrentColor(options.color, cal.get(0)); setNewColor(options.color, cal.get(0)); //Append to body if flat=false, else show in place if (options.flat) { cal.appendTo(this).show(); cal.css({ position: 'relative', display: 'block' }); } else { cal.appendTo(document.body); $(this).on(options.showEvent, show); cal.css({ position:'absolute' }); } } }); }, //Shows the picker showPicker: function() { return this.each( function () { if ($(this).data('colpickId')) { show.apply(this); } }); }, //Hides the picker hidePicker: function() { return this.each( function () { if ($(this).data('colpickId')) { $('#' + $(this).data('colpickId')).hide(); } }); }, //Sets a color as new and current (default) setColor: function(col, setCurrent) { setCurrent = (typeof setCurrent === "undefined") ? 1 : setCurrent; if (typeof col == 'string') { col = hexToHsb(col); } else if (col.r != undefined && col.g != undefined && col.b != undefined) { col = rgbToHsb(col); } else if (col.h != undefined && col.s != undefined && col.b != undefined) { col = fixHSB(col); } else { return this; } return this.each(function(){ if ($(this).data('colpickId')) { var cal = $('#' + $(this).data('colpickId')); cal.data('colpick').color = col; cal.data('colpick').origColor = col; fillRGBFields(col, cal.get(0)); fillHSBFields(col, cal.get(0)); fillHexFields(col, cal.get(0)); setHue(col, cal.get(0)); setSelector(col, cal.get(0)); setNewColor(col, cal.get(0)); cal.data('colpick').onChange.apply(cal.parent(), [col, hsbToHex(col), hsbToRgb(col), cal.data('colpick').el, 1]); if(setCurrent) { setCurrentColor(col, cal.get(0)); } } }); } }; }(); //Color space convertions var hexToRgb = function (hex) { var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16); return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)}; }; var hexToHsb = function (hex) { return rgbToHsb(hexToRgb(hex)); }; var rgbToHsb = function (rgb) { var hsb = {h: 0, s: 0, b: 0}; var min = Math.min(rgb.r, rgb.g, rgb.b); var max = Math.max(rgb.r, rgb.g, rgb.b); var delta = max - min; hsb.b = max; hsb.s = max != 0 ? 255 * delta / max : 0; if (hsb.s != 0) { if (rgb.r == max) hsb.h = (rgb.g - rgb.b) / delta; else if (rgb.g == max) hsb.h = 2 + (rgb.b - rgb.r) / delta; else hsb.h = 4 + (rgb.r - rgb.g) / delta; } else hsb.h = -1; hsb.h *= 60; if (hsb.h < 0) hsb.h += 360; hsb.s *= 100/255; hsb.b *= 100/255; return hsb; }; var hsbToRgb = function (hsb) { var rgb = {}; var h = hsb.h; var s = hsb.s*255/100; var v = hsb.b*255/100; if(s == 0) { rgb.r = rgb.g = rgb.b = v; } else { var t1 = v; var t2 = (255-s)*v/255; var t3 = (t1-t2)*(h%60)/60; if(h==360) h = 0; if(h<60) {rgb.r=t1; rgb.b=t2; rgb.g=t2+t3} else if(h<120) {rgb.g=t1; rgb.b=t2; rgb.r=t1-t3} else if(h<180) {rgb.g=t1; rgb.r=t2; rgb.b=t2+t3} else if(h<240) {rgb.b=t1; rgb.r=t2; rgb.g=t1-t3} else if(h<300) {rgb.b=t1; rgb.g=t2; rgb.r=t2+t3} else if(h<360) {rgb.r=t1; rgb.g=t2; rgb.b=t1-t3} else {rgb.r=0; rgb.g=0; rgb.b=0} } return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)}; }; var rgbToHex = function (rgb) { var hex = [ rgb.r.toString(16), rgb.g.toString(16), rgb.b.toString(16) ]; $.each(hex, function (nr, val) { if (val.length == 1) { hex[nr] = '0' + val; } }); return hex.join(''); }; var hsbToHex = function (hsb) { return rgbToHex(hsbToRgb(hsb)); }; $.fn.extend({ colpick: colpick.init, colpickHide: colpick.hidePicker, colpickShow: colpick.showPicker, colpickSetColor: colpick.setColor }); $.extend({ colpick:{ rgbToHex: rgbToHex, rgbToHsb: rgbToHsb, hsbToHex: hsbToHex, hsbToRgb: hsbToRgb, hexToHsb: hexToHsb, hexToRgb: hexToRgb } }); })(jQuery);
// Copyright (C) 2011 Sean Swezey // 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. // Declarations var contentPort, popupPort, passFields, formFields, passId; function handleContentMessages(msg) { if(msg.type === "show"){ chrome.tabs.getSelected(null, function(t){ chrome.pageAction.show(t.id); }); passFields = msg.fields; formFields = msg.forms; } if(msg.type === "check"){ chrome.tabs.getSelected(null, function(tab) { var mod_url = tab.url.match(/(\w*\.\w{2,3})\//)[1]; var inLocalStorage = false; var userField; for(var field in msg.formData){ if(localStorage[mod_url + msg.formData[field]] != null){ inLocalStorage = true; userField = msg.formData[field]; } } if(inLocalStorage){ var d = new Date(); var hour = d.getHours().toString(); var minute = d.getMinutes().toString(); var day = d.getDate().toString(); var month = (d.getMonth() + 1).toString(); var storageObj = JSON.parse(localStorage[mod_url + userField]); var format = storageObj.format; format = format.replace(new RegExp("%h", 'gm'),hour); format = format.replace(new RegExp("%m", 'gm'),minute); format = format.replace(new RegExp("%d", 'gm'),day); format = format.replace(new RegExp("%t", 'gm'),month); if((msg.formData.password === format) || (msg.formData.password === storageObj.password)){ contentPort.postMessage({"type": "replace", "form": storageObj.formField, "pass": storageObj.password, "passField": storageObj.passfield}); } else { contentPort.postMessage({"type": "clear", "form": storageObj.formField}); } } else { contentPort.postMessage({"type": "clear", "form": msg.formData.formId}); } }); } } function handlePopupMessages(msg) { if(typeof handlePopupMessages.passIndex == 'undefined'){ handlePopupMessages.passIndex = 0; } if(msg.type !== "init"){ contentPort.postMessage({"type": "unlight", "id": passId}); } if(msg.type === "wantNext"){ handlePopupMessages.passIndex = (handlePopupMessages.passIndex + 1) % passFields.length; } if(msg.type === "wantPrev"){ handlePopupMessages.passIndex--; if(handlePopupMessages.passIndex < 0){ handlePopupMessages.passIndex = passFields.length - 1} } if((msg.type === "init") || (msg.type === "wantNext") || (msg.type === "wantPrev")){ contentPort.postMessage({"type": "highlight", "id": passFields[handlePopupMessages.passIndex]}); passId = passFields[handlePopupMessages.passIndex]; } if(msg.type === "result"){ chrome.tabs.getSelected(null, function(tab) { mod_url = tab.url.match(/(\w*\.\w{2,3})\//)[1]; // may save for later: .substring(0, mod_url.indexOf(".")) var storageKey = mod_url + msg.user; var storageObj = Object(); storageObj.user = msg.user; storageObj.format = msg.format; storageObj.password = msg.password; storageObj.passfield = passId; storageObj.formfield = formFields[passFields.indexOf(passId)]; localStorage[storageKey] = JSON.stringify(storageObj); }); } if((msg.type === "close") || (msg.type === "result")){ chrome.tabs.getSelected(null, function(tab) { chrome.tabs.update(tab.id, { selected: true }); }); } } // Scripting chrome.extension.onConnect.addListener(function(port) { if(port.name === "content"){ contentPort = port; port.onMessage.addListener(handleContentMessages); } else if(port.name === "popup"){ popupPort = port; port.onMessage.addListener(handlePopupMessages); } });
(window.webpackJsonp=window.webpackJsonp||[]).push([[3],{52:function(t,n,e){"use strict";e.r(n);var s=e(0),c=Object(s.a)({},function(){var t=this.$createElement;return(this._self._c||t)("div",{staticClass:"content"})},[],!1,null,null,null);n.default=c.exports}}]);
const fs = require('fs'); const path = require('path'); const webpack = require('webpack'); const { createElement } = require('rax'); const renderer = require('rax-server-renderer'); const interopRequire = require('./interopRequire'); const getAssets = require('./getAssets'); const getWebpackNodeConfig = require('./getWebpackNodeConfig'); class DocumentHandler { constructor(options) { this.options = options; const { appDocument, appHtml, appDirectory } = this.options; this.documentJsFilePath; this.withDocumentJs = fs.existsSync(appDocument) || !fs.existsSync(appHtml); // Temp File this.tempHtmlFileName = '_document'; this.tempHtmlFilePath = path.resolve(appDirectory, '.temp', this.tempHtmlFileName + '.js'); if (this.withDocumentJs) { this.documentJsFilePath = fs.existsSync(appDocument) ? appDocument : require.resolve('rax-pwa/lib/Document'); } } build(next) { const { appDirectory } = this.options; const webpackHtmlConfig = getWebpackNodeConfig(appDirectory); webpackHtmlConfig.entry[this.tempHtmlFileName] = this.documentJsFilePath; webpack(webpackHtmlConfig).run(() => { next('document'); }); } getDocument(compilation, appShellTemplate = '', skeletonTemplate = '', title = 'WebApp') { let _htmlValue; let _htmlPath; const _htmlAssets = getAssets(compilation); const { appHtml } = this.options; if (!this.withDocumentJs) { // Use public/index.html _htmlPath = appHtml; _htmlValue = fs.readFileSync(_htmlPath, 'utf8'); _htmlValue = _htmlValue.replace( /<div(.*?) id=\"root\">(.*?)<\/div>/, `<div id="root">${appShellTemplate}</div>` ); if (skeletonTemplate) { _htmlValue = _htmlValue.replace( '</body>', `<script>${skeletonTemplate}</script></body>` ); } const jsTagStr = _htmlAssets.js.map(src => `<script src="${src}"></script>`).join('') || ''; const cssTagStr = _htmlAssets.css.map(src => `<link rel="stylesheet" href="${src}" />`).join('') || ''; _htmlValue = _htmlValue .replace('</head>', `${cssTagStr}</head>`) .replace('</body>', `${jsTagStr}</body>`); } else { // Use document.js _htmlPath = this.documentJsFilePath; _htmlValue = renderer.renderToString( createElement(interopRequire(eval(fs.readFileSync(this.tempHtmlFilePath, 'utf-8'))), { scripts: _htmlAssets.js, styles: _htmlAssets.css, title: title, pageData: JSON.stringify({}), pageHtml: appShellTemplate }) ); if (skeletonTemplate) { _htmlValue = _htmlValue.replace( '<script', `<script>${skeletonTemplate}</script><script` ); } } return { html: _htmlValue, path: _htmlPath }; } } module.exports = DocumentHandler;
import crEsDimConfig from './crEsDimConfig'; import crSdnDimConfig from './crSdnDimConfig'; import crDimConfig from './crDimConfig'; import loadJson from './loadJson'; const _isArr = Array.isArray; const _isEs = (dimension, source) => dimension && source === 'Eurostat' const _isSdn = item => item && item.id && item.text && !_isArr(item.valueTexts) && _isArr(item.values); const _crDimsConfig = (json) => { const dims = [] , { variables, dimension, source } = json; let timeId, mapFrequency = 'Y'; if (_isEs(dimension, source)) { return crEsDimConfig(dimension); } if (!_isArr(variables)) { return {dims, timeId, mapFrequency}; } if (_isSdn(variables[0])) { return crSdnDimConfig(variables); } return crDimConfig(variables); }; const loadDimsWithOptions = url => loadJson(url) .then(_crDimsConfig); export default loadDimsWithOptions
import { FETCH_ITEMS, ADD_ITEM, DELETE_ITEM, SAVE_ITEM } from "../actions"; export default function (state = [], action) { switch (action.type){ case FETCH_ITEMS: if (action.payload.status === 200) { return action.payload.data; } else { return state; } case ADD_ITEM: if (action.payload.status === 201) { return [action.payload.data.item, ...state]; } else { return state; } case SAVE_ITEM: if (action.payload.status === 200) { return state.map((item) => { if (item.uri === action.payload.data.item.uri) { return action.payload.data.item; } else { return item; } }); } else { return state; } case DELETE_ITEM: if (action.payload.status === 200) { return state.filter((item) => { return item.uri !== `/api/item/${action.payload.data.id}`; }); } else { return state; } default: return state; } }
function formValidate() { var number = document.forms["payment"]["number"].value; var month = document.forms["payment"]["month"].value; var year = document.forms["payment"]["year"].value; var code = document.forms["payment"]["code"].value; if(isEmpty(number)) if(isEmpty(month)) if(isEmpty(year)) if(isEmpty(code)) // if(isNumeric(number)) // if(isNumeric(month)) // if(isNumeric(year)) // if(isNumeric(code)) // if(cardValidation(number)) // if(monthValidation(month)) // if(yearValidation(year)) // if(codeValidation(code)) return true; else return false; else return false; else return false; else return false; // else // return false; // else // return false; // else // return false; // else // return false; // else // return false; // else // return false; // else // return false; // else // return false; } function isEmpty(elemValue,field) { if(elemValue == "" || elemValue == null){ alert("You cannot have " + field + " field empty"); } else return false; // // function isNumeric(elemValue,field) { // var exp = /^[0-9]+$/; // if(!isEmpty(elemValue,field)) // { // if(elemValue.match(exp)) // { // return true; // } // else // { // alert("Enter Numbers Only"); // return false; // } // } // else // { // return false; // } // } // // function cardValidation(elemValue) { // if(!isEmpty(elemValue,"number")){ // // if(elemValue.length > 15 && elemValue.length <= 16 ) { // // return true; // } // else{ // // alert("Invalid Card Number"); // return false; // } // // } // // } // // function monthValidation(elemValue) { // if(!isEmpty(elemValue,"month")){ // // if (elemValue > 0 && elemValue <= 12){ // // return true; // } // else { // // alert("Enter valid month"); // return false; // } // } // } // // function yearValidation(elemValue) { // if(!isEmpty(elemValue,"year")){ // // if(elemValue.length == 2){ // return true; // } // else { // // alert("Enter Valid Year"); // return false; // } // } // } // // function codeValidation(elemValue) { // if (!isEmpty(elemValue,"code")){ // // if(elemValue.length > 2 && elemValue.length <= 3){ // // return true; // } // } // else{ // alert("Enter Valid Security Code"); // return false; // // } }
// Generated by CoffeeScript 1.3.3 (function() { var TreeStream; TreeStream = require('./treestream'); module.exports = function(roots, list, callback) { var files, root, stream, _i, _len, _results; stream = new TreeStream(list); files = []; stream.on('file', function(file) { return files.push(file); }); stream.on('end', function() { files.sort(); return callback(files); }); if (typeof roots === 'string') { return stream.visit(roots); } else { _results = []; for (_i = 0, _len = roots.length; _i < _len; _i++) { root = roots[_i]; _results.push(stream.visit(root)); } return _results; } }; }).call(this);
import { appName, buildVersion, version } from 'config'; export const index = async ctx => { ctx.body = { appName: appName, environment: process.env.NODE_ENV || 'development', version: version, build: buildVersion, }; ctx.status = 200; };
CKEDITOR.plugins.setLang("smiley","az",{options:"Smayli-nin seçimləri",title:"Smayli-ni daxil et",toolbar:"Smayli"});
import pino from 'pino' const logger = pino({ level: process.env.LOG_LEVEL || 'info' }); export default logger
module.exports = function (string) { var i = 0; var replacements = { 'AB': 'AA', 'BA': 'AA', 'CB': 'CC', 'BC': 'CC', 'AA': 'A', 'CC': 'C' }; while (i < string.length) { var replacement = replacements[string.substr(i, 2)]; if (replacement) { string = string.substr(0, i) + replacement + string.substr(i + 2); } else { i++; } } return string; };
const Ciudad = require('../models/Ciudad'); const Estado = require('../models/Estado'); const { isBoolean } = require('./CategoriasController'); /* ========================================== Registrar un ciudad: POST - /ciudad Body: (x-www-form-urlencoded) nameCiudad (string), idEstadoF (int) ========================================== */ exports.register = async (req, res) => { const { body } = req; console.log(body); if (body.nameCiudad != '' && body.nameCiudad && body.idEstadoF) { const validVisible = isBoolean(body.isVisible); if (validVisible) { try { const ciudad = await Ciudad.create({ nameCiudad: body.nameCiudad, idEstadoF: body.idEstadoF, isVisible: body.isVisible }); return res.status(200).json({ ok: true, ciudad }); } catch (err) { if (err.original) { if (err.original.errno == 1452) { // Accion Prohibida return res.status(403).json({ ok: false, msg: err.original.sqlMessage }); } } console.log(err); return res.status(500).json({ msg: 'Internal server error' }); } } else { return res.status(400).json({ ok: false, msg: 'Bad Request: isVisible debe ser true o false' }); } } return res.status(400).json({ msg: 'Bad Request: Ingrese una ciudad' }); } // ========================================== // Obtiene todas las ciudades: GET /ciudad // ========================================== exports.getAll = async (req, res) => { // console.log(req); try { const ciudades = await Ciudad.findAll({ include: { all: true }}); return res.status(200).json({ ok: true, ciudades }); } catch (err) { console.log(err); return res.status(500).json({ msg: 'Internal server error' }); } } // ========================================== // Obtiene todos las ciudades de un estado en especifico: GET /ciudad-por-idestadof?idEstadoF=0 // ========================================== exports.getCityByStateId = async (req, res) => { let idEstadoF = req.query.idEstadoF || 0; // console.log(req); if (idEstadoF) { try { const ciudades = await Ciudad.findAll({ order: [["nameCiudad", "ASC"]], // Ordenar por orden alfabetico los nombres de los ciudades. where: { isVisible: true, idEstadoF, }, include: [ { model: Estado, required: true, as: "estado", }, ], }); const cantidadEstados = ciudades.length; return res.status(200).json({ ok: true, cantidadEstados, ciudades, }); } catch (err) { console.log(err); return res.status(500).json({ msg: "Internal server error", }); } } else { // 400 (Bad Request) return res.status(400).json({ ok: false, msg: "Debe enviar un idEstadoF", }); } }; // ========================================== // Editar un ciudad: PUT /ciudad/:idCiudad Ejm. /ciudad/1 idCiudad: Params. nameCiudad (string), idEstadoF (int) Body (x-www-form-urlencoded) // ========================================== exports.edit = async (req, res) => { /* // Para debugger console.log('Por aqui'); console.log(req.params); console.log(req.body);*/ // Obtener los datos const idCiudad = req.params.idCiudad, nameCiudad = req.body.nameCiudad, idEstadoF = req.body.idEstadoF, isVisible = req.body.isVisible; // Si existen las variables que se necesitan. if (idCiudad) { if (isBoolean(isVisible)) { try { // Validar que no esten vacios los datos. if (nameCiudad != '' && nameCiudad && idEstadoF) { const ciudad = await Ciudad.findOne({ where: { idCiudad } }); //Cambiar el nombre del ciudad: ciudad.nameCiudad = nameCiudad; ciudad.idEstadoF = idEstadoF; ciudad.updatedAt = new Date(); //Metodo save de sequelize para guardar en la BDD const resultado = await ciudad.save(); if (!resultado) return next(); return res.status(200).json({ ok: true, msg: 'Ciudad Actualizada' }); } return res.status(400).json({ ok: false, msg: 'Bad Request: Ingrese una ciudad valida' }); } catch (err) { //console.log(err.original.errno); if (err.original.errno == 1452) { // Accion Prohibida return res.status(403).json({ ok: false, msg: err.original.sqlMessage }); } return res.status(500).json({ ok: false, msg: 'Internal server error' }); } } else { return res.status(400).json({ ok: false, msg: 'Bad Request: isVisible debe ser true o false' }); } } else { // Accion prohibida. (Error) return res.status(403).json({ ok: false, msg: 'El id de la ciudad es obligatorio' }); } } // ========================================== // Borrar un ciudad: DELETE /ciudad/:idCiudad Ejm. /ciudad/1 // ========================================== exports.delete = async (req, res, next) => { /* // Para debugger console.log('Por aqui'); console.log(req.params); console.log(req.body);*/ // Obtener los datos const { idCiudad } = req.params; if (idCiudad) { try { //Eliminar el ciudad const resultado = await Ciudad.destroy({ where: { idCiudad } }); if (!resultado) { return res.status(400).json({ ok: false, msg: 'idCiudad no registrada' }); } return res.status(200).json({ ok: true, msg: 'Ciudad Eliminada' }); } catch (err) { console.log(err); return res.status(500).json({ msg: 'Internal server error' }); } } else { // Accion prohibida. (Error) return res.status(403).json({ ok: false, msg: 'El id de la ciudad es obligatorio' }); } }
/* * jQuery Superfish Menu Plugin - v1.7.4 * Copyright (c) 2013 Joel Birch * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ ;(function ($) { "use strict"; var methods = (function () { // private properties and methods go here var c = { bcClass: 'sf-breadcrumb', menuClass: 'sf-js-enabled', anchorClass: 'sf-with-ul', menuArrowClass: 'sf-arrows' }, ios = (function () { var ios = /iPhone|iPad|iPod/i.test(navigator.userAgent); if (ios) { // iOS clicks only bubble as far as body children $(window).load(function () { $('body').children().on('click', $.noop); }); } return ios; })(), wp7 = (function () { var style = document.documentElement.style; return ('behavior' in style && 'fill' in style && /iemobile/i.test(navigator.userAgent)); })(), toggleMenuClasses = function ($menu, o) { var classes = c.menuClass; if (o.cssArrows) { classes += ' ' + c.menuArrowClass; } $menu.toggleClass(classes); }, setPathToCurrent = function ($menu, o) { return $menu.find('li.' + o.pathClass).slice(0, o.pathLevels) .addClass(o.hoverClass + ' ' + c.bcClass) .filter(function () { return ($(this).children(o.popUpSelector).hide().show().length); }).removeClass(o.pathClass); }, toggleAnchorClass = function ($li) { $li.children('a').toggleClass(c.anchorClass); }, toggleTouchAction = function ($menu) { var touchAction = $menu.css('ms-touch-action'); touchAction = (touchAction === 'pan-y') ? 'auto' : 'pan-y'; $menu.css('ms-touch-action', touchAction); }, applyHandlers = function ($menu, o) { var targets = 'li:has(' + o.popUpSelector + ')'; if ($.fn.hoverIntent && !o.disableHI) { $menu.hoverIntent(over, out, targets); } else { $menu .on('mouseenter.superfish', targets, over) .on('mouseleave.superfish', targets, out); } var touchevent = 'MSPointerDown.superfish'; if (!ios) { touchevent += ' touchend.superfish'; } if (wp7) { touchevent += ' mousedown.superfish'; } $menu .on('focusin.superfish', 'li', over) .on('focusout.superfish', 'li', out) .on(touchevent, 'a', o, touchHandler); }, touchHandler = function (e) { var $this = $(this), $ul = $this.siblings(e.data.popUpSelector); if ($ul.length > 0 && $ul.is(':hidden')) { $this.one('click.superfish', false); if (e.type === 'MSPointerDown') { $this.trigger('focus'); } else { $.proxy(over, $this.parent('li'))(); } } }, over = function () { var $this = $(this), o = getOptions($this); clearTimeout(o.sfTimer); $this.siblings().superfish('hide').end().superfish('show'); }, out = function () { var $this = $(this), o = getOptions($this); if (ios) { $.proxy(close, $this, o)(); } else { clearTimeout(o.sfTimer); o.sfTimer = setTimeout($.proxy(close, $this, o), o.delay); } }, close = function (o) { o.retainPath = ($.inArray(this[0], o.$path) > -1); this.superfish('hide'); if (!this.parents('.' + o.hoverClass).length) { o.onIdle.call(getMenu(this)); if (o.$path.length) { $.proxy(over, o.$path)(); } } }, getMenu = function ($el) { return $el.closest('.' + c.menuClass); }, getOptions = function ($el) { return getMenu($el).data('sf-options'); }; return { // public methods hide: function (instant) { if (this.length) { var $this = this, o = getOptions($this); if (!o) { return this; } var not = (o.retainPath === true) ? o.$path : '', $ul = $this.find('li.' + o.hoverClass).add(this).not(not).removeClass(o.hoverClass).children(o.popUpSelector), speed = o.speedOut; if (instant) { $ul.show(); speed = 0; } o.retainPath = false; o.onBeforeHide.call($ul); $ul.stop(true, true).animate(o.animationOut, speed, function () { var $this = $(this); o.onHide.call($this); }); } return this; }, show: function () { var o = getOptions(this); if (!o) { return this; } var $this = this.addClass(o.hoverClass), $ul = $this.children(o.popUpSelector); o.onBeforeShow.call($ul); $ul.stop(true, true).animate(o.animation, o.speed, function () { o.onShow.call($ul); }); return this; }, destroy: function () { return this.each(function () { var $this = $(this), o = $this.data('sf-options'), $hasPopUp; if (!o) { return false; } $hasPopUp = $this.find(o.popUpSelector).parent('li'); clearTimeout(o.sfTimer); toggleMenuClasses($this, o); toggleAnchorClass($hasPopUp); toggleTouchAction($this); // remove event handlers $this.off('.superfish').off('.hoverIntent'); // clear animation's inline display style $hasPopUp.children(o.popUpSelector).attr('style', function (i, style) { return style.replace(/display[^;]+;?/g, ''); }); // reset 'current' path classes o.$path.removeClass(o.hoverClass + ' ' + c.bcClass).addClass(o.pathClass); $this.find('.' + o.hoverClass).removeClass(o.hoverClass); o.onDestroy.call($this); $this.removeData('sf-options'); }); }, init: function (op) { return this.each(function () { var $this = $(this); if ($this.data('sf-options')) { return false; } var o = $.extend({}, $.fn.superfish.defaults, op), $hasPopUp = $this.find(o.popUpSelector).parent('li'); o.$path = setPathToCurrent($this, o); $this.data('sf-options', o); toggleMenuClasses($this, o); toggleAnchorClass($hasPopUp); toggleTouchAction($this); applyHandlers($this, o); $hasPopUp.not('.' + c.bcClass).superfish('hide', true); o.onInit.call(this); }); } }; })(); $.fn.superfish = function (method, args) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || ! method) { return methods.init.apply(this, arguments); } else { return $.error('Method ' + method + ' does not exist on jQuery.fn.superfish'); } }; $.fn.superfish.defaults = { popUpSelector: 'ul,.sf-mega', // within menu context hoverClass: 'sfHover', pathClass: 'overrideThisToUse', pathLevels: 1, delay: 800, animation: {height: 'show'}, animationOut: {height: 'hide'}, speed: 'normal', speedOut: 'fast', cssArrows: true, disableHI: false, onInit: $.noop, onBeforeShow: $.noop, onShow: $.noop, onBeforeHide: $.noop, onHide: $.noop, onIdle: $.noop, onDestroy: $.noop }; // soon to be deprecated $.fn.extend({ hideSuperfishUl: methods.hide, showSuperfishUl: methods.show }); })(jQuery); $(window).load(function(){ $('.sf-menu').superfish() })
module.exports = new Date(1973, 2, 14)
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define("react",[],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.React=e()}}(function(){return function e(t,n,r){function i(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(s)return s(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return i(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var s="function"==typeof require&&require,o=0;o<r.length;o++)i(r[o]);return i}({1:[function(e,t,n){"use strict";var r=e(19),i=e(32),s=e(34),o=e(33),u=e(38),a=e(39),f=e(55),l=(e(56),e(40)),c=e(51),h=e(54),p=e(64),d=e(68),v=e(73),m=e(76),g=e(79),y=e(82),b=e(27),w=e(115),E=e(142);h.inject();var S=f.createElement,x=f.createFactory,T=f.cloneElement,N=v.measure("React","render",d.render),C={Children:{map:i.map,forEach:i.forEach,count:i.count,only:E},Component:s,DOM:l,PropTypes:m,initializeTouchEvents:function(e){r.useTouchEvents=e},createClass:o.createClass,createElement:S,cloneElement:T,createFactory:x,createMixin:function(e){return e},constructAndRenderComponent:d.constructAndRenderComponent,constructAndRenderComponentByID:d.constructAndRenderComponentByID,findDOMNode:w,render:N,renderToString:y.renderToString,renderToStaticMarkup:y.renderToStaticMarkup,unmountComponentAtNode:d.unmountComponentAtNode,isValidElement:f.isValidElement,withContext:u.withContext,__spread:b};"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({CurrentOwner:a,InstanceHandles:p,Mount:d,Reconciler:g,TextComponent:c}),C.version="0.13.3",t.exports=C},{115:115,142:142,19:19,27:27,32:32,33:33,34:34,38:38,39:39,40:40,51:51,54:54,55:55,56:56,64:64,68:68,73:73,76:76,79:79,82:82}],2:[function(e,t,n){"use strict";var r=e(117),i={componentDidMount:function(){this.props.autoFocus&&r(this.getDOMNode())}};t.exports=i},{117:117}],3:[function(e,t,n){"use strict";function r(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}function i(e){return(e.ctrlKey||e.altKey||e.metaKey)&&(!e.ctrlKey||!e.altKey)}function s(e){switch(e){case L.topCompositionStart:return A.compositionStart;case L.topCompositionEnd:return A.compositionEnd;case L.topCompositionUpdate:return A.compositionUpdate}}function o(e,t){return e===L.topKeyDown&&t.keyCode===E}function u(e,t){switch(e){case L.topKeyUp:return-1!==w.indexOf(t.keyCode);case L.topKeyDown:return t.keyCode!==E;case L.topKeyPress:case L.topMouseDown:case L.topBlur:return!0;default:return!1}}function a(e){var t=e.detail;return"object"==typeof t&&"data"in t?t.data:null}function f(e,t,n,r){var i,f;if(S?i=s(e):M?u(e,r)&&(i=A.compositionEnd):o(e,r)&&(i=A.compositionStart),!i)return null;N&&(M||i!==A.compositionStart?i===A.compositionEnd&&M&&(f=M.getData()):M=m.getPooled(t));var l=g.getPooled(i,n,r);if(f)l.data=f;else{var c=a(r);null!==c&&(l.data=c)}return d.accumulateTwoPhaseDispatches(l),l}function l(e,t){switch(e){case L.topCompositionEnd:return a(t);case L.topKeyPress:var n=t.which;return n!==C?null:(O=!0,k);case L.topTextInput:var r=t.data;return r===k&&O?null:r;default:return null}}function c(e,t){if(M){if(e===L.topCompositionEnd||u(e,t)){var n=M.getData();return m.release(M),M=null,n}return null}switch(e){case L.topPaste:return null;case L.topKeyPress:return t.which&&!i(t)?String.fromCharCode(t.which):null;case L.topCompositionEnd:return N?null:t.data;default:return null}}function h(e,t,n,r){var i;if(i=T?l(e,r):c(e,r),!i)return null;var s=y.getPooled(A.beforeInput,n,r);return s.data=i,d.accumulateTwoPhaseDispatches(s),s}var p=e(15),d=e(20),v=e(21),m=e(22),g=e(91),y=e(95),b=e(139),w=[9,13,27,32],E=229,S=v.canUseDOM&&"CompositionEvent"in window,x=null;v.canUseDOM&&"documentMode"in document&&(x=document.documentMode);var T=v.canUseDOM&&"TextEvent"in window&&!x&&!r(),N=v.canUseDOM&&(!S||x&&x>8&&11>=x),C=32,k=String.fromCharCode(C),L=p.topLevelTypes,A={beforeInput:{phasedRegistrationNames:{bubbled:b({onBeforeInput:null}),captured:b({onBeforeInputCapture:null})},dependencies:[L.topCompositionEnd,L.topKeyPress,L.topTextInput,L.topPaste]},compositionEnd:{phasedRegistrationNames:{bubbled:b({onCompositionEnd:null}),captured:b({onCompositionEndCapture:null})},dependencies:[L.topBlur,L.topCompositionEnd,L.topKeyDown,L.topKeyPress,L.topKeyUp,L.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:b({onCompositionStart:null}),captured:b({onCompositionStartCapture:null})},dependencies:[L.topBlur,L.topCompositionStart,L.topKeyDown,L.topKeyPress,L.topKeyUp,L.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:b({onCompositionUpdate:null}),captured:b({onCompositionUpdateCapture:null})},dependencies:[L.topBlur,L.topCompositionUpdate,L.topKeyDown,L.topKeyPress,L.topKeyUp,L.topMouseDown]}},O=!1,M=null,_={eventTypes:A,extractEvents:function(e,t,n,r){return[f(e,t,n,r),h(e,t,n,r)]}};t.exports=_},{139:139,15:15,20:20,21:21,22:22,91:91,95:95}],4:[function(e,t,n){"use strict";function r(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var i={boxFlex:!0,boxFlexGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,strokeDashoffset:!0,strokeOpacity:!0,strokeWidth:!0},s=["Webkit","ms","Moz","O"];Object.keys(i).forEach(function(e){s.forEach(function(t){i[r(t,e)]=i[e]})});var o={background:{backgroundImage:!0,backgroundPosition:!0,backgroundRepeat:!0,backgroundColor:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0}},u={isUnitlessNumber:i,shorthandPropertyExpansions:o};t.exports=u},{}],5:[function(e,t,n){"use strict";var r=e(4),i=e(21),s=(e(106),e(111)),o=e(131),u=e(141),a=(e(150),u(function(e){return o(e)})),f="cssFloat";i.canUseDOM&&void 0===document.documentElement.style.cssFloat&&(f="styleFloat");var l={createMarkupForStyles:function(e){var t="";for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];null!=r&&(t+=a(n)+":",t+=s(n,r)+";")}return t||null},setValueForStyles:function(e,t){var n=e.style;for(var i in t)if(t.hasOwnProperty(i)){var o=s(i,t[i]);if("float"===i&&(i=f),o)n[i]=o;else{var u=r.shorthandPropertyExpansions[i];if(u)for(var a in u)n[a]="";else n[i]=""}}}};t.exports=l},{106:106,111:111,131:131,141:141,150:150,21:21,4:4}],6:[function(e,t,n){"use strict";function r(){this._callbacks=null,this._contexts=null}var i=e(28),s=e(27),o=e(133);s(r.prototype,{enqueue:function(e,t){this._callbacks=this._callbacks||[],this._contexts=this._contexts||[],this._callbacks.push(e),this._contexts.push(t)},notifyAll:function(){var e=this._callbacks,t=this._contexts;if(e){o(e.length===t.length),this._callbacks=null,this._contexts=null;for(var n=0,r=e.length;r>n;n++)e[n].call(t[n]);e.length=0,t.length=0}},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),i.addPoolingTo(r),t.exports=r},{133:133,27:27,28:28}],7:[function(e,t,n){"use strict";function r(e){return"SELECT"===e.nodeName||"INPUT"===e.nodeName&&"file"===e.type}function i(e){var t=x.getPooled(L.change,O,e);w.accumulateTwoPhaseDispatches(t),S.batchedUpdates(s,t)}function s(e){b.enqueueEvents(e),b.processEventQueue()}function o(e,t){A=e,O=t,A.attachEvent("onchange",i)}function u(){A&&(A.detachEvent("onchange",i),A=null,O=null)}function a(e,t,n){return e===k.topChange?n:void 0}function f(e,t,n){e===k.topFocus?(u(),o(t,n)):e===k.topBlur&&u()}function l(e,t){A=e,O=t,M=e.value,_=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(A,"value",H),A.attachEvent("onpropertychange",h)}function c(){A&&(delete A.value,A.detachEvent("onpropertychange",h),A=null,O=null,M=null,_=null)}function h(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==M&&(M=t,i(e))}}function p(e,t,n){return e===k.topInput?n:void 0}function d(e,t,n){e===k.topFocus?(c(),l(t,n)):e===k.topBlur&&c()}function v(e,t,n){return e!==k.topSelectionChange&&e!==k.topKeyUp&&e!==k.topKeyDown||!A||A.value===M?void 0:(M=A.value,O)}function m(e){return"INPUT"===e.nodeName&&("checkbox"===e.type||"radio"===e.type)}function g(e,t,n){return e===k.topClick?n:void 0}var y=e(15),b=e(17),w=e(20),E=e(21),S=e(85),x=e(93),T=e(134),N=e(136),C=e(139),k=y.topLevelTypes,L={change:{phasedRegistrationNames:{bubbled:C({onChange:null}),captured:C({onChangeCapture:null})},dependencies:[k.topBlur,k.topChange,k.topClick,k.topFocus,k.topInput,k.topKeyDown,k.topKeyUp,k.topSelectionChange]}},A=null,O=null,M=null,_=null,D=!1;E.canUseDOM&&(D=T("change")&&(!("documentMode"in document)||document.documentMode>8));var P=!1;E.canUseDOM&&(P=T("input")&&(!("documentMode"in document)||document.documentMode>9));var H={get:function(){return _.get.call(this)},set:function(e){M=""+e,_.set.call(this,e)}},B={eventTypes:L,extractEvents:function(e,t,n,i){var s,o;if(r(t)?D?s=a:o=f:N(t)?P?s=p:(s=v,o=d):m(t)&&(s=g),s){var u=s(e,t,n);if(u){var l=x.getPooled(L.change,u,i);return w.accumulateTwoPhaseDispatches(l),l}}o&&o(e,t,n)}};t.exports=B},{134:134,136:136,139:139,15:15,17:17,20:20,21:21,85:85,93:93}],8:[function(e,t,n){"use strict";var r=0,i={createReactRootIndex:function(){return r++}};t.exports=i},{}],9:[function(e,t,n){"use strict";function r(e,t,n){e.insertBefore(t,e.childNodes[n]||null)}var i=e(12),s=e(70),o=e(145),u=e(133),a={dangerouslyReplaceNodeWithMarkup:i.dangerouslyReplaceNodeWithMarkup,updateTextContent:o,processUpdates:function(e,t){for(var n,a=null,f=null,l=0;l<e.length;l++)if(n=e[l],n.type===s.MOVE_EXISTING||n.type===s.REMOVE_NODE){var c=n.fromIndex,h=n.parentNode.childNodes[c],p=n.parentID;u(h),a=a||{},a[p]=a[p]||[],a[p][c]=h,f=f||[],f.push(h)}var d=i.dangerouslyRenderMarkup(t);if(f)for(var v=0;v<f.length;v++)f[v].parentNode.removeChild(f[v]);for(var m=0;m<e.length;m++)switch(n=e[m],n.type){case s.INSERT_MARKUP:r(n.parentNode,d[n.markupIndex],n.toIndex);break;case s.MOVE_EXISTING:r(n.parentNode,a[n.parentID][n.fromIndex],n.toIndex);break;case s.TEXT_CONTENT:o(n.parentNode,n.textContent);break;case s.REMOVE_NODE:}}};t.exports=a},{12:12,133:133,145:145,70:70}],10:[function(e,t,n){"use strict";function r(e,t){return(e&t)===t}var i=e(133),s={MUST_USE_ATTRIBUTE:1,MUST_USE_PROPERTY:2,HAS_SIDE_EFFECTS:4,HAS_BOOLEAN_VALUE:8,HAS_NUMERIC_VALUE:16,HAS_POSITIVE_NUMERIC_VALUE:48,HAS_OVERLOADED_BOOLEAN_VALUE:64,injectDOMPropertyConfig:function(e){var t=e.Properties||{},n=e.DOMAttributeNames||{},o=e.DOMPropertyNames||{},a=e.DOMMutationMethods||{};e.isCustomAttribute&&u._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var f in t){i(!u.isStandardName.hasOwnProperty(f)),u.isStandardName[f]=!0;var l=f.toLowerCase();if(u.getPossibleStandardName[l]=f,n.hasOwnProperty(f)){var c=n[f];u.getPossibleStandardName[c]=f,u.getAttributeName[f]=c}else u.getAttributeName[f]=l;u.getPropertyName[f]=o.hasOwnProperty(f)?o[f]:f,a.hasOwnProperty(f)?u.getMutationMethod[f]=a[f]:u.getMutationMethod[f]=null;var h=t[f];u.mustUseAttribute[f]=r(h,s.MUST_USE_ATTRIBUTE),u.mustUseProperty[f]=r(h,s.MUST_USE_PROPERTY),u.hasSideEffects[f]=r(h,s.HAS_SIDE_EFFECTS),u.hasBooleanValue[f]=r(h,s.HAS_BOOLEAN_VALUE),u.hasNumericValue[f]=r(h,s.HAS_NUMERIC_VALUE),u.hasPositiveNumericValue[f]=r(h,s.HAS_POSITIVE_NUMERIC_VALUE),u.hasOverloadedBooleanValue[f]=r(h,s.HAS_OVERLOADED_BOOLEAN_VALUE),i(!u.mustUseAttribute[f]||!u.mustUseProperty[f]),i(u.mustUseProperty[f]||!u.hasSideEffects[f]),i(!!u.hasBooleanValue[f]+!!u.hasNumericValue[f]+!!u.hasOverloadedBooleanValue[f]<=1)}}},o={},u={ID_ATTRIBUTE_NAME:"data-reactid",isStandardName:{},getPossibleStandardName:{},getAttributeName:{},getPropertyName:{},getMutationMethod:{},mustUseAttribute:{},mustUseProperty:{},hasSideEffects:{},hasBooleanValue:{},hasNumericValue:{},hasPositiveNumericValue:{},hasOverloadedBooleanValue:{},_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<u._isCustomAttributeFunctions.length;t++){var n=u._isCustomAttributeFunctions[t];if(n(e))return!0}return!1},getDefaultValueForProperty:function(e,t){var n,r=o[e];return r||(o[e]=r={}),t in r||(n=document.createElement(e),r[t]=n[t]),r[t]},injection:s};t.exports=u},{133:133}],11:[function(e,t,n){"use strict";function r(e,t){return null==t||i.hasBooleanValue[e]&&!t||i.hasNumericValue[e]&&isNaN(t)||i.hasPositiveNumericValue[e]&&1>t||i.hasOverloadedBooleanValue[e]&&t===!1}var i=e(10),s=e(143),o=(e(150),{createMarkupForID:function(e){return i.ID_ATTRIBUTE_NAME+"="+s(e)},createMarkupForProperty:function(e,t){if(i.isStandardName.hasOwnProperty(e)&&i.isStandardName[e]){if(r(e,t))return"";var n=i.getAttributeName[e];return i.hasBooleanValue[e]||i.hasOverloadedBooleanValue[e]&&t===!0?n:n+"="+s(t)}return i.isCustomAttribute(e)?null==t?"":e+"="+s(t):null},setValueForProperty:function(e,t,n){if(i.isStandardName.hasOwnProperty(t)&&i.isStandardName[t]){var s=i.getMutationMethod[t];if(s)s(e,n);else if(r(t,n))this.deleteValueForProperty(e,t);else if(i.mustUseAttribute[t])e.setAttribute(i.getAttributeName[t],""+n);else{var o=i.getPropertyName[t];i.hasSideEffects[t]&&""+e[o]==""+n||(e[o]=n)}}else i.isCustomAttribute(t)&&(null==n?e.removeAttribute(t):e.setAttribute(t,""+n))},deleteValueForProperty:function(e,t){if(i.isStandardName.hasOwnProperty(t)&&i.isStandardName[t]){var n=i.getMutationMethod[t];if(n)n(e,void 0);else if(i.mustUseAttribute[t])e.removeAttribute(i.getAttributeName[t]);else{var r=i.getPropertyName[t],s=i.getDefaultValueForProperty(e.nodeName,r);i.hasSideEffects[t]&&""+e[r]===s||(e[r]=s)}}else i.isCustomAttribute(t)&&e.removeAttribute(t)}});t.exports=o},{10:10,143:143,150:150}],12:[function(e,t,n){"use strict";function r(e){return e.substring(1,e.indexOf(" "))}var i=e(21),s=e(110),o=e(112),u=e(125),a=e(133),f=/^(<[^ \/>]+)/,l="data-danger-index",c={dangerouslyRenderMarkup:function(e){a(i.canUseDOM);for(var t,n={},c=0;c<e.length;c++)a(e[c]),t=r(e[c]),t=u(t)?t:"*",n[t]=n[t]||[],n[t][c]=e[c];var h=[],p=0;for(t in n)if(n.hasOwnProperty(t)){var d,v=n[t];for(d in v)if(v.hasOwnProperty(d)){var m=v[d];v[d]=m.replace(f,"$1 "+l+'="'+d+'" ')}for(var g=s(v.join(""),o),y=0;y<g.length;++y){var b=g[y];b.hasAttribute&&b.hasAttribute(l)&&(d=+b.getAttribute(l),b.removeAttribute(l),a(!h.hasOwnProperty(d)),h[d]=b,p+=1)}}return a(p===h.length),a(h.length===e.length),h},dangerouslyReplaceNodeWithMarkup:function(e,t){a(i.canUseDOM),a(t),a("html"!==e.tagName.toLowerCase());var n=s(t,o)[0];e.parentNode.replaceChild(n,e)}};t.exports=c},{110:110,112:112,125:125,133:133,21:21}],13:[function(e,t,n){"use strict";var r=e(139),i=[r({ResponderEventPlugin:null}),r({SimpleEventPlugin:null}),r({TapEventPlugin:null}),r({EnterLeaveEventPlugin:null}),r({ChangeEventPlugin:null}),r({SelectEventPlugin:null}),r({BeforeInputEventPlugin:null}),r({AnalyticsEventPlugin:null}),r({MobileSafariClickEventPlugin:null})];t.exports=i},{139:139}],14:[function(e,t,n){"use strict";var r=e(15),i=e(20),s=e(97),o=e(68),u=e(139),a=r.topLevelTypes,f=o.getFirstReactDOM,l={mouseEnter:{registrationName:u({onMouseEnter:null}),dependencies:[a.topMouseOut,a.topMouseOver]},mouseLeave:{registrationName:u({onMouseLeave:null}),dependencies:[a.topMouseOut,a.topMouseOver]}},c=[null,null],h={eventTypes:l,extractEvents:function(e,t,n,r){if(e===a.topMouseOver&&(r.relatedTarget||r.fromElement))return null;if(e!==a.topMouseOut&&e!==a.topMouseOver)return null;var u;if(t.window===t)u=t;else{var h=t.ownerDocument;u=h?h.defaultView||h.parentWindow:window}var d,v;if(e===a.topMouseOut?(d=t,v=f(r.relatedTarget||r.toElement)||u):(d=u,v=t),d===v)return null;var m=d?o.getID(d):"",g=v?o.getID(v):"",y=s.getPooled(l.mouseLeave,m,r);y.type="mouseleave",y.target=d,y.relatedTarget=v;var b=s.getPooled(l.mouseEnter,g,r);return b.type="mouseenter",b.target=v,b.relatedTarget=d,i.accumulateEnterLeaveDispatches(y,b,m,g),c[0]=y,c[1]=b,c}};t.exports=h},{139:139,15:15,20:20,68:68,97:97}],15:[function(e,t,n){"use strict";var r=e(138),i=r({bubbled:null,captured:null}),s=r({topBlur:null,topChange:null,topClick:null,topCompositionEnd:null,topCompositionStart:null,topCompositionUpdate:null,topContextMenu:null,topCopy:null,topCut:null,topDoubleClick:null,topDrag:null,topDragEnd:null,topDragEnter:null,topDragExit:null,topDragLeave:null,topDragOver:null,topDragStart:null,topDrop:null,topError:null,topFocus:null,topInput:null,topKeyDown:null,topKeyPress:null,topKeyUp:null,topLoad:null,topMouseDown:null,topMouseMove:null,topMouseOut:null,topMouseOver:null,topMouseUp:null,topPaste:null,topReset:null,topScroll:null,topSelectionChange:null,topSubmit:null,topTextInput:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topWheel:null}),o={topLevelTypes:s,PropagationPhases:i};t.exports=o},{138:138}],16:[function(e,t,n){var r=e(112),i={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!0),{remove:function(){e.removeEventListener(t,n,!0)}}):{remove:r}},registerDefault:function(){}};t.exports=i},{112:112}],17:[function(e,t,n){"use strict";var r=e(18),i=e(19),s=e(103),o=e(118),u=e(133),a={},f=null,l=function(e){if(e){var t=i.executeDispatch,n=r.getPluginModuleForEvent(e);n&&n.executeDispatch&&(t=n.executeDispatch),i.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e)}},c=null,h={injection:{injectMount:i.injection.injectMount,injectInstanceHandle:function(e){c=e},getInstanceHandle:function(){return c},injectEventPluginOrder:r.injectEventPluginOrder,injectEventPluginsByName:r.injectEventPluginsByName},eventNameDispatchConfigs:r.eventNameDispatchConfigs,registrationNameModules:r.registrationNameModules,putListener:function(e,t,n){u(!n||"function"==typeof n);var r=a[t]||(a[t]={});r[e]=n},getListener:function(e,t){var n=a[t];return n&&n[e]},deleteListener:function(e,t){var n=a[t];n&&delete n[e]},deleteAllListeners:function(e){for(var t in a)delete a[t][e]},extractEvents:function(e,t,n,i){for(var o,u=r.plugins,a=0,f=u.length;f>a;a++){var l=u[a];if(l){var c=l.extractEvents(e,t,n,i);c&&(o=s(o,c))}}return o},enqueueEvents:function(e){e&&(f=s(f,e))},processEventQueue:function(){var e=f;f=null,o(e,l),u(!f)},__purge:function(){a={}},__getListenerBank:function(){return a}};t.exports=h},{103:103,118:118,133:133,18:18,19:19}],18:[function(e,t,n){"use strict";function r(){if(u)for(var e in a){var t=a[e],n=u.indexOf(e);if(o(n>-1),!f.plugins[n]){o(t.extractEvents),f.plugins[n]=t;var r=t.eventTypes;for(var s in r)o(i(r[s],t,s))}}}function i(e,t,n){o(!f.eventNameDispatchConfigs.hasOwnProperty(n)),f.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var i in r)if(r.hasOwnProperty(i)){var u=r[i];s(u,t,n)}return!0}return e.registrationName?(s(e.registrationName,t,n),!0):!1}function s(e,t,n){o(!f.registrationNameModules[e]),f.registrationNameModules[e]=t,f.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var o=e(133),u=null,a={},f={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(e){o(!u),u=Array.prototype.slice.call(e),r()},injectEventPluginsByName:function(e){var t=!1;for(var n in e)if(e.hasOwnProperty(n)){var i=e[n];a.hasOwnProperty(n)&&a[n]===i||(o(!a[n]),a[n]=i,t=!0)}t&&r()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return f.registrationNameModules[t.registrationName]||null;for(var n in t.phasedRegistrationNames)if(t.phasedRegistrationNames.hasOwnProperty(n)){var r=f.registrationNameModules[t.phasedRegistrationNames[n]];if(r)return r}return null},_resetEventPlugins:function(){u=null;for(var e in a)a.hasOwnProperty(e)&&delete a[e];f.plugins.length=0;var t=f.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var r=f.registrationNameModules;for(var i in r)r.hasOwnProperty(i)&&delete r[i]}};t.exports=f},{133:133}],19:[function(e,t,n){"use strict";function r(e){return e===m.topMouseUp||e===m.topTouchEnd||e===m.topTouchCancel}function i(e){return e===m.topMouseMove||e===m.topTouchMove}function s(e){return e===m.topMouseDown||e===m.topTouchStart}function o(e,t){var n=e._dispatchListeners,r=e._dispatchIDs;if(Array.isArray(n))for(var i=0;i<n.length&&!e.isPropagationStopped();i++)t(e,n[i],r[i]);else n&&t(e,n,r)}function u(e,t,n){e.currentTarget=v.Mount.getNode(n);var r=t(e,n);return e.currentTarget=null,r}function a(e,t){o(e,t),e._dispatchListeners=null,e._dispatchIDs=null}function f(e){var t=e._dispatchListeners,n=e._dispatchIDs;if(Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function l(e){var t=f(e);return e._dispatchIDs=null,e._dispatchListeners=null,t}function c(e){var t=e._dispatchListeners,n=e._dispatchIDs;d(!Array.isArray(t));var r=t?t(e,n):null;return e._dispatchListeners=null,e._dispatchIDs=null,r}function h(e){return!!e._dispatchListeners}var p=e(15),d=e(133),v={Mount:null,injectMount:function(e){v.Mount=e}},m=p.topLevelTypes,g={isEndish:r,isMoveish:i,isStartish:s,executeDirectDispatch:c,executeDispatch:u,executeDispatchesInOrder:a,executeDispatchesInOrderStopAtTrue:l,hasDispatches:h,injection:v,useTouchEvents:!1};t.exports=g},{133:133,15:15}],20:[function(e,t,n){"use strict";function r(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return m(e,r)}function i(e,t,n){var i=t?v.bubbled:v.captured,s=r(e,n,i);s&&(n._dispatchListeners=p(n._dispatchListeners,s),n._dispatchIDs=p(n._dispatchIDs,e))}function s(e){e&&e.dispatchConfig.phasedRegistrationNames&&h.injection.getInstanceHandle().traverseTwoPhase(e.dispatchMarker,i,e)}function o(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,i=m(e,r);i&&(n._dispatchListeners=p(n._dispatchListeners,i),n._dispatchIDs=p(n._dispatchIDs,e))}}function u(e){e&&e.dispatchConfig.registrationName&&o(e.dispatchMarker,null,e)}function a(e){d(e,s)}function f(e,t,n,r){h.injection.getInstanceHandle().traverseEnterLeave(n,r,o,e,t)}function l(e){d(e,u)}var c=e(15),h=e(17),p=e(103),d=e(118),v=c.PropagationPhases,m=h.getListener,g={accumulateTwoPhaseDispatches:a,accumulateDirectDispatches:l,accumulateEnterLeaveDispatches:f};t.exports=g},{103:103,118:118,15:15,17:17}],21:[function(e,t,n){"use strict";var r="undefined"!=typeof window&&!!window.document&&!!window.document.createElement,i={canUseDOM:r,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:r&&(!!window.addEventListener||!!window.attachEvent),canUseViewport:r&&!!window.screen,isInWorker:!r};t.exports=i},{}],22:[function(e,t,n){"use strict";function r(e){this._root=e,this._startText=this.getText(),this._fallbackText=null}var i=e(28),s=e(27),o=e(128);s(r.prototype,{getText:function(){return"value"in this._root?this._root.value:this._root[o()]},getData:function(){if(this._fallbackText)return this._fallbackText;var e,t,n=this._startText,r=n.length,i=this.getText(),s=i.length;for(e=0;r>e&&n[e]===i[e];e++);var o=r-e;for(t=1;o>=t&&n[r-t]===i[s-t];t++);var u=t>1?1-t:void 0;return this._fallbackText=i.slice(e,u),this._fallbackText}}),i.addPoolingTo(r),t.exports=r},{128:128,27:27,28:28}],23:[function(e,t,n){"use strict";var r,i=e(10),s=e(21),o=i.injection.MUST_USE_ATTRIBUTE,u=i.injection.MUST_USE_PROPERTY,a=i.injection.HAS_BOOLEAN_VALUE,f=i.injection.HAS_SIDE_EFFECTS,l=i.injection.HAS_NUMERIC_VALUE,c=i.injection.HAS_POSITIVE_NUMERIC_VALUE,h=i.injection.HAS_OVERLOADED_BOOLEAN_VALUE;if(s.canUseDOM){var p=document.implementation;r=p&&p.hasFeature&&p.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")}var d={isCustomAttribute:RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),Properties:{accept:null,acceptCharset:null,accessKey:null,action:null,allowFullScreen:o|a,allowTransparency:o,alt:null,async:a,autoComplete:null,autoPlay:a,cellPadding:null,cellSpacing:null,charSet:o,checked:u|a,classID:o,className:r?o:u,cols:o|c,colSpan:null,content:null,contentEditable:null,contextMenu:o,controls:u|a,coords:null,crossOrigin:null,data:null,dateTime:o,defer:a,dir:null,disabled:o|a,download:h,draggable:null,encType:null,form:o,formAction:o,formEncType:o,formMethod:o,formNoValidate:a,formTarget:o,frameBorder:o,headers:null,height:o,hidden:o|a,high:null,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:u,label:null,lang:null,list:o,loop:u|a,low:null,manifest:o,marginHeight:null,marginWidth:null,max:null,maxLength:o,media:o,mediaGroup:null,method:null,min:null,multiple:u|a,muted:u|a,name:null,noValidate:a,open:a,optimum:null,pattern:null,placeholder:null,poster:null,preload:null,radioGroup:null,readOnly:u|a,rel:null,required:a,role:o,rows:o|c,rowSpan:null,sandbox:null,scope:null,scoped:a,scrolling:null,seamless:o|a,selected:u|a,shape:null,size:o|c,sizes:o,span:c,spellCheck:null,src:null,srcDoc:u,srcSet:o,start:l,step:null,style:null,tabIndex:null,target:null,title:null,type:null,useMap:null,value:u|f,width:o,wmode:o,autoCapitalize:null,autoCorrect:null,itemProp:o,itemScope:o|a,itemType:o,itemID:o,itemRef:o,property:null,unselectable:o},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{autoCapitalize:"autocapitalize",autoComplete:"autocomplete",autoCorrect:"autocorrect",autoFocus:"autofocus",autoPlay:"autoplay",encType:"encoding",hrefLang:"hreflang",radioGroup:"radiogroup",spellCheck:"spellcheck",srcDoc:"srcdoc",srcSet:"srcset"}};t.exports=d},{10:10,21:21}],24:[function(e,t,n){"use strict";function r(e){f(null==e.props.checkedLink||null==e.props.valueLink)}function i(e){r(e),f(null==e.props.value&&null==e.props.onChange)}function s(e){r(e),f(null==e.props.checked&&null==e.props.onChange)}function o(e){this.props.valueLink.requestChange(e.target.value)}function u(e){this.props.checkedLink.requestChange(e.target.checked)}var a=e(76),f=e(133),l={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0},c={Mixin:{propTypes:{value:function(e,t,n){return!e[t]||l[e.type]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.")},checked:function(e,t,n){return!e[t]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")},onChange:a.func}},getValue:function(e){return e.props.valueLink?(i(e),e.props.valueLink.value):e.props.value},getChecked:function(e){return e.props.checkedLink?(s(e),e.props.checkedLink.value):e.props.checked},getOnChange:function(e){return e.props.valueLink?(i(e),o):e.props.checkedLink?(s(e),u):e.props.onChange}};t.exports=c},{133:133,76:76}],25:[function(e,t,n){"use strict";function r(e){e.remove()}var i=e(30),s=e(103),o=e(118),u=e(133),a={trapBubbledEvent:function(e,t){u(this.isMounted());var n=this.getDOMNode();u(n);var r=i.trapBubbledEvent(e,t,n);this._localEventListeners=s(this._localEventListeners,r)},componentWillUnmount:function(){this._localEventListeners&&o(this._localEventListeners,r)}};t.exports=a},{103:103,118:118,133:133,30:30}],26:[function(e,t,n){"use strict";var r=e(15),i=e(112),s=r.topLevelTypes,o={eventTypes:null,extractEvents:function(e,t,n,r){if(e===s.topTouchStart){var o=r.target;o&&!o.onclick&&(o.onclick=i)}}};t.exports=o},{112:112,15:15}],27:[function(e,t,n){"use strict";function r(e,t){if(null==e)throw new TypeError("Object.assign target cannot be null or undefined");for(var n=Object(e),r=Object.prototype.hasOwnProperty,i=1;i<arguments.length;i++){var s=arguments[i];if(null!=s){var o=Object(s);for(var u in o)r.call(o,u)&&(n[u]=o[u])}}return n}t.exports=r},{}],28:[function(e,t,n){"use strict";var r=e(133),i=function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)},s=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},o=function(e,t,n){var r=this;if(r.instancePool.length){var i=r.instancePool.pop();return r.call(i,e,t,n),i}return new r(e,t,n)},u=function(e,t,n,r,i){var s=this;if(s.instancePool.length){var o=s.instancePool.pop();return s.call(o,e,t,n,r,i),o}return new s(e,t,n,r,i)},a=function(e){var t=this;r(e instanceof t),e.destructor&&e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},f=10,l=i,c=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||l,n.poolSize||(n.poolSize=f),n.release=a,n},h={addPoolingTo:c,oneArgumentPooler:i,twoArgumentPooler:s,threeArgumentPooler:o,fiveArgumentPooler:u};t.exports=h},{133:133}],29:[function(e,t,n){"use strict";var r=e(115),i={getDOMNode:function(){return r(this)}};t.exports=i},{115:115}],30:[function(e,t,n){"use strict";function r(e){return Object.prototype.hasOwnProperty.call(e,v)||(e[v]=p++,c[e[v]]={}),c[e[v]]}var i=e(15),s=e(17),o=e(18),u=e(59),a=e(102),f=e(27),l=e(134),c={},h=!1,p=0,d={topBlur:"blur",topChange:"change",topClick:"click",topCompositionEnd:"compositionend",topCompositionStart:"compositionstart",topCompositionUpdate:"compositionupdate",topContextMenu:"contextmenu",topCopy:"copy",topCut:"cut",topDoubleClick:"dblclick",topDrag:"drag",topDragEnd:"dragend",topDragEnter:"dragenter",topDragExit:"dragexit",topDragLeave:"dragleave",topDragOver:"dragover",topDragStart:"dragstart",topDrop:"drop",topFocus:"focus",topInput:"input",topKeyDown:"keydown",topKeyPress:"keypress",topKeyUp:"keyup",topMouseDown:"mousedown",topMouseMove:"mousemove",topMouseOut:"mouseout",topMouseOver:"mouseover",topMouseUp:"mouseup",topPaste:"paste",topScroll:"scroll",topSelectionChange:"selectionchange",topTextInput:"textInput",topTouchCancel:"touchcancel",topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topWheel:"wheel"},v="_reactListenersID"+String(Math.random()).slice(2),m=f({},u,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(m.handleTopLevel),m.ReactEventListener=e}},setEnabled:function(e){m.ReactEventListener&&m.ReactEventListener.setEnabled(e)},isEnabled:function(){return!!m.ReactEventListener&&!!m.ReactEventListener.isEnabled()},listenTo:function(e,t){for(var n=t,s=r(n),u=o.registrationNameDependencies[e],a=i.topLevelTypes,f=0,c=u.length;c>f;f++){var h=u[f];s.hasOwnProperty(h)&&s[h]||(h===a.topWheel?l("wheel")?m.ReactEventListener.trapBubbledEvent(a.topWheel,"wheel",n):l("mousewheel")?m.ReactEventListener.trapBubbledEvent(a.topWheel,"mousewheel",n):m.ReactEventListener.trapBubbledEvent(a.topWheel,"DOMMouseScroll",n):h===a.topScroll?l("scroll",!0)?m.ReactEventListener.trapCapturedEvent(a.topScroll,"scroll",n):m.ReactEventListener.trapBubbledEvent(a.topScroll,"scroll",m.ReactEventListener.WINDOW_HANDLE):h===a.topFocus||h===a.topBlur?(l("focus",!0)?(m.ReactEventListener.trapCapturedEvent(a.topFocus,"focus",n),m.ReactEventListener.trapCapturedEvent(a.topBlur,"blur",n)):l("focusin")&&(m.ReactEventListener.trapBubbledEvent(a.topFocus,"focusin",n),m.ReactEventListener.trapBubbledEvent(a.topBlur,"focusout",n)),s[a.topBlur]=!0,s[a.topFocus]=!0):d.hasOwnProperty(h)&&m.ReactEventListener.trapBubbledEvent(h,d[h],n),s[h]=!0)}},trapBubbledEvent:function(e,t,n){return m.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return m.ReactEventListener.trapCapturedEvent(e,t,n)},ensureScrollValueMonitoring:function(){if(!h){var e=a.refreshScrollValues;m.ReactEventListener.monitorScrollValue(e),h=!0}},eventNameDispatchConfigs:s.eventNameDispatchConfigs,registrationNameModules:s.registrationNameModules,putListener:s.putListener,getListener:s.getListener,deleteListener:s.deleteListener,deleteAllListeners:s.deleteAllListeners});t.exports=m},{102:102,134:134,15:15,17:17,18:18,27:27,59:59}],31:[function(e,t,n){"use strict";var r=e(79),i=e(116),s=e(132),o=e(147),u={instantiateChildren:function(e,t,n){var r=i(e);for(var o in r)if(r.hasOwnProperty(o)){var u=r[o],a=s(u,null);r[o]=a}return r},updateChildren:function(e,t,n,u){var f=i(t);if(!f&&!e)return null;var l;for(l in f)if(f.hasOwnProperty(l)){var c=e&&e[l],h=c&&c._currentElement,p=f[l];if(o(h,p))r.receiveComponent(c,p,n,u),f[l]=c;else{c&&r.unmountComponent(c,l);var d=s(p,null);f[l]=d}}for(l in e)!e.hasOwnProperty(l)||f&&f.hasOwnProperty(l)||r.unmountComponent(e[l]);return f},unmountChildren:function(e){for(var t in e){var n=e[t];r.unmountComponent(n)}}};t.exports=u},{116:116,132:132,147:147,79:79}],32:[function(e,t,n){"use strict";function r(e,t){this.forEachFunction=e,this.forEachContext=t}function i(e,t,n,r){var i=e;i.forEachFunction.call(i.forEachContext,t,r)}function s(e,t,n){if(null==e)return e;var s=r.getPooled(t,n);p(e,i,s),r.release(s)}function o(e,t,n){this.mapResult=e,this.mapFunction=t,this.mapContext=n}function u(e,t,n,r){var i=e,s=i.mapResult,o=!s.hasOwnProperty(n);if(o){var u=i.mapFunction.call(i.mapContext,t,r);s[n]=u}}function a(e,t,n){if(null==e)return e;var r={},i=o.getPooled(r,t,n);return p(e,u,i),o.release(i),h.create(r)}function f(e,t,n,r){return null}function l(e,t){return p(e,f,null)}var c=e(28),h=e(61),p=e(149),d=(e(150),c.twoArgumentPooler),v=c.threeArgumentPooler;c.addPoolingTo(r,d),c.addPoolingTo(o,v);var m={forEach:s,map:a,count:l};t.exports=m},{149:149,150:150,28:28,61:61}],33:[function(e,t,n){"use strict";function r(e,t){var n=T.hasOwnProperty(t)?T[t]:null;C.hasOwnProperty(t)&&y(n===S.OVERRIDE_BASE),e.hasOwnProperty(t)&&y(n===S.DEFINE_MANY||n===S.DEFINE_MANY_MERGED)}function i(e,t){if(t){y("function"!=typeof t),y(!h.isValidElement(t));var n=e.prototype;t.hasOwnProperty(E)&&N.mixins(e,t.mixins);for(var i in t)if(t.hasOwnProperty(i)&&i!==E){var s=t[i];if(r(n,i),N.hasOwnProperty(i))N[i](e,s);else{var o=T.hasOwnProperty(i),f=n.hasOwnProperty(i),l=s&&s.__reactDontBind,c="function"==typeof s,p=c&&!o&&!f&&!l;if(p)n.__reactAutoBindMap||(n.__reactAutoBindMap={}),n.__reactAutoBindMap[i]=s,n[i]=s;else if(f){var d=T[i];y(o&&(d===S.DEFINE_MANY_MERGED||d===S.DEFINE_MANY)),d===S.DEFINE_MANY_MERGED?n[i]=u(n[i],s):d===S.DEFINE_MANY&&(n[i]=a(n[i],s))}else n[i]=s}}}}function s(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var i=n in N;y(!i);var s=n in e;y(!s),e[n]=r}}}function o(e,t){y(e&&t&&"object"==typeof e&&"object"==typeof t);for(var n in t)t.hasOwnProperty(n)&&(y(void 0===e[n]),e[n]=t[n]);return e}function u(e,t){return function(){var n=e.apply(this,arguments),r=t.apply(this,arguments);if(null==n)return r;if(null==r)return n;var i={};return o(i,n),o(i,r),i}}function a(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function f(e,t){var n=t.bind(e);return n}function l(e){for(var t in e.__reactAutoBindMap)if(e.__reactAutoBindMap.hasOwnProperty(t)){var n=e.__reactAutoBindMap[t];e[t]=f(e,p.guard(n,e.constructor.displayName+"."+t))}}var c=e(34),h=(e(39),e(55)),p=e(58),d=e(65),v=e(66),m=(e(75),e(74),e(84)),g=e(27),y=e(133),b=e(138),w=e(139),E=(e(150),w({mixins:null})),S=b({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null}),x=[],T={mixins:S.DEFINE_MANY,statics:S.DEFINE_MANY,propTypes:S.DEFINE_MANY,contextTypes:S.DEFINE_MANY,childContextTypes:S.DEFINE_MANY,getDefaultProps:S.DEFINE_MANY_MERGED,getInitialState:S.DEFINE_MANY_MERGED,getChildContext:S.DEFINE_MANY_MERGED,render:S.DEFINE_ONCE,componentWillMount:S.DEFINE_MANY,componentDidMount:S.DEFINE_MANY,componentWillReceiveProps:S.DEFINE_MANY,shouldComponentUpdate:S.DEFINE_ONCE,componentWillUpdate:S.DEFINE_MANY,componentDidUpdate:S.DEFINE_MANY,componentWillUnmount:S.DEFINE_MANY,updateComponent:S.OVERRIDE_BASE},N={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)i(e,t[n])},childContextTypes:function(e,t){e.childContextTypes=g({},e.childContextTypes,t)},contextTypes:function(e,t){e.contextTypes=g({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps?e.getDefaultProps=u(e.getDefaultProps,t):e.getDefaultProps=t},propTypes:function(e,t){e.propTypes=g({},e.propTypes,t)},statics:function(e,t){s(e,t)}},C={replaceState:function(e,t){m.enqueueReplaceState(this,e),t&&m.enqueueCallback(this,t)},isMounted:function(){var e=d.get(this);return e&&e!==v.currentlyMountingInstance},setProps:function(e,t){m.enqueueSetProps(this,e),t&&m.enqueueCallback(this,t)},replaceProps:function(e,t){m.enqueueReplaceProps(this,e),t&&m.enqueueCallback(this,t)}},k=function(){};g(k.prototype,c.prototype,C);var L={createClass:function(e){var t=function(e,t){this.__reactAutoBindMap&&l(this),this.props=e,this.context=t,this.state=null;var n=this.getInitialState?this.getInitialState():null;y("object"==typeof n&&!Array.isArray(n)),this.state=n};t.prototype=new k,t.prototype.constructor=t,x.forEach(i.bind(null,t)),i(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),y(t.prototype.render);for(var n in T)t.prototype[n]||(t.prototype[n]=null);return t.type=t,t},injection:{injectMixin:function(e){x.push(e)}}};t.exports=L},{133:133,138:138,139:139,150:150,27:27,34:34,39:39,55:55,58:58,65:65,66:66,74:74,75:75,84:84}],34:[function(e,t,n){"use strict";function r(e,t){this.props=e,this.context=t}var i=e(84),s=e(133);e(150),r.prototype.setState=function(e,t){s("object"==typeof e||"function"==typeof e||null==e),i.enqueueSetState(this,e),t&&i.enqueueCallback(this,t)},r.prototype.forceUpdate=function(e){i.enqueueForceUpdate(this),e&&i.enqueueCallback(this,e)},t.exports=r},{133:133,150:150,84:84}],35:[function(e,t,n){"use strict";var r=e(44),i=e(68),s={processChildrenUpdates:r.dangerouslyProcessChildrenUpdates,replaceNodeWithMarkupByID:r.dangerouslyReplaceNodeWithMarkupByID,unmountIDFromEnvironment:function(e){i.purgeID(e)}};t.exports=s},{44:44,68:68}],36:[function(e,t,n){"use strict";var r=e(133),i=!1,s={unmountIDFromEnvironment:null,replaceNodeWithMarkupByID:null,processChildrenUpdates:null,injection:{injectEnvironment:function(e){r(!i),s.unmountIDFromEnvironment=e.unmountIDFromEnvironment,s.replaceNodeWithMarkupByID=e.replaceNodeWithMarkupByID,s.processChildrenUpdates=e.processChildrenUpdates,i=!0}}};t.exports=s},{133:133}],37:[function(e,t,n){"use strict";function r(e){var t=e._currentElement._owner||null;if(t){var n=t.getName();if(n)return" Check the render method of `"+n+"`."}return""}var i=e(36),s=e(38),o=e(39),u=e(55),a=(e(56),e(65)),f=e(66),l=e(71),c=e(73),h=e(75),p=(e(74),e(79)),d=e(85),v=e(27),m=e(113),g=e(133),y=e(147),b=(e(150),1),w={construct:function(e){this._currentElement=e,this._rootNodeID=null,this._instance=null,this._pendingElement=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._renderedComponent=null,this._context=null,this._mountOrder=0,this._isTopLevel=!1,this._pendingCallbacks=null},mountComponent:function(e,t,n){this._context=n,this._mountOrder=b++,this._rootNodeID=e;var r=this._processProps(this._currentElement.props),i=this._processContext(this._currentElement._context),s=l.getComponentClassForElement(this._currentElement),o=new s(r,i);o.props=r,o.context=i,o.refs=m,this._instance=o,a.set(o,this);var u=o.state;void 0===u&&(o.state=u=null),g("object"==typeof u&&!Array.isArray(u)),this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1;var c,h,d=f.currentlyMountingInstance;f.currentlyMountingInstance=this;try{o.componentWillMount&&(o.componentWillMount(),this._pendingStateQueue&&(o.state=this._processPendingState(o.props,o.context))),c=this._getValidatedChildContext(n),h=this._renderValidatedComponent(c)}finally{f.currentlyMountingInstance=d}this._renderedComponent=this._instantiateReactComponent(h,this._currentElement.type);var v=p.mountComponent(this._renderedComponent,e,t,this._mergeChildContext(n,c));return o.componentDidMount&&t.getReactMountReady().enqueue(o.componentDidMount,o),v},unmountComponent:function(){var e=this._instance;if(e.componentWillUnmount){var t=f.currentlyUnmountingInstance;f.currentlyUnmountingInstance=this;try{e.componentWillUnmount()}finally{f.currentlyUnmountingInstance=t}}p.unmountComponent(this._renderedComponent),this._renderedComponent=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._pendingCallbacks=null,this._pendingElement=null,this._context=null,this._rootNodeID=null,a.remove(e)},_setPropsInternal:function(e,t){var n=this._pendingElement||this._currentElement;this._pendingElement=u.cloneAndReplaceProps(n,v({},n.props,e)),d.enqueueUpdate(this,t)},_maskContext:function(e){var t=null;if("string"==typeof this._currentElement.type)return m;var n=this._currentElement.type.contextTypes;if(!n)return m;t={};for(var r in n)t[r]=e[r];return t},_processContext:function(e){var t=this._maskContext(e);return t},_getValidatedChildContext:function(e){var t=this._instance,n=t.getChildContext&&t.getChildContext();if(n){g("object"==typeof t.constructor.childContextTypes);for(var r in n)g(r in t.constructor.childContextTypes);return n}return null},_mergeChildContext:function(e,t){return t?v({},e,t):e},_processProps:function(e){return e},_checkPropTypes:function(e,t,n){var i=this.getName();for(var s in e)if(e.hasOwnProperty(s)){var o;try{g("function"==typeof e[s]),o=e[s](t,s,i,n)}catch(u){o=u}o instanceof Error&&(r(this),n===h.prop)}},receiveComponent:function(e,t,n){var r=this._currentElement,i=this._context;this._pendingElement=null,this.updateComponent(t,r,e,i,n)},performUpdateIfNecessary:function(e){null!=this._pendingElement&&p.receiveComponent(this,this._pendingElement||this._currentElement,e,this._context),(null!==this._pendingStateQueue||this._pendingForceUpdate)&&this.updateComponent(e,this._currentElement,this._currentElement,this._context,this._context)},_warnIfContextsDiffer:function(e,t){e=this._maskContext(e),t=this._maskContext(t);for(var n=Object.keys(t).sort(),r=(this.getName()||"ReactCompositeComponent",0);r<n.length;r++)n[r]},updateComponent:function(e,t,n,r,i){var s=this._instance,o=s.context,u=s.props;t!==n&&(o=this._processContext(n._context),u=this._processProps(n.props),s.componentWillReceiveProps&&s.componentWillReceiveProps(u,o));var a=this._processPendingState(u,o),f=this._pendingForceUpdate||!s.shouldComponentUpdate||s.shouldComponentUpdate(u,a,o);f?(this._pendingForceUpdate=!1,this._performComponentUpdate(n,u,a,o,e,i)):(this._currentElement=n,this._context=i,s.props=u,s.state=a,s.context=o)},_processPendingState:function(e,t){var n=this._instance,r=this._pendingStateQueue,i=this._pendingReplaceState;if(this._pendingReplaceState=!1,this._pendingStateQueue=null,!r)return n.state;if(i&&1===r.length)return r[0];for(var s=v({},i?r[0]:n.state),o=i?1:0;o<r.length;o++){var u=r[o];v(s,"function"==typeof u?u.call(n,s,e,t):u)}return s},_performComponentUpdate:function(e,t,n,r,i,s){var o=this._instance,u=o.props,a=o.state,f=o.context;o.componentWillUpdate&&o.componentWillUpdate(t,n,r),this._currentElement=e,this._context=s,o.props=t,o.state=n,o.context=r,this._updateRenderedComponent(i,s),o.componentDidUpdate&&i.getReactMountReady().enqueue(o.componentDidUpdate.bind(o,u,a,f),o)},_updateRenderedComponent:function(e,t){var n=this._renderedComponent,r=n._currentElement,i=this._getValidatedChildContext(),s=this._renderValidatedComponent(i);if(y(r,s))p.receiveComponent(n,s,e,this._mergeChildContext(t,i));else{var o=this._rootNodeID,u=n._rootNodeID;p.unmountComponent(n),this._renderedComponent=this._instantiateReactComponent(s,this._currentElement.type);var a=p.mountComponent(this._renderedComponent,o,e,this._mergeChildContext(t,i));this._replaceNodeWithMarkupByID(u,a)}},_replaceNodeWithMarkupByID:function(e,t){i.replaceNodeWithMarkupByID(e,t)},_renderValidatedComponentWithoutOwnerOrContext:function(){var e=this._instance,t=e.render();return t},_renderValidatedComponent:function(e){var t,n=s.current;s.current=this._mergeChildContext(this._currentElement._context,e),o.current=this;try{t=this._renderValidatedComponentWithoutOwnerOrContext()}finally{s.current=n,o.current=null}return g(null===t||t===!1||u.isValidElement(t)),t},attachRef:function(e,t){var n=this.getPublicInstance(),r=n.refs===m?n.refs={}:n.refs;r[e]=t.getPublicInstance()},detachRef:function(e){var t=this.getPublicInstance().refs;delete t[e]},getName:function(){var e=this._currentElement.type,t=this._instance&&this._instance.constructor;return e.displayName||t&&t.displayName||e.name||t&&t.name||null},getPublicInstance:function(){return this._instance},_instantiateReactComponent:null};c.measureMethods(w,"ReactCompositeComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent",_renderValidatedComponent:"_renderValidatedComponent"});var E={Mixin:w};t.exports=E},{113:113,133:133,147:147,150:150,27:27,36:36,38:38,39:39,55:55,56:56,65:65,66:66,71:71,73:73,74:74,75:75,79:79,85:85}],38:[function(e,t,n){"use strict";var r=e(27),i=e(113),s=(e(150),{current:i,withContext:function(e,t){var n,i=s.current;s.current=r({},i,e);try{n=t()}finally{s.current=i}return n}});t.exports=s},{113:113,150:150,27:27}],39:[function(e,t,n){"use strict";var r={current:null};t.exports=r},{}],40:[function(e,t,n){"use strict";function r(e){return i.createFactory(e)}var i=e(55),s=(e(56),e(140)),o=s({a:"a",abbr:"abbr",address:"address",area:"area",article:"article",aside:"aside",audio:"audio",b:"b",base:"base",bdi:"bdi",bdo:"bdo",big:"big",blockquote:"blockquote",body:"body",br:"br",button:"button",canvas:"canvas",caption:"caption",cite:"cite",code:"code",col:"col",colgroup:"colgroup",data:"data",datalist:"datalist",dd:"dd",del:"del",details:"details",dfn:"dfn",dialog:"dialog",div:"div",dl:"dl",dt:"dt",em:"em",embed:"embed",fieldset:"fieldset",figcaption:"figcaption",figure:"figure",footer:"footer",form:"form",h1:"h1",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",head:"head",header:"header",hr:"hr",html:"html",i:"i",iframe:"iframe",img:"img",input:"input",ins:"ins",kbd:"kbd",keygen:"keygen",label:"label",legend:"legend",li:"li",link:"link",main:"main",map:"map",mark:"mark",menu:"menu",menuitem:"menuitem",meta:"meta",meter:"meter",nav:"nav",noscript:"noscript",object:"object",ol:"ol",optgroup:"optgroup",option:"option",output:"output",p:"p",param:"param",picture:"picture",pre:"pre",progress:"progress",q:"q",rp:"rp",rt:"rt",ruby:"ruby",s:"s",samp:"samp",script:"script",section:"section",select:"select",small:"small",source:"source",span:"span",strong:"strong",style:"style",sub:"sub",summary:"summary",sup:"sup",table:"table",tbody:"tbody",td:"td",textarea:"textarea",tfoot:"tfoot",th:"th",thead:"thead",time:"time",title:"title",tr:"tr",track:"track",u:"u",ul:"ul","var":"var",video:"video",wbr:"wbr",circle:"circle",clipPath:"clipPath",defs:"defs",ellipse:"ellipse",g:"g",line:"line",linearGradient:"linearGradient",mask:"mask",path:"path",pattern:"pattern",polygon:"polygon",polyline:"polyline",radialGradient:"radialGradient",rect:"rect",stop:"stop",svg:"svg",text:"text",tspan:"tspan"},r);t.exports=o},{140:140,55:55,56:56}],41:[function(e,t,n){"use strict";var r=e(2),i=e(29),s=e(33),o=e(55),u=e(138),a=o.createFactory("button"),f=u({onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0}),l=s.createClass({displayName:"ReactDOMButton",tagName:"BUTTON",mixins:[r,i],render:function(){var e={};for(var t in this.props)!this.props.hasOwnProperty(t)||this.props.disabled&&f[t]||(e[t]=this.props[t]);return a(e,this.props.children)}});t.exports=l},{138:138,2:2,29:29,33:33,55:55}],42:[function(e,t,n){"use strict";function r(e){e&&(null!=e.dangerouslySetInnerHTML&&(g(null==e.children),g("object"==typeof e.dangerouslySetInnerHTML&&"__html"in e.dangerouslySetInnerHTML)),g(null==e.style||"object"==typeof e.style))}function i(e,t,n,r){var i=h.findReactContainerForID(e);if(i){var s=i.nodeType===T?i.ownerDocument:i;w(t,s)}r.getPutListenerQueue().enqueuePutListener(e,t,n)}function s(e){A.call(L,e)||(g(k.test(e)),L[e]=!0)}function o(e){s(e),this._tag=e,this._renderedChildren=null,this._previousStyleCopy=null,this._rootNodeID=null}var u=e(5),a=e(10),f=e(11),l=e(30),c=e(35),h=e(68),p=e(69),d=e(73),v=e(27),m=e(114),g=e(133),y=(e(134),e(139)),b=(e(150),l.deleteListener),w=l.listenTo,E=l.registrationNameModules,S={string:!0,number:!0},x=y({style:null}),T=1,N=null,C={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},k=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,L={},A={}.hasOwnProperty;o.displayName="ReactDOMComponent",o.Mixin={construct:function(e){this._currentElement=e},mountComponent:function(e,t,n){this._rootNodeID=e,r(this._currentElement.props);var i=C[this._tag]?"":"</"+this._tag+">";return this._createOpenTagMarkupAndPutListeners(t)+this._createContentMarkup(t,n)+i},_createOpenTagMarkupAndPutListeners:function(e){var t=this._currentElement.props,n="<"+this._tag;for(var r in t)if(t.hasOwnProperty(r)){var s=t[r];if(null!=s)if(E.hasOwnProperty(r))i(this._rootNodeID,r,s,e);else{r===x&&(s&&(s=this._previousStyleCopy=v({},t.style)),s=u.createMarkupForStyles(s));var o=f.createMarkupForProperty(r,s);o&&(n+=" "+o)}}if(e.renderToStaticMarkup)return n+">";var a=f.createMarkupForID(this._rootNodeID);return n+" "+a+">"},_createContentMarkup:function(e,t){var n="";("listing"===this._tag||"pre"===this._tag||"textarea"===this._tag)&&(n="\n");var r=this._currentElement.props,i=r.dangerouslySetInnerHTML;if(null!=i){if(null!=i.__html)return n+i.__html}else{var s=S[typeof r.children]?r.children:null,o=null!=s?null:r.children;if(null!=s)return n+m(s);if(null!=o){var u=this.mountChildren(o,e,t);return n+u.join("")}}return n},receiveComponent:function(e,t,n){var r=this._currentElement;this._currentElement=e,this.updateComponent(t,r,e,n)},updateComponent:function(e,t,n,i){r(this._currentElement.props),this._updateDOMProperties(t.props,e),this._updateDOMChildren(t.props,e,i)},_updateDOMProperties:function(e,t){var n,r,s,o=this._currentElement.props;for(n in e)if(!o.hasOwnProperty(n)&&e.hasOwnProperty(n))if(n===x){var u=this._previousStyleCopy;for(r in u)u.hasOwnProperty(r)&&(s=s||{},s[r]="");this._previousStyleCopy=null}else E.hasOwnProperty(n)?b(this._rootNodeID,n):(a.isStandardName[n]||a.isCustomAttribute(n))&&N.deletePropertyByID(this._rootNodeID,n);for(n in o){var f=o[n],l=n===x?this._previousStyleCopy:e[n];if(o.hasOwnProperty(n)&&f!==l)if(n===x)if(f?f=this._previousStyleCopy=v({},f):this._previousStyleCopy=null,l){for(r in l)!l.hasOwnProperty(r)||f&&f.hasOwnProperty(r)||(s=s||{},s[r]="");for(r in f)f.hasOwnProperty(r)&&l[r]!==f[r]&&(s=s||{},s[r]=f[r])}else s=f;else E.hasOwnProperty(n)?i(this._rootNodeID,n,f,t):(a.isStandardName[n]||a.isCustomAttribute(n))&&N.updatePropertyByID(this._rootNodeID,n,f)}s&&N.updateStylesByID(this._rootNodeID,s)},_updateDOMChildren:function(e,t,n){var r=this._currentElement.props,i=S[typeof e.children]?e.children:null,s=S[typeof r.children]?r.children:null,o=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,u=r.dangerouslySetInnerHTML&&r.dangerouslySetInnerHTML.__html,a=null!=i?null:e.children,f=null!=s?null:r.children,l=null!=i||null!=o,c=null!=s||null!=u;null!=a&&null==f?this.updateChildren(null,t,n):l&&!c&&this.updateTextContent(""),null!=s?i!==s&&this.updateTextContent(""+s):null!=u?o!==u&&N.updateInnerHTMLByID(this._rootNodeID,u):null!=f&&this.updateChildren(f,t,n)},unmountComponent:function(){this.unmountChildren(),l.deleteAllListeners(this._rootNodeID),c.unmountIDFromEnvironment(this._rootNodeID),this._rootNodeID=null}},d.measureMethods(o,"ReactDOMComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent"}),v(o.prototype,o.Mixin,p.Mixin),o.injection={injectIDOperations:function(e){o.BackendIDOperations=N=e}},t.exports=o},{10:10,11:11,114:114,133:133,134:134,139:139,150:150,27:27,30:30,35:35,5:5,68:68,69:69,73:73}],43:[function(e,t,n){"use strict";var r=e(15),i=e(25),s=e(29),o=e(33),u=e(55),a=u.createFactory("form"),f=o.createClass({displayName:"ReactDOMForm",tagName:"FORM",mixins:[s,i],render:function(){return a(this.props)},componentDidMount:function(){this.trapBubbledEvent(r.topLevelTypes.topReset,"reset"),this.trapBubbledEvent(r.topLevelTypes.topSubmit,"submit")}});t.exports=f},{15:15,25:25,29:29,33:33,55:55}],44:[function(e,t,n){"use strict";var r=e(5),i=e(9),s=e(11),o=e(68),u=e(73),a=e(133),f=e(144),l={dangerouslySetInnerHTML:"`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.",style:"`style` must be set using `updateStylesByID()`."},c={updatePropertyByID:function(e,t,n){var r=o.getNode(e);a(!l.hasOwnProperty(t)),null!=n?s.setValueForProperty(r,t,n):s.deleteValueForProperty(r,t)},deletePropertyByID:function(e,t,n){var r=o.getNode(e);a(!l.hasOwnProperty(t)),s.deleteValueForProperty(r,t,n)},updateStylesByID:function(e,t){var n=o.getNode(e);r.setValueForStyles(n,t)},updateInnerHTMLByID:function(e,t){var n=o.getNode(e);f(n,t)},updateTextContentByID:function(e,t){var n=o.getNode(e);i.updateTextContent(n,t)},dangerouslyReplaceNodeWithMarkupByID:function(e,t){var n=o.getNode(e);i.dangerouslyReplaceNodeWithMarkup(n,t)},dangerouslyProcessChildrenUpdates:function(e,t){for(var n=0;n<e.length;n++)e[n].parentNode=o.getNode(e[n].parentID);i.processUpdates(e,t)}};u.measureMethods(c,"ReactDOMIDOperations",{updatePropertyByID:"updatePropertyByID",deletePropertyByID:"deletePropertyByID",updateStylesByID:"updateStylesByID",updateInnerHTMLByID:"updateInnerHTMLByID",updateTextContentByID:"updateTextContentByID",dangerouslyReplaceNodeWithMarkupByID:"dangerouslyReplaceNodeWithMarkupByID",dangerouslyProcessChildrenUpdates:"dangerouslyProcessChildrenUpdates"}),t.exports=c},{11:11,133:133,144:144,5:5,68:68,73:73,9:9}],45:[function(e,t,n){"use strict";var r=e(15),i=e(25),s=e(29),o=e(33),u=e(55),a=u.createFactory("iframe"),f=o.createClass({displayName:"ReactDOMIframe",tagName:"IFRAME",mixins:[s,i],render:function(){return a(this.props)},componentDidMount:function(){this.trapBubbledEvent(r.topLevelTypes.topLoad,"load")}});t.exports=f},{15:15,25:25,29:29,33:33,55:55}],46:[function(e,t,n){"use strict";var r=e(15),i=e(25),s=e(29),o=e(33),u=e(55),a=u.createFactory("img"),f=o.createClass({displayName:"ReactDOMImg",tagName:"IMG",mixins:[s,i],render:function(){return a(this.props)},componentDidMount:function(){this.trapBubbledEvent(r.topLevelTypes.topLoad,"load"),this.trapBubbledEvent(r.topLevelTypes.topError,"error")}});t.exports=f},{15:15,25:25,29:29,33:33,55:55}],47:[function(e,t,n){"use strict";function r(){this.isMounted()&&this.forceUpdate()}var i=e(2),s=e(11),o=e(24),u=e(29),a=e(33),f=e(55),l=e(68),c=e(85),h=e(27),p=e(133),d=f.createFactory("input"),v={},m=a.createClass({displayName:"ReactDOMInput",tagName:"INPUT",mixins:[i,o.Mixin,u],getInitialState:function(){var e=this.props.defaultValue;return{initialChecked:this.props.defaultChecked||!1,initialValue:null!=e?e:null}},render:function(){var e=h({},this.props);e.defaultChecked=null,e.defaultValue=null;var t=o.getValue(this);e.value=null!=t?t:this.state.initialValue;var n=o.getChecked(this);return e.checked=null!=n?n:this.state.initialChecked,e.onChange=this._handleChange,d(e,this.props.children)},componentDidMount:function(){var e=l.getID(this.getDOMNode());v[e]=this},componentWillUnmount:function(){var e=this.getDOMNode(),t=l.getID(e);delete v[t]},componentDidUpdate:function(e,t,n){var r=this.getDOMNode();null!=this.props.checked&&s.setValueForProperty(r,"checked",this.props.checked||!1);var i=o.getValue(this);null!=i&&s.setValueForProperty(r,"value",""+i)},_handleChange:function(e){var t,n=o.getOnChange(this);n&&(t=n.call(this,e)),c.asap(r,this);var i=this.props.name;if("radio"===this.props.type&&null!=i){for(var s=this.getDOMNode(),u=s;u.parentNode;)u=u.parentNode;for(var a=u.querySelectorAll("input[name="+JSON.stringify(""+i)+'][type="radio"]'),f=0,h=a.length;h>f;f++){var d=a[f];if(d!==s&&d.form===s.form){var m=l.getID(d);p(m);var g=v[m];p(g),c.asap(r,g)}}}return t}});t.exports=m},{11:11,133:133,2:2,24:24,27:27,29:29,33:33,55:55,68:68,85:85}],48:[function(e,t,n){"use strict";var r=e(29),i=e(33),s=e(55),o=(e(150),s.createFactory("option")),u=i.createClass({displayName:"ReactDOMOption",tagName:"OPTION",mixins:[r],componentWillMount:function(){},render:function(){return o(this.props,this.props.children)}});t.exports=u},{150:150,29:29,33:33,55:55}],49:[function(e,t,n){"use strict";function r(){if(this._pendingUpdate){this._pendingUpdate=!1;var e=u.getValue(this);null!=e&&this.isMounted()&&s(this,e)}}function i(e,t,n){if(null==e[t])return null;if(e.multiple){if(!Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be an array if `multiple` is true.")}else if(Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be a scalar value if `multiple` is false.")}function s(e,t){var n,r,i,s=e.getDOMNode().options;if(e.props.multiple){for(n={},r=0,i=t.length;i>r;r++)n[""+t[r]]=!0;for(r=0,i=s.length;i>r;r++){var o=n.hasOwnProperty(s[r].value);s[r].selected!==o&&(s[r].selected=o)}}else{for(n=""+t,r=0,i=s.length;i>r;r++)if(s[r].value===n)return void (s[r].selected=!0);s.length&&(s[0].selected=!0)}}var o=e(2),u=e(24),a=e(29),f=e(33),l=e(55),c=e(85),h=e(27),p=l.createFactory("select"),d=f.createClass({displayName:"ReactDOMSelect",tagName:"SELECT",mixins:[o,u.Mixin,a],propTypes:{defaultValue:i,value:i},render:function(){var e=h({},this.props);return e.onChange=this._handleChange,e.value=null,p(e,this.props.children)},componentWillMount:function(){this._pendingUpdate=!1},componentDidMount:function(){var e=u.getValue(this);null!=e?s(this,e):null!=this.props.defaultValue&&s(this,this.props.defaultValue)},componentDidUpdate:function(e){var t=u.getValue(this);null!=t?(this._pendingUpdate=!1,s(this,t)):!e.multiple!=!this.props.multiple&&(null!=this.props.defaultValue?s(this,this.props.defaultValue):s(this,this.props.multiple?[]:""))},_handleChange:function(e){var t,n=u.getOnChange(this);return n&&(t=n.call(this,e)),this._pendingUpdate=!0,c.asap(r,this),t}});t.exports=d},{2:2,24:24,27:27,29:29,33:33,55:55,85:85}],50:[function(e,t,n){"use strict";function r(e,t,n,r){return e===n&&t===r}function i(e){var t=document.selection,n=t.createRange(),r=n.text.length,i=n.duplicate();i.moveToElementText(e),i.setEndPoint("EndToStart",n);var s=i.text.length,o=s+r;return{start:s,end:o}}function s(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var n=t.anchorNode,i=t.anchorOffset,s=t.focusNode,o=t.focusOffset,u=t.getRangeAt(0),a=r(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),f=a?0:u.toString().length,l=u.cloneRange();l.selectNodeContents(e),l.setEnd(u.startContainer,u.startOffset);var c=r(l.startContainer,l.startOffset,l.endContainer,l.endOffset),h=c?0:l.toString().length,p=h+f,d=document.createRange();d.setStart(n,i),d.setEnd(s,o);var v=d.collapsed;return{start:v?p:h,end:v?h:p}}function o(e,t){var n,r,i=document.selection.createRange().duplicate();"undefined"==typeof t.end?(n=t.start,r=n):t.start>t.end?(n=t.end,r=t.start):(n=t.start,r=t.end),i.moveToElementText(e),i.moveStart("character",n),i.setEndPoint("EndToStart",i),i.moveEnd("character",r-n),i.select()}function u(e,t){if(window.getSelection){var n=window.getSelection(),r=e[l()].length,i=Math.min(t.start,r),s="undefined"==typeof t.end?i:Math.min(t.end,r);if(!n.extend&&i>s){var o=s;s=i,i=o}var u=f(e,i),a=f(e,s);if(u&&a){var c=document.createRange();c.setStart(u.node,u.offset),n.removeAllRanges(),i>s?(n.addRange(c),n.extend(a.node,a.offset)):(c.setEnd(a.node,a.offset),n.addRange(c))}}}var a=e(21),f=e(126),l=e(128),c=a.canUseDOM&&"selection"in document&&!("getSelection"in window),h={getOffsets:c?i:s,setOffsets:c?o:u};t.exports=h},{126:126,128:128,21:21}],51:[function(e,t,n){"use strict";var r=e(11),i=e(35),s=e(42),o=e(27),u=e(114),a=function(e){};o(a.prototype,{construct:function(e){this._currentElement=e,this._stringText=""+e,this._rootNodeID=null,this._mountIndex=0},mountComponent:function(e,t,n){this._rootNodeID=e;var i=u(this._stringText);return t.renderToStaticMarkup?i:"<span "+r.createMarkupForID(e)+">"+i+"</span>"},receiveComponent:function(e,t){if(e!==this._currentElement){this._currentElement=e;var n=""+e;n!==this._stringText&&(this._stringText=n,s.BackendIDOperations.updateTextContentByID(this._rootNodeID,n))}},unmountComponent:function(){i.unmountIDFromEnvironment(this._rootNodeID)}}),t.exports=a},{11:11,114:114,27:27,35:35,42:42}],52:[function(e,t,n){"use strict";function r(){this.isMounted()&&this.forceUpdate()}var i=e(2),s=e(11),o=e(24),u=e(29),a=e(33),f=e(55),l=e(85),c=e(27),h=e(133),p=(e(150),f.createFactory("textarea")),d=a.createClass({displayName:"ReactDOMTextarea",tagName:"TEXTAREA",mixins:[i,o.Mixin,u],getInitialState:function(){var e=this.props.defaultValue,t=this.props.children;null!=t&&(h(null==e),Array.isArray(t)&&(h(t.length<=1),t=t[0]),e=""+t),null==e&&(e="");var n=o.getValue(this);return{initialValue:""+(null!=n?n:e)}},render:function(){var e=c({},this.props);return h(null==e.dangerouslySetInnerHTML),e.defaultValue=null,e.value=null,e.onChange=this._handleChange,p(e,this.state.initialValue)},componentDidUpdate:function(e,t,n){var r=o.getValue(this);if(null!=r){var i=this.getDOMNode();s.setValueForProperty(i,"value",""+r)}},_handleChange:function(e){var t,n=o.getOnChange(this);return n&&(t=n.call(this,e)),l.asap(r,this),t}});t.exports=d},{11:11,133:133,150:150,2:2,24:24,27:27,29:29,33:33,55:55,85:85}],53:[function(e,t,n){"use strict";function r(){this.reinitializeTransaction()}var i=e(85),s=e(101),o=e(27),u=e(112),a={initialize:u,close:function(){h.isBatchingUpdates=!1}},f={initialize:u,close:i.flushBatchedUpdates.bind(i)},l=[f,a];o(r.prototype,s.Mixin,{getTransactionWrappers:function(){return l}});var c=new r,h={isBatchingUpdates:!1,batchedUpdates:function(e,t,n,r,i){var s=h.isBatchingUpdates;h.isBatchingUpdates=!0,s?e(t,n,r,i):c.perform(e,null,t,n,r,i)}};t.exports=h},{101:101,112:112,27:27,85:85}],54:[function(e,t,n){"use strict";function r(e){return d.createClass({tagName:e.toUpperCase(),render:function(){return new L(e,null,null,null,null,this.props)}})}function i(){O.EventEmitter.injectReactEventListener(A),O.EventPluginHub.injectEventPluginOrder(a),O.EventPluginHub.injectInstanceHandle(M),O.EventPluginHub.injectMount(_),O.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:B,EnterLeaveEventPlugin:f,ChangeEventPlugin:o,MobileSafariClickEventPlugin:h,SelectEventPlugin:P,BeforeInputEventPlugin:s}),O.NativeComponent.injectGenericComponentClass(g),O.NativeComponent.injectTextComponentClass(k),O.NativeComponent.injectAutoWrapper(r),O.Class.injectMixin(p),O.NativeComponent.injectComponentClasses({button:y,form:b,iframe:S,img:w,input:x,option:T,select:N,textarea:C,html:F("html"),head:F("head"),body:F("body")}),O.DOMProperty.injectDOMPropertyConfig(c),O.DOMProperty.injectDOMPropertyConfig(j),O.EmptyComponent.injectEmptyComponent("noscript"),O.Updates.injectReconcileTransaction(D),O.Updates.injectBatchingStrategy(m),O.RootIndex.injectCreateReactRootIndex(l.canUseDOM?u.createReactRootIndex:H.createReactRootIndex),O.Component.injectEnvironment(v),O.DOMComponent.injectIDOperations(E)}var s=e(3),o=e(7),u=e(8),a=e(13),f=e(14),l=e(21),c=e(23),h=e(26),p=e(29),d=e(33),v=e(35),m=e(53),g=e(42),y=e(41),b=e(43),w=e(46),E=e(44),S=e(45),x=e(47),T=e(48),N=e(49),C=e(52),k=e(51),L=e(55),A=e(60),O=e(62),M=e(64),_=e(68),D=e(78),P=e(87),H=e(88),B=e(89),j=e(86),F=e(109);t.exports={inject:i}},{109:109,13:13,14:14,21:21,23:23,26:26,29:29,3:3,33:33,35:35,41:41,42:42,43:43,44:44,45:45,46:46,47:47,48:48,49:49,51:51,52:52,53:53,55:55,60:60,62:62,64:64,68:68,7:7,78:78,8:8,86:86,87:87,88:88,89:89}],55:[function(e,t,n){"use strict";var r=e(38),i=e(39),s=e(27),o=(e(150),{key:!0,ref:!0}),u=function(e,t,n,r,i,s){this.type=e,this.key=t,this.ref=n,this._owner=r,this._context=i,this.props=s};u.prototype={_isReactElement:!0},u.createElement=function(e,t,n){var s,f={},l=null,c=null;if(null!=t){c=void 0===t.ref?null:t.ref,l=void 0===t.key?null:""+t.key;for(s in t)t.hasOwnProperty(s)&&!o.hasOwnProperty(s)&&(f[s]=t[s])}var h=arguments.length-2;if(1===h)f.children=n;else if(h>1){for(var p=Array(h),d=0;h>d;d++)p[d]=arguments[d+2];f.children=p}if(e&&e.defaultProps){var v=e.defaultProps;for(s in v)"undefined"==typeof f[s]&&(f[s]=v[s])}return new u(e,l,c,i.current,r.current,f)},u.createFactory=function(e){var t=u.createElement.bind(null,e);return t.type=e,t},u.cloneAndReplaceProps=function(e,t){var n=new u(e.type,e.key,e.ref,e._owner,e._context,t);return n},u.cloneElement=function(e,t,n){var r,f=s({},e.props),l=e.key,c=e.ref,h=e._owner;if(null!=t){void 0!==t.ref&&(c=t.ref,h=i.current),void 0!==t.key&&(l=""+t.key);for(r in t)t.hasOwnProperty(r)&&!o.hasOwnProperty(r)&&(f[r]=t[r])}var p=arguments.length-2;if(1===p)f.children=n;else if(p>1){for(var d=Array(p),v=0;p>v;v++)d[v]=arguments[v+2];f.children=d}return new u(e.type,l,c,h,e._context,f)},u.isValidElement=function(e){var t=!!e&&!!e._isReactElement;return t},t.exports=u},{150:150,27:27,38:38,39:39}],56:[function(e,t,n){"use strict";function r(){if(y.current){var e=y.current.getName();if(e)return" Check the render method of `"+e+"`."}return""}function i(e){var t=e&&e.getPublicInstance();if(!t)return void 0;var n=t.constructor;return n?n.displayName||n.name||void 0:void 0}function s(){var e=y.current;return e&&i(e)||void 0}function o(e,t){e._store.validated||null!=e.key||(e._store.validated=!0,a('Each child in an array or iterator should have a unique "key" prop.',e,t))}function u(e,t,n){T.test(e)&&a("Child objects should have non-numeric keys so ordering is preserved.",t,n)}function a(e,t,n){var r=s(),o="string"==typeof n?n:n.displayName||n.name,u=r||o,a=S[e]||(S[e]={});if(!a.hasOwnProperty(u)){a[u]=!0;var f="";if(t&&t._owner&&t._owner!==y.current){var l=i(t._owner);f=" It was passed a child from "+l+"."}}}function f(e,t){if(Array.isArray(e))for(var n=0;n<e.length;n++){var r=e[n];v.isValidElement(r)&&o(r,t)}else if(v.isValidElement(e))e._store.validated=!0;else if(e){var i=w(e);if(i){if(i!==e.entries)for(var s,a=i.call(e);!(s=a.next()).done;)v.isValidElement(s.value)&&o(s.value,t)}else if("object"==typeof e){var f=m.extractIfFragment(e);for(var l in f)f.hasOwnProperty(l)&&u(l,f[l],t)}}}function l(e,t,n,i){for(var s in t)if(t.hasOwnProperty(s)){var o;try{E("function"==typeof t[s]),o=t[s](n,s,e,i)}catch(u){o=u}o instanceof Error&&!(o.message in x)&&(x[o.message]=!0,r(this))}}function c(e,t){var n=t.type,r="string"==typeof n?n:n.displayName,i=t._owner?t._owner.getPublicInstance().constructor.displayName:null,s=e+"|"+r+"|"+i;if(!N.hasOwnProperty(s)){N[s]=!0;var o="";r&&(o=" <"+r+" />");var u="";i&&(u=" The element was created by "+i+".")}}function h(e,t){return e!==e?t!==t:0===e&&0===t?1/e===1/t:e===t}function p(e){if(e._store){var t=e._store.originalProps,n=e.props;for(var r in n)n.hasOwnProperty(r)&&(t.hasOwnProperty(r)&&h(t[r],n[r])||(c(r,e),t[r]=n[r]))}}function d(e){if(null!=e.type){var t=b.getComponentClassForElement(e),n=t.displayName||t.name;t.propTypes&&l(n,t.propTypes,e.props,g.prop),"function"==typeof t.getDefaultProps}}var v=e(55),m=e(61),g=e(75),y=(e(74),e(39)),b=e(71),w=e(124),E=e(133),S=(e(150),{}),x={},T=/^\d+$/,N={},C={checkAndWarnForMutatedProps:p,createElement:function(e,t,n){var r=v.createElement.apply(this,arguments);if(null==r)return r;for(var i=2;i<arguments.length;i++)f(arguments[i],e);return d(r),r},createFactory:function(e){var t=C.createElement.bind(null,e);return t.type=e,t},cloneElement:function(e,t,n){for(var r=v.cloneElement.apply(this,arguments),i=2;i<arguments.length;i++)f(arguments[i],r.type);return d(r),r}};t.exports=C},{124:124,133:133,150:150,39:39,55:55,61:61,71:71,74:74,75:75}],57:[function(e,t,n){"use strict";function r(e){l[e]=!0}function i(e){delete l[e]}function s(e){return!!l[e]}var o,u=e(55),a=e(65),f=e(133),l={},c={injectEmptyComponent:function(e){o=u.createFactory(e)}},h=function(){};h.prototype.componentDidMount=function(){var e=a.get(this);e&&r(e._rootNodeID)},h.prototype.componentWillUnmount=function(){var e=a.get(this);e&&i(e._rootNodeID)},h.prototype.render=function(){return f(o),o()};var p=u.createElement(h),d={emptyElement:p,injection:c,isNullComponentID:s};t.exports=d},{133:133,55:55,65:65}],58:[function(e,t,n){"use strict";var r={guard:function(e,t){return e}};t.exports=r},{}],59:[function(e,t,n){"use strict";function r(e){i.enqueueEvents(e),i.processEventQueue()}var i=e(17),s={handleTopLevel:function(e,t,n,s){var u=i.extractEvents(e,t,n,s);r(u)}};t.exports=s},{17:17}],60:[function(e,t,n){"use strict";function r(e){var t=c.getID(e),n=l.getReactRootIDFromNodeID(t),r=c.findReactContainerForID(n),i=c.getFirstReactDOM(r);return i}function i(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function s(e){for(var t=c.getFirstReactDOM(d(e.nativeEvent))||window,n=t;n;)e.ancestors.push(n),n=r(n);for(var i=0,s=e.ancestors.length;s>i;i++){t=e.ancestors[i];var o=c.getID(t)||"";m._handleTopLevel(e.topLevelType,t,o,e.nativeEvent)}}function o(e){var t=v(window);e(t)}var u=e(16),a=e(21),f=e(28),l=e(64),c=e(68),h=e(85),p=e(27),d=e(123),v=e(129);p(i.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),f.addPoolingTo(i,f.twoArgumentPooler);var m={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:a.canUseDOM?window:null,setHandleTopLevel:function(e){m._handleTopLevel=e},setEnabled:function(e){m._enabled=!!e},isEnabled:function(){return m._enabled},trapBubbledEvent:function(e,t,n){var r=n;return r?u.listen(r,t,m.dispatchEvent.bind(null,e)):null},trapCapturedEvent:function(e,t,n){var r=n;return r?u.capture(r,t,m.dispatchEvent.bind(null,e)):null},monitorScrollValue:function(e){var t=o.bind(null,e);u.listen(window,"scroll",t)},dispatchEvent:function(e,t){if(m._enabled){var n=i.getPooled(e,t);try{h.batchedUpdates(s,n)}finally{i.release(n)}}}};t.exports=m},{123:123,129:129,16:16,21:21,27:27,28:28,64:64,68:68,85:85}],61:[function(e,t,n){"use strict";var r=(e(55),e(150),{create:function(e){return e},extract:function(e){return e},extractIfFragment:function(e){return e}});t.exports=r},{150:150,55:55}],62:[function(e,t,n){"use strict";var r=e(10),i=e(17),s=e(36),o=e(33),u=e(57),a=e(30),f=e(71),l=e(42),c=e(73),h=e(81),p=e(85),d={Component:s.injection,Class:o.injection,DOMComponent:l.injection,DOMProperty:r.injection,EmptyComponent:u.injection,EventPluginHub:i.injection,EventEmitter:a.injection,NativeComponent:f.injection,Perf:c.injection,RootIndex:h.injection,Updates:p.injection};t.exports=d},{10:10,17:17,30:30,33:33,36:36,42:42,57:57,71:71,73:73,81:81,85:85}],63:[function(e,t,n){"use strict";function r(e){return s(document.documentElement,e)}var i=e(50),s=e(107),o=e(117),u=e(119),a={hasSelectionCapabilities:function(e){return e&&("INPUT"===e.nodeName&&"text"===e.type||"TEXTAREA"===e.nodeName||"true"===e.contentEditable)},getSelectionInformation:function(){var e=u();return{focusedElem:e,selectionRange:a.hasSelectionCapabilities(e)?a.getSelection(e):null}},restoreSelection:function(e){var t=u(),n=e.focusedElem,i=e.selectionRange;t!==n&&r(n)&&(a.hasSelectionCapabilities(n)&&a.setSelection(n,i),o(n))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&"INPUT"===e.nodeName){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=i.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,r=t.end;if("undefined"==typeof r&&(r=n),"selectionStart"in e)e.selectionStart=n,e.selectionEnd=Math.min(r,e.value.length);else if(document.selection&&"INPUT"===e.nodeName){var s=e.createTextRange();s.collapse(!0),s.moveStart("character",n),s.moveEnd("character",r-n),s.select()}else i.setOffsets(e,t)}};t.exports=a},{107:107,117:117,119:119,50:50}],64:[function(e,t,n){"use strict";function r(e){return p+e.toString(36)}function i(e,t){return e.charAt(t)===p||t===e.length}function s(e){return""===e||e.charAt(0)===p&&e.charAt(e.length-1)!==p}function o(e,t){return 0===t.indexOf(e)&&i(t,e.length)}function u(e){return e?e.substr(0,e.lastIndexOf(p)):""}function a(e,t){if(h(s(e)&&s(t)),h(o(e,t)),e===t)return e;var n,r=e.length+d;for(n=r;n<t.length&&!i(t,n);n++);return t.substr(0,n)}function f(e,t){var n=Math.min(e.length,t.length);if(0===n)return"";for(var r=0,o=0;n>=o;o++)if(i(e,o)&&i(t,o))r=o;else if(e.charAt(o)!==t.charAt(o))break;var u=e.substr(0,r);return h(s(u)),u}function l(e,t,n,r,i,s){e=e||"",t=t||"",h(e!==t);var f=o(t,e);h(f||o(e,t));for(var l=0,c=f?u:a,p=e;;p=c(p,t)){var d;if(i&&p===e||s&&p===t||(d=n(p,f,r)),d===!1||p===t)break;h(l++<v)}}var c=e(81),h=e(133),p=".",d=p.length,v=100,m={createReactRootID:function(){return r(c.createReactRootIndex())},createReactID:function(e,t){return e+t},getReactRootIDFromNodeID:function(e){if(e&&e.charAt(0)===p&&e.length>1){var t=e.indexOf(p,1);return t>-1?e.substr(0,t):e}return null},traverseEnterLeave:function(e,t,n,r,i){var s=f(e,t);s!==e&&l(e,s,n,r,!1,!0),s!==t&&l(s,t,n,i,!0,!1)},traverseTwoPhase:function(e,t,n){e&&(l("",e,t,n,!0,!1),l(e,"",t,n,!1,!0))},traverseAncestors:function(e,t,n){l("",e,t,n,!0,!1)},_getFirstCommonAncestorID:f,_getNextDescendantID:a,isAncestorIDOf:o,SEPARATOR:p};t.exports=m},{133:133,81:81}],65:[function(e,t,n){"use strict";var r={remove:function(e){e._reactInternalInstance=void 0},get:function(e){return e._reactInternalInstance},has:function(e){return void 0!==e._reactInternalInstance},set:function(e,t){e._reactInternalInstance=t}};t.exports=r},{}],66:[function(e,t,n){"use strict";var r={currentlyMountingInstance:null,currentlyUnmountingInstance:null};t.exports=r},{}],67:[function(e,t,n){"use strict";var r=e(104),i={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=r(e);return e.replace(">"," "+i.CHECKSUM_ATTR_NAME+'="'+t+'">')},canReuseMarkup:function(e,t){var n=t.getAttribute(i.CHECKSUM_ATTR_NAME);n=n&&parseInt(n,10);var s=r(e);return s===n}};t.exports=i},{104:104}],68:[function(e,t,n){"use strict";function r(e,t){for(var n=Math.min(e.length,t.length),r=0;n>r;r++)if(e.charAt(r)!==t.charAt(r))return r;return e.length===t.length?-1:n}function i(e){var t=A(e);return t&&z.getID(t)}function s(e){var t=o(e);if(t)if(B.hasOwnProperty(t)){var n=B[t];n!==e&&(M(!l(n,t)),B[t]=e)}else B[t]=e;return t}function o(e){return e&&e.getAttribute&&e.getAttribute(H)||""}function u(e,t){var n=o(e);n!==t&&delete B[n],e.setAttribute(H,t),B[t]=e}function a(e){return B.hasOwnProperty(e)&&l(B[e],e)||(B[e]=z.findReactNodeByID(e)),B[e]}function f(e){var t=E.get(e)._rootNodeID;return b.isNullComponentID(t)?null:(B.hasOwnProperty(t)&&l(B[t],t)||(B[t]=z.findReactNodeByID(t)),B[t])}function l(e,t){if(e){M(o(e)===t);var n=z.findReactContainerForID(t);if(n&&L(n,e))return!0}return!1}function c(e){delete B[e]}function h(e){var t=B[e];return t&&l(t,e)?void (U=t):!1}function p(e){U=null,w.traverseAncestors(e,h);var t=U;return U=null,t}function d(e,t,n,r,i){var s=T.mountComponent(e,t,r,k);e._isTopLevel=!0,z._mountImageIntoNode(s,n,i)}function v(e,t,n,r){var i=C.ReactReconcileTransaction.getPooled();i.perform(d,null,e,t,n,i,r),C.ReactReconcileTransaction.release(i)}var m=e(10),g=e(30),y=(e(39),e(55)),b=(e(56),e(57)),w=e(64),E=e(65),S=e(67),x=e(73),T=e(79),N=e(84),C=e(85),k=e(113),L=e(107),A=e(127),O=e(132),M=e(133),_=e(144),D=e(147),P=(e(150),w.SEPARATOR),H=m.ID_ATTRIBUTE_NAME,B={},j=1,F=9,I={},q={},R=[],U=null,z={_instancesByReactRootID:I,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,r){return z.scrollMonitor(n,function(){N.enqueueElementInternal(e,t),r&&N.enqueueCallbackInternal(e,r)}),e},_registerComponent:function(e,t){M(t&&(t.nodeType===j||t.nodeType===F)),g.ensureScrollValueMonitoring();var n=z.registerContainer(t);return I[n]=e,n},_renderNewRootComponent:function(e,t,n){var r=O(e,null),i=z._registerComponent(r,t);return C.batchedUpdates(v,r,i,t,n),r},render:function(e,t,n){M(y.isValidElement(e));var r=I[i(t)];if(r){var s=r._currentElement;if(D(s,e))return z._updateRootComponent(r,e,t,n).getPublicInstance();z.unmountComponentAtNode(t)}var o=A(t),u=o&&z.isRenderedByReact(o),a=u&&!r,f=z._renderNewRootComponent(e,t,a).getPublicInstance();return n&&n.call(f),f},constructAndRenderComponent:function(e,t,n){var r=y.createElement(e,t);return z.render(r,n)},constructAndRenderComponentByID:function(e,t,n){var r=document.getElementById(n);return M(r),z.constructAndRenderComponent(e,t,r)},registerContainer:function(e){var t=i(e);return t&&(t=w.getReactRootIDFromNodeID(t)),t||(t=w.createReactRootID()),q[t]=e,t},unmountComponentAtNode:function(e){M(e&&(e.nodeType===j||e.nodeType===F));var t=i(e),n=I[t];return n?(z.unmountComponentFromNode(n,e),delete I[t],delete q[t],!0):!1},unmountComponentFromNode:function(e,t){for(T.unmountComponent(e),t.nodeType===F&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)},findReactContainerForID:function(e){var t=w.getReactRootIDFromNodeID(e),n=q[t];return n},findReactNodeByID:function(e){var t=z.findReactContainerForID(e);return z.findComponentRoot(t,e)},isRenderedByReact:function(e){if(1!==e.nodeType)return!1;var t=z.getID(e);return t?t.charAt(0)===P:!1},getFirstReactDOM:function(e){for(var t=e;t&&t.parentNode!==t;){if(z.isRenderedByReact(t))return t;t=t.parentNode}return null},findComponentRoot:function(e,t){var n=R,r=0,i=p(t)||e;for(n[0]=i.firstChild,n.length=1;r<n.length;){for(var s,o=n[r++];o;){var u=z.getID(o);u?t===u?s=o:w.isAncestorIDOf(u,t)&&(n.length=r=0,n.push(o.firstChild)):n.push(o.firstChild),o=o.nextSibling}if(s)return n.length=0,s}n.length=0,M(!1)},_mountImageIntoNode:function(e,t,n){if(M(t&&(t.nodeType===j||t.nodeType===F)),n){var i=A(t);if(S.canReuseMarkup(e,i))return;var s=i.getAttribute(S.CHECKSUM_ATTR_NAME);i.removeAttribute(S.CHECKSUM_ATTR_NAME);var o=i.outerHTML;i.setAttribute(S.CHECKSUM_ATTR_NAME,s);var u=r(e,o);" (client) "+e.substring(u-20,u+20)+"\n (server) "+o.substring(u-20,u+20),M(t.nodeType!==F)}M(t.nodeType!==F),_(t,e)},getReactRootID:i,getID:s,setID:u,getNode:a,getNodeFromInstance:f,purgeID:c};x.measureMethods(z,"ReactMount",{_renderNewRootComponent:"_renderNewRootComponent",_mountImageIntoNode:"_mountImageIntoNode"}),t.exports=z},{10:10,107:107,113:113,127:127,132:132,133:133,144:144,147:147,150:150,30:30,39:39,55:55,56:56,57:57,64:64,65:65,67:67,73:73,79:79,84:84,85:85}],69:[function(e,t,n){"use strict";function r(e,t,n){d.push({parentID:e,parentNode:null,type:l.INSERT_MARKUP,markupIndex:v.push(t)-1,textContent:null,fromIndex:null,toIndex:n})}function i(e,t,n){d.push({parentID:e,parentNode:null,type:l.MOVE_EXISTING,markupIndex:null,textContent:null,fromIndex:t,toIndex:n})}function s(e,t){d.push({parentID:e,parentNode:null,type:l.REMOVE_NODE,markupIndex:null,textContent:null,fromIndex:t,toIndex:null})}function o(e,t){d.push({parentID:e,parentNode:null,type:l.TEXT_CONTENT,markupIndex:null,textContent:t,fromIndex:null,toIndex:null})}function u(){d.length&&(f.processChildrenUpdates(d,v),a())}function a(){d.length=0,v.length=0}var f=e(36),l=e(70),c=e(79),h=e(31),p=0,d=[],v=[],m={Mixin:{mountChildren:function(e,t,n){var r=h.instantiateChildren(e,t,n);this._renderedChildren=r;var i=[],s=0;for(var o in r)if(r.hasOwnProperty(o)){var u=r[o],a=this._rootNodeID+o,f=c.mountComponent(u,a,t,n);u._mountIndex=s,i.push(f),s++}return i},updateTextContent:function(e){p++;var t=!0;try{var n=this._renderedChildren;h.unmountChildren(n);for(var r in n)n.hasOwnProperty(r)&&this._unmountChildByName(n[r],r);this.setTextContent(e),t=!1}finally{p--,p||(t?a():u())}},updateChildren:function(e,t,n){p++;var r=!0;try{this._updateChildren(e,t,n),r=!1}finally{p--,p||(r?a():u())}},_updateChildren:function(e,t,n){var r=this._renderedChildren,i=h.updateChildren(r,e,t,n);if(this._renderedChildren=i,i||r){var s,o=0,u=0;for(s in i)if(i.hasOwnProperty(s)){var a=r&&r[s],f=i[s];a===f?(this.moveChild(a,u,o),o=Math.max(a._mountIndex,o),a._mountIndex=u):(a&&(o=Math.max(a._mountIndex,o),this._unmountChildByName(a,s)),this._mountChildByNameAtIndex(f,s,u,t,n)),u++}for(s in r)!r.hasOwnProperty(s)||i&&i.hasOwnProperty(s)||this._unmountChildByName(r[s],s)}},unmountChildren:function(){var e=this._renderedChildren;h.unmountChildren(e),this._renderedChildren=null},moveChild:function(e,t,n){e._mountIndex<n&&i(this._rootNodeID,e._mountIndex,t)},createChild:function(e,t){r(this._rootNodeID,t,e._mountIndex)},removeChild:function(e){s(this._rootNodeID,e._mountIndex)},setTextContent:function(e){o(this._rootNodeID,e)},_mountChildByNameAtIndex:function(e,t,n,r,i){var s=this._rootNodeID+t,o=c.mountComponent(e,s,r,i);e._mountIndex=n,this.createChild(e,o)},_unmountChildByName:function(e,t){this.removeChild(e),e._mountIndex=null}}};t.exports=m},{31:31,36:36,70:70,79:79}],70:[function(e,t,n){"use strict";var r=e(138),i=r({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,TEXT_CONTENT:null});t.exports=i},{138:138}],71:[function(e,t,n){"use strict";function r(e){if("function"==typeof e.type)return e.type;var t=e.type,n=c[t];return null==n&&(c[t]=n=f(t)),n}function i(e){return a(l),new l(e.type,e.props)}function s(e){return new h(e)}function o(e){return e instanceof h}var u=e(27),a=e(133),f=null,l=null,c={},h=null,p={injectGenericComponentClass:function(e){l=e},injectTextComponentClass:function(e){h=e},injectComponentClasses:function(e){u(c,e)},injectAutoWrapper:function(e){f=e}},d={getComponentClassForElement:r,createInternalComponent:i,createInstanceForText:s,isTextComponent:o,injection:p};t.exports=d},{133:133,27:27}],72:[function(e,t,n){"use strict";var r=e(133),i={isValidOwner:function(e){return!!e&&"function"==typeof e.attachRef&&"function"==typeof e.detachRef},addComponentAsRefTo:function(e,t,n){r(i.isValidOwner(n)),n.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,n){r(i.isValidOwner(n)),n.getPublicInstance().refs[t]===e.getPublicInstance()&&n.detachRef(t)}};t.exports=i},{133:133}],73:[function(e,t,n){"use strict";function r(e,t,n){return n}var i={enableMeasure:!1,storedMeasure:r,measureMethods:function(e,t,n){},measure:function(e,t,n){return n},injection:{injectMeasure:function(e){i.storedMeasure=e}}};t.exports=i},{}],74:[function(e,t,n){"use strict";var r={};t.exports=r},{}],75:[function(e,t,n){"use strict";var r=e(138),i=r({prop:null,context:null,childContext:null});t.exports=i},{138:138}],76:[function(e,t,n){"use strict";function r(e){function t(t,n,r,i,s){if(i=i||E,null==n[r]){var o=b[s];return t?new Error("Required "+o+" `"+r+"` was not specified in "+("`"+i+"`.")):null}return e(n,r,i,s)}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function i(e){function t(t,n,r,i){var s=t[n],o=v(s);if(o!==e){var u=b[i],a=m(s);return new Error("Invalid "+u+" `"+n+"` of type `"+a+"` "+("supplied to `"+r+"`, expected `"+e+"`."))}return null}return r(t)}function s(){return r(w.thatReturns(null))}function o(e){function t(t,n,r,i){var s=t[n];if(!Array.isArray(s)){var o=b[i],u=v(s);return new Error("Invalid "+o+" `"+n+"` of type "+("`"+u+"` supplied to `"+r+"`, expected an array."))}for(var a=0;a<s.length;a++){var f=e(s,a,r,i);if(f instanceof Error)return f}return null}return r(t)}function u(){function e(e,t,n,r){if(!g.isValidElement(e[t])){var i=b[r];return new Error("Invalid "+i+" `"+t+"` supplied to "+("`"+n+"`, expected a ReactElement."))}return null}return r(e)}function a(e){function t(t,n,r,i){if(t[n]instanceof e)return null;var s=b[i],o=e.name||E;return new Error("Invalid "+s+" `"+n+"` supplied to "+("`"+r+"`, expected instance of `"+o+"`."))}return r(t)}function f(e){function t(t,n,r,i){for(var s=t[n],o=0;o<e.length;o++)if(s===e[o])return null;var u=b[i],a=JSON.stringify(e);return new Error("Invalid "+u+" `"+n+"` of value `"+s+"` "+("supplied to `"+r+"`, expected one of "+a+"."))}return r(t)}function l(e){function t(t,n,r,i){var s=t[n],o=v(s);if("object"!==o){var u=b[i];return new Error("Invalid "+u+" `"+n+"` of type "+("`"+o+"` supplied to `"+r+"`, expected an object."))}for(var a in s)if(s.hasOwnProperty(a)){var f=e(s,a,r,i);if(f instanceof Error)return f}return null}return r(t)}function c(e){function t(t,n,r,i){for(var s=0;s<e.length;s++){var o=e[s];if(null==o(t,n,r,i))return null}var u=b[i];return new Error("Invalid "+u+" `"+n+"` supplied to "+("`"+r+"`."))}return r(t)}function h(){function e(e,t,n,r){if(!d(e[t])){var i=b[r];return new Error("Invalid "+i+" `"+t+"` supplied to "+("`"+n+"`, expected a ReactNode."))}return null}return r(e)}function p(e){function t(t,n,r,i){var s=t[n],o=v(s);if("object"!==o){var u=b[i];return new Error("Invalid "+u+" `"+n+"` of type `"+o+"` "+("supplied to `"+r+"`, expected `object`."))}for(var a in e){var f=e[a];if(f){var l=f(s,a,r,i);if(l)return l}}return null}return r(t)}function d(e){switch(typeof e){case"number":case"string":case"undefined":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(d);if(null===e||g.isValidElement(e))return!0;e=y.extractIfFragment(e);for(var t in e)if(!d(e[t]))return!1;return!0;default:return!1}}function v(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":t}function m(e){var t=v(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}var g=e(55),y=e(61),b=e(74),w=e(112),E="<<anonymous>>",S=u(),x=h(),T={array:i("array"),bool:i("boolean"),func:i("function"),number:i("number"),object:i("object"),string:i("string"),any:s(),arrayOf:o,element:S,instanceOf:a,node:x,objectOf:l,oneOf:f,oneOfType:c,shape:p};t.exports=T},{112:112,55:55,61:61,74:74}],77:[function(e,t,n){"use strict";function r(){this.listenersToPut=[]}var i=e(28),s=e(30),o=e(27);o(r.prototype,{enqueuePutListener:function(e,t,n){this.listenersToPut.push({rootNodeID:e,propKey:t,propValue:n})},putListeners:function(){for(var e=0;e<this.listenersToPut.length;e++){var t=this.listenersToPut[e];s.putListener(t.rootNodeID,t.propKey,t.propValue)}},reset:function(){this.listenersToPut.length=0},destructor:function(){this.reset()}}),i.addPoolingTo(r),t.exports=r},{27:27,28:28,30:30}],78:[function(e,t,n){"use strict";function r(){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=i.getPooled(null),this.putListenerQueue=a.getPooled()}var i=e(6),s=e(28),o=e(30),u=e(63),a=e(77),f=e(101),l=e(27),c={initialize:u.getSelectionInformation,close:u.restoreSelection},h={initialize:function(){var e=o.isEnabled();return o.setEnabled(!1),e},close:function(e){o.setEnabled(e)}},p={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},d={initialize:function(){this.putListenerQueue.reset()},close:function(){this.putListenerQueue.putListeners()}},v=[d,c,h,p],m={getTransactionWrappers:function(){return v},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){i.release(this.reactMountReady),this.reactMountReady=null,a.release(this.putListenerQueue),this.putListenerQueue=null}};l(r.prototype,f.Mixin,m),s.addPoolingTo(r),t.exports=r},{101:101,27:27,28:28,30:30,6:6,63:63,77:77}],79:[function(e,t,n){"use strict";function r(){i.attachRefs(this,this._currentElement)}var i=e(80),s=(e(56),{mountComponent:function(e,t,n,i){var s=e.mountComponent(t,n,i);return n.getReactMountReady().enqueue(r,e),s},unmountComponent:function(e){i.detachRefs(e,e._currentElement),e.unmountComponent()},receiveComponent:function(e,t,n,s){var u=e._currentElement;if(t!==u||null==t._owner){var a=i.shouldUpdateRefs(u,t);a&&i.detachRefs(e,u),e.receiveComponent(t,n,s),a&&n.getReactMountReady().enqueue(r,e)}},performUpdateIfNecessary:function(e,t){e.performUpdateIfNecessary(t)}});t.exports=s},{56:56,80:80}],80:[function(e,t,n){"use strict";function r(e,t,n){"function"==typeof e?e(t.getPublicInstance()):s.addComponentAsRefTo(t,e,n)}function i(e,t,n){"function"==typeof e?e(null):s.removeComponentAsRefFrom(t,e,n)}var s=e(72),o={};o.attachRefs=function(e,t){var n=t.ref;null!=n&&r(n,e,t._owner)},o.shouldUpdateRefs=function(e,t){return t._owner!==e._owner||t.ref!==e.ref},o.detachRefs=function(e,t){var n=t.ref;null!=n&&i(n,e,t._owner)},t.exports=o},{72:72}],81:[function(e,t,n){"use strict";var r={injectCreateReactRootIndex:function(e){i.createReactRootIndex=e}},i={createReactRootIndex:null,injection:r};t.exports=i},{}],82:[function(e,t,n){"use strict";function r(e){c(s.isValidElement(e));var t;try{var n=o.createReactRootID();return t=a.getPooled(!1),t.perform(function(){var r=l(e,null),i=r.mountComponent(n,t,f);return u.addChecksumToMarkup(i)},null)}finally{a.release(t)}}function i(e){c(s.isValidElement(e));var t;try{var n=o.createReactRootID();return t=a.getPooled(!0),t.perform(function(){var r=l(e,null);return r.mountComponent(n,t,f)},null)}finally{a.release(t)}}var s=e(55),o=e(64),u=e(67),a=e(83),f=e(113),l=e(132),c=e(133);t.exports={renderToString:r,renderToStaticMarkup:i}},{113:113,132:132,133:133,55:55,64:64,67:67,83:83}],83:[function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.reactMountReady=s.getPooled(null),this.putListenerQueue=o.getPooled()}var i=e(28),s=e(6),o=e(77),u=e(101),a=e(27),f=e(112),l={initialize:function(){this.reactMountReady.reset()},close:f},c={initialize:function(){this.putListenerQueue.reset()},close:f},h=[c,l],p={getTransactionWrappers:function(){return h},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){s.release(this.reactMountReady),this.reactMountReady=null,o.release(this.putListenerQueue),this.putListenerQueue=null}};a(r.prototype,u.Mixin,p),i.addPoolingTo(r),t.exports=r},{101:101,112:112,27:27,28:28,6:6,77:77}],84:[function(e,t,n){"use strict";function r(e){e!==s.currentlyMountingInstance&&f.enqueueUpdate(e)}function i(e,t){c(null==o.current);var n=a.get(e);return n?n===s.currentlyUnmountingInstance?null:n:null}var s=e(66),o=e(39),u=e(55),a=e(65),f=e(85),l=e(27),c=e(133),h=(e(150),{enqueueCallback:function(e,t){c("function"==typeof t);var n=i(e);return n&&n!==s.currentlyMountingInstance?(n._pendingCallbacks?n._pendingCallbacks.push(t):n._pendingCallbacks=[t],void r(n)):null},enqueueCallbackInternal:function(e,t){c("function"==typeof t),e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t],r(e)},enqueueForceUpdate:function(e){var t=i(e,"forceUpdate");t&&(t._pendingForceUpdate=!0,r(t))},enqueueReplaceState:function(e,t){var n=i(e,"replaceState");n&&(n._pendingStateQueue=[t],n._pendingReplaceState=!0,r(n))},enqueueSetState:function(e,t){var n=i(e,"setState");if(n){var s=n._pendingStateQueue||(n._pendingStateQueue=[]);s.push(t),r(n)}},enqueueSetProps:function(e,t){var n=i(e,"setProps");if(n){c(n._isTopLevel);var s=n._pendingElement||n._currentElement,o=l({},s.props,t);n._pendingElement=u.cloneAndReplaceProps(s,o),r(n)}},enqueueReplaceProps:function(e,t){var n=i(e,"replaceProps");if(n){c(n._isTopLevel);var s=n._pendingElement||n._currentElement;n._pendingElement=u.cloneAndReplaceProps(s,t),r(n)}},enqueueElementInternal:function(e,t){e._pendingElement=t,r(e)}});t.exports=h},{133:133,150:150,27:27,39:39,55:55,65:65,66:66,85:85}],85:[function(e,t,n){"use strict";function r(){m(C.ReactReconcileTransaction&&w)}function i(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=l.getPooled(),this.reconcileTransaction=C.ReactReconcileTransaction.getPooled()}function s(e,t,n,i,s){r(),w.batchedUpdates(e,t,n,i,s)}function o(e,t){return e._mountOrder-t._mountOrder}function u(e){var t=e.dirtyComponentsLength;m(t===g.length),g.sort(o);for(var n=0;t>n;n++){var r=g[n],i=r._pendingCallbacks;if(r._pendingCallbacks=null,p.performUpdateIfNecessary(r,e.reconcileTransaction),i)for(var s=0;s<i.length;s++)e.callbackQueue.enqueue(i[s],r.getPublicInstance())}}function a(e){return r(),w.isBatchingUpdates?void g.push(e):void w.batchedUpdates(a,e)}function f(e,t){m(w.isBatchingUpdates),y.enqueue(e,t),b=!0}var l=e(6),c=e(28),h=(e(39),e(73)),p=e(79),d=e(101),v=e(27),m=e(133),g=(e(150),[]),y=l.getPooled(),b=!1,w=null,E={initialize:function(){this.dirtyComponentsLength=g.length},close:function(){this.dirtyComponentsLength!==g.length?(g.splice(0,this.dirtyComponentsLength),T()):g.length=0}},S={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},x=[E,S];v(i.prototype,d.Mixin,{getTransactionWrappers:function(){return x},destructor:function(){this.dirtyComponentsLength=null,l.release(this.callbackQueue),this.callbackQueue=null,C.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return d.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),c.addPoolingTo(i);var T=function(){for(;g.length||b;){if(g.length){var e=i.getPooled();e.perform(u,null,e),i.release(e)}if(b){b=!1;var t=y;y=l.getPooled(),t.notifyAll(),l.release(t)}}};T=h.measure("ReactUpdates","flushBatchedUpdates",T);var N={injectReconcileTransaction:function(e){m(e),C.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){m(e),m("function"==typeof e.batchedUpdates),m("boolean"==typeof e.isBatchingUpdates),w=e}},C={ReactReconcileTransaction:null,batchedUpdates:s,enqueueUpdate:a,flushBatchedUpdates:T,injection:N,asap:f};t.exports=C},{101:101,133:133,150:150,27:27,28:28,39:39,6:6,73:73,79:79}],86:[function(e,t,n){"use strict";var r=e(10),i=r.injection.MUST_USE_ATTRIBUTE,s={Properties:{clipPath:i,cx:i,cy:i,d:i,dx:i,dy:i,fill:i,fillOpacity:i,fontFamily:i,fontSize:i,fx:i,fy:i,gradientTransform:i,gradientUnits:i,markerEnd:i,markerMid:i,markerStart:i,offset:i,opacity:i,patternContentUnits:i,patternUnits:i,points:i,preserveAspectRatio:i,r:i,rx:i,ry:i,spreadMethod:i,stopColor:i,stopOpacity:i,stroke:i,strokeDasharray:i,strokeLinecap:i,strokeOpacity:i,strokeWidth:i,textAnchor:i,transform:i,version:i,viewBox:i,x1:i,x2:i,x:i,y1:i,y2:i,y:i},DOMAttributeNames:{clipPath:"clip-path",fillOpacity:"fill-opacity",fontFamily:"font-family",fontSize:"font-size",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",patternContentUnits:"patternContentUnits",patternUnits:"patternUnits",preserveAspectRatio:"preserveAspectRatio",spreadMethod:"spreadMethod",stopColor:"stop-color",stopOpacity:"stop-opacity",strokeDasharray:"stroke-dasharray",strokeLinecap:"stroke-linecap",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",textAnchor:"text-anchor",viewBox:"viewBox"}};t.exports=s},{10:10}],87:[function(e,t,n){"use strict";function r(e){if("selectionStart"in e&&u.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}if(document.selection){var n=document.selection.createRange();return{parentElement:n.parentElement(),text:n.text,top:n.boundingTop,left:n.boundingLeft}}}function i(e){if(y||null==v||v!==f())return null;var t=r(v);if(!g||!h(g,t)){g=t;var n=a.getPooled(d.select,m,e);return n.type="select",n.target=v,o.accumulateTwoPhaseDispatches(n),n}}var s=e(15),o=e(20),u=e(63),a=e(93),f=e(119),l=e(136),c=e(139),h=e(146),p=s.topLevelTypes,d={select:{phasedRegistrationNames:{bubbled:c({onSelect:null}),captured:c({onSelectCapture:null})},dependencies:[p.topBlur,p.topContextMenu,p.topFocus,p.topKeyDown,p.topMouseDown,p.topMouseUp,p.topSelectionChange]}},v=null,m=null,g=null,y=!1,b={eventTypes:d,extractEvents:function(e,t,n,r){switch(e){case p.topFocus:(l(t)||"true"===t.contentEditable)&&(v=t,m=n,g=null);break;case p.topBlur:v=null,m=null,g=null;break;case p.topMouseDown:y=!0;break;case p.topContextMenu:case p.topMouseUp:return y=!1,i(r);case p.topSelectionChange:case p.topKeyDown:case p.topKeyUp:return i(r)}}};t.exports=b},{119:119,136:136,139:139,146:146,15:15,20:20,63:63,93:93}],88:[function(e,t,n){"use strict";var r=Math.pow(2,53),i={createReactRootIndex:function(){return Math.ceil(Math.random()*r)}};t.exports=i},{}],89:[function(e,t,n){"use strict";var r=e(15),i=e(19),s=e(20),o=e(90),u=e(93),a=e(94),f=e(96),l=e(97),c=e(92),h=e(98),p=e(99),d=e(100),v=e(120),m=e(133),g=e(139),y=(e(150),r.topLevelTypes),b={blur:{phasedRegistrationNames:{bubbled:g({onBlur:!0}),captured:g({onBlurCapture:!0})}},click:{phasedRegistrationNames:{bubbled:g({onClick:!0}),captured:g({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:g({onContextMenu:!0}),captured:g({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:g({onCopy:!0}),captured:g({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:g({onCut:!0}),captured:g({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:g({onDoubleClick:!0}),captured:g({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:g({onDrag:!0}),captured:g({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:g({onDragEnd:!0}),captured:g({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:g({onDragEnter:!0}),captured:g({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:g({onDragExit:!0}),captured:g({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:g({onDragLeave:!0}),captured:g({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:g({onDragOver:!0}),captured:g({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:g({onDragStart:!0}),captured:g({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:g({onDrop:!0}),captured:g({onDropCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:g({onFocus:!0}),captured:g({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:g({onInput:!0}),captured:g({onInputCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:g({onKeyDown:!0}),captured:g({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:g({onKeyPress:!0}),captured:g({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:g({onKeyUp:!0}),captured:g({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:g({onLoad:!0}),captured:g({onLoadCapture:!0})}},error:{phasedRegistrationNames:{bubbled:g({onError:!0}),captured:g({onErrorCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:g({onMouseDown:!0}),captured:g({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:g({onMouseMove:!0}),captured:g({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:g({onMouseOut:!0}),captured:g({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:g({onMouseOver:!0}),captured:g({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:g({onMouseUp:!0}),captured:g({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:g({onPaste:!0}),captured:g({onPasteCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:g({onReset:!0}),captured:g({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:g({onScroll:!0}),captured:g({onScrollCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:g({onSubmit:!0}),captured:g({onSubmitCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:g({onTouchCancel:!0}),captured:g({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:g({onTouchEnd:!0}),captured:g({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:g({onTouchMove:!0}),captured:g({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:g({onTouchStart:!0}),captured:g({onTouchStartCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:g({onWheel:!0}),captured:g({onWheelCapture:!0})}}},w={topBlur:b.blur,topClick:b.click,topContextMenu:b.contextMenu,topCopy:b.copy,topCut:b.cut,topDoubleClick:b.doubleClick,topDrag:b.drag,topDragEnd:b.dragEnd,topDragEnter:b.dragEnter,topDragExit:b.dragExit,topDragLeave:b.dragLeave,topDragOver:b.dragOver,topDragStart:b.dragStart,topDrop:b.drop,topError:b.error,topFocus:b.focus,topInput:b.input,topKeyDown:b.keyDown,topKeyPress:b.keyPress,topKeyUp:b.keyUp,topLoad:b.load,topMouseDown:b.mouseDown,topMouseMove:b.mouseMove,topMouseOut:b.mouseOut,topMouseOver:b.mouseOver,topMouseUp:b.mouseUp,topPaste:b.paste,topReset:b.reset,topScroll:b.scroll,topSubmit:b.submit,topTouchCancel:b.touchCancel,topTouchEnd:b.touchEnd,topTouchMove:b.touchMove,topTouchStart:b.touchStart,topWheel:b.wheel};for(var E in w)w[E].dependencies=[E];var S={eventTypes:b,executeDispatch:function(e,t,n){var r=i.executeDispatch(e,t,n);r===!1&&(e.stopPropagation(),e.preventDefault())},extractEvents:function(e,t,n,r){var i=w[e];if(!i)return null;var g;switch(e){case y.topInput:case y.topLoad:case y.topError:case y.topReset:case y.topSubmit:g=u;break;case y.topKeyPress:if(0===v(r))return null;case y.topKeyDown:case y.topKeyUp:g=f;break;case y.topBlur:case y.topFocus:g=a;break;case y.topClick:if(2===r.button)return null;case y.topContextMenu:case y.topDoubleClick:case y.topMouseDown:case y.topMouseMove:case y.topMouseOut:case y.topMouseOver:case y.topMouseUp:g=l;break;case y.topDrag:case y.topDragEnd:case y.topDragEnter:case y.topDragExit:case y.topDragLeave:case y.topDragOver:case y.topDragStart:case y.topDrop:g=c;break;case y.topTouchCancel:case y.topTouchEnd:case y.topTouchMove:case y.topTouchStart:g=h;break;case y.topScroll:g=p;break;case y.topWheel:g=d;break;case y.topCopy:case y.topCut:case y.topPaste:g=o}m(g);var b=g.getPooled(i,n,r);return s.accumulateTwoPhaseDispatches(b),b}};t.exports=S},{100:100,120:120,133:133,139:139,15:15,150:150,19:19,20:20,90:90,92:92,93:93,94:94,96:96,97:97,98:98,99:99}],90:[function(e,t,n){"use strict";function r(e,t,n){i.call(this,e,t,n)}var i=e(93),s={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};i.augmentClass(r,s),t.exports=r},{93:93}],91:[function(e,t,n){"use strict";function r(e,t,n){i.call(this,e,t,n)}var i=e(93),s={data:null};i.augmentClass(r,s),t.exports=r},{93:93}],92:[function(e,t,n){"use strict";function r(e,t,n){i.call(this,e,t,n)}var i=e(97),s={dataTransfer:null};i.augmentClass(r,s),t.exports=r},{97:97}],93:[function(e,t,n){"use strict";function r(e,t,n){this.dispatchConfig=e,this.dispatchMarker=t,this.nativeEvent=n;var r=this.constructor.Interface;for(var i in r)if(r.hasOwnProperty(i)){var s=r[i];s?this[i]=s(n):this[i]=n[i]}var u=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;u?this.isDefaultPrevented=o.thatReturnsTrue:this.isDefaultPrevented=o.thatReturnsFalse,this.isPropagationStopped=o.thatReturnsFalse}var i=e(28),s=e(27),o=e(112),u=e(123),a={type:null,target:u,currentTarget:o.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};s(r.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=o.thatReturnsTrue},stopPropagation:function(){var e=this.nativeEvent;e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=o.thatReturnsTrue},persist:function(){this.isPersistent=o.thatReturnsTrue},isPersistent:o.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;this.dispatchConfig=null,this.dispatchMarker=null,this.nativeEvent=null}}),r.Interface=a,r.augmentClass=function(e,t){var n=this,r=Object.create(n.prototype);s(r,e.prototype),e.prototype=r,e.prototype.constructor=e,e.Interface=s({},n.Interface,t),e.augmentClass=n.augmentClass,i.addPoolingTo(e,i.threeArgumentPooler)},i.addPoolingTo(r,i.threeArgumentPooler),t.exports=r},{112:112,123:123,27:27,28:28}],94:[function(e,t,n){"use strict";function r(e,t,n){i.call(this,e,t,n)}var i=e(99),s={relatedTarget:null};i.augmentClass(r,s),t.exports=r},{99:99}],95:[function(e,t,n){"use strict";function r(e,t,n){i.call(this,e,t,n)}var i=e(93),s={data:null};i.augmentClass(r,s),t.exports=r},{93:93}],96:[function(e,t,n){"use strict";function r(e,t,n){i.call(this,e,t,n)}var i=e(99),s=e(120),o=e(121),u=e(122),a={key:o,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:u,charCode:function(e){return"keypress"===e.type?s(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?s(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};i.augmentClass(r,a),t.exports=r},{120:120,121:121,122:122,99:99}],97:[function(e,t,n){"use strict";function r(e,t,n){i.call(this,e,t,n)}var i=e(99),s=e(102),o=e(122),u={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:o,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+s.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+s.currentScrollTop}};i.augmentClass(r,u),t.exports=r},{102:102,122:122,99:99}],98:[function(e,t,n){"use strict";function r(e,t,n){i.call(this,e,t,n)}var i=e(99),s=e(122),o={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:s};i.augmentClass(r,o),t.exports=r},{122:122,99:99}],99:[function(e,t,n){"use strict";function r(e,t,n){i.call(this,e,t,n)}var i=e(93),s=e(123),o={view:function(e){if(e.view)return e.view;var t=s(e);if(null!=t&&t.window===t)return t;var n=t.ownerDocument;return n?n.defaultView||n.parentWindow:window},detail:function(e){return e.detail||0}};i.augmentClass(r,o),t.exports=r},{123:123,93:93}],100:[function(e,t,n){"use strict";function r(e,t,n){i.call(this,e,t,n)}var i=e(97),s={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};i.augmentClass(r,s),t.exports=r},{97:97}],101:[function(e,t,n){"use strict";var r=e(133),i={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(e,t,n,i,s,o,u,a){r(!this.isInTransaction());var f,l;try{this._isInTransaction=!0,f=!0,this.initializeAll(0),l=e.call(t,n,i,s,o,u,a),f=!1}finally{try{if(f)try{this.closeAll(0)}catch(c){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return l},initializeAll:function(e){for(var t=this.transactionWrappers,n=e;n<t.length;n++){var r=t[n];try{this.wrapperInitData[n]=s.OBSERVED_ERROR,this.wrapperInitData[n]=r.initialize?r.initialize.call(this):null}finally{if(this.wrapperInitData[n]===s.OBSERVED_ERROR)try{this.initializeAll(n+1)}catch(i){}}}},closeAll:function(e){r(this.isInTransaction());for(var t=this.transactionWrappers,n=e;n<t.length;n++){var i,o=t[n],u=this.wrapperInitData[n];try{i=!0,u!==s.OBSERVED_ERROR&&o.close&&o.close.call(this,u),i=!1}finally{if(i)try{this.closeAll(n+1)}catch(a){}}}this.wrapperInitData.length=0}},s={Mixin:i,OBSERVED_ERROR:{}};t.exports=s},{133:133}],102:[function(e,t,n){"use strict";var r={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(e){r.currentScrollLeft=e.x,r.currentScrollTop=e.y}};t.exports=r},{}],103:[function(e,t,n){"use strict";function r(e,t){if(i(null!=t),null==e)return t;var n=Array.isArray(e),r=Array.isArray(t);return n&&r?(e.push.apply(e,t),e):n?(e.push(t),e):r?[e].concat(t):[e,t]}var i=e(133);t.exports=r},{133:133}],104:[function(e,t,n){"use strict";function r(e){for(var t=1,n=0,r=0;r<e.length;r++)t=(t+e.charCodeAt(r))%i,n=(n+t)%i;return t|n<<16}var i=65521;t.exports=r},{}],105:[function(e,t,n){function r(e){return e.replace(i,function(e,t){return t.toUpperCase()})}var i=/-(.)/g;t.exports=r},{}],106:[function(e,t,n){"use strict";function r(e){return i(e.replace(s,"ms-"))}var i=e(105),s=/^-ms-/;t.exports=r},{105:105}],107:[function(e,t,n){function r(e,t){return e&&t?e===t?!0:i(e)?!1:i(t)?r(e,t.parentNode):e.contains?e.contains(t):e.compareDocumentPosition?!!(16&e.compareDocumentPosition(t)):!1:!1}var i=e(137);t.exports=r},{137:137}],108:[function(e,t,n){function r(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function i(e){return r(e)?Array.isArray(e)?e.slice():s(e):[e]}var s=e(148);t.exports=i},{148:148}],109:[function(e,t,n){"use strict";function r(e){var t=s.createFactory(e),n=i.createClass({tagName:e.toUpperCase(),displayName:"ReactFullPageComponent"+e,componentWillUnmount:function(){o(!1)},render:function(){return t(this.props)}});return n}var i=e(33),s=e(55),o=e(133);t.exports=r},{133:133,33:33,55:55}],110:[function(e,t,n){function r(e){var t=e.match(l);return t&&t[1].toLowerCase()}function i(e,t){var n=f;a(!!f);var i=r(e),s=i&&u(i);if(s){n.innerHTML=s[1]+e+s[2];for(var l=s[0];l--;)n=n.lastChild}else n.innerHTML=e;var c=n.getElementsByTagName("script");c.length&&(a(t),o(c).forEach(t));for(var h=o(n.childNodes);n.lastChild;)n.removeChild(n.lastChild);return h}var s=e(21),o=e(108),u=e(125),a=e(133),f=s.canUseDOM?document.createElement("div"):null,l=/^\s*<(\w+)/;t.exports=i},{108:108,125:125,133:133,21:21}],111:[function(e,t,n){"use strict";function r(e,t){var n=null==t||"boolean"==typeof t||""===t;if(n)return"";var r=isNaN(t);return r||0===t||s.hasOwnProperty(e)&&s[e]?""+t:("string"==typeof t&&(t=t.trim()),t+"px")}var i=e(4),s=i.isUnitlessNumber;t.exports=r},{4:4}],112:[function(e,t,n){function r(e){return function(){return e}}function i(){}i.thatReturns=r,i.thatReturnsFalse=r(!1),i.thatReturnsTrue=r(!0),i.thatReturnsNull=r(null),i.thatReturnsThis=function(){return this},i.thatReturnsArgument=function(e){return e},t.exports=i},{}],113:[function(e,t,n){"use strict";var r={};t.exports=r},{}],114:[function(e,t,n){"use strict";function r(e){return s[e]}function i(e){return(""+e).replace(o,r)}var s={"&":"&amp;",">":"&gt;","<":"&lt;",'"':"&quot;","'":"&#x27;"},o=/[&><"']/g;t.exports=i},{}],115:[function(e,t,n){"use strict";function r(e){return null==e?null:u(e)?e:i.has(e)?s.getNodeFromInstance(e):(o(null==e.render||"function"!=typeof e.render),void o(!1))}var i=(e(39),e(65)),s=e(68),o=e(133),u=e(135);e(150),t.exports=r},{133:133,135:135,150:150,39:39,65:65,68:68}],116:[function(e,t,n){"use strict";function r(e,t,n){var r=e,i=!r.hasOwnProperty(n);i&&null!=t&&(r[n]=t)}function i(e){if(null==e)return e;var t={};return s(e,r,t),t}var s=e(149);e(150),t.exports=i},{149:149,150:150}],117:[function(e,t,n){"use strict";function r(e){try{e.focus()}catch(t){}}t.exports=r},{}],118:[function(e,t,n){"use strict";var r=function(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)};t.exports=r},{}],119:[function(e,t,n){function r(){try{return document.activeElement||document.body}catch(e){return document.body}}t.exports=r},{}],120:[function(e,t,n){"use strict";function r(e){var t,n=e.keyCode;return"charCode"in e?(t=e.charCode,0===t&&13===n&&(t=13)):t=n,t>=32||13===t?t:0}t.exports=r},{}],121:[function(e,t,n){"use strict";function r(e){if(e.key){var t=s[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=i(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?o[e.keyCode]||"Unidentified":""}var i=e(120),s={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},o={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};t.exports=r},{120:120}],122:[function(e,t,n){"use strict";function r(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var r=s[e];return r?!!n[r]:!1}function i(e){return r}var s={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};t.exports=i},{}],123:[function(e,t,n){"use strict";function r(e){var t=e.target||e.srcElement||window;return 3===t.nodeType?t.parentNode:t}t.exports=r},{}],124:[function(e,t,n){"use strict";function r(e){var t=e&&(i&&e[i]||e[s]);return"function"==typeof t?t:void 0}var i="function"==typeof Symbol&&Symbol.iterator,s="@@iterator";t.exports=r},{}],125:[function(e,t,n){function r(e){return s(!!o),h.hasOwnProperty(e)||(e="*"),u.hasOwnProperty(e)||("*"===e?o.innerHTML="<link />":o.innerHTML="<"+e+"></"+e+">",u[e]=!o.firstChild),u[e]?h[e]:null}var i=e(21),s=e(133),o=i.canUseDOM?document.createElement("div"):null,u={circle:!0,clipPath:!0,defs:!0,ellipse:!0,g:!0,line:!0,linearGradient:!0,path:!0,polygon:!0,polyline:!0,radialGradient:!0,rect:!0,stop:!0,text:!0},a=[1,'<select multiple="true">',"</select>"],f=[1,"<table>","</table>"],l=[3,"<table><tbody><tr>","</tr></tbody></table>"],c=[1,"<svg>","</svg>"],h={"*":[1,"?<div>","</div>"],area:[1,"<map>","</map>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],legend:[1,"<fieldset>","</fieldset>"],param:[1,"<object>","</object>"],tr:[2,"<table><tbody>","</tbody></table>"],optgroup:a,option:a,caption:f,colgroup:f,tbody:f,tfoot:f,thead:f,td:l,th:l,circle:c,clipPath:c,defs:c,ellipse:c,g:c,line:c,linearGradient:c,path:c,polygon:c,polyline:c,radialGradient:c,rect:c,stop:c,text:c};t.exports=r},{133:133,21:21}],126:[function(e,t,n){"use strict";function r(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function i(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function s(e,t){for(var n=r(e),s=0,u=0;n;){if(3===n.nodeType){if(u=s+n.textContent.length,t>=s&&u>=t)return{node:n,offset:t-s};s=u}n=r(i(n))}}t.exports=s},{}],127:[function(e,t,n){"use strict";function r(e){return e?e.nodeType===i?e.documentElement:e.firstChild:null}var i=9;t.exports=r},{}],128:[function(e,t,n){"use strict";function r(){return!s&&i.canUseDOM&&(s="textContent"in document.documentElement?"textContent":"innerText"),s}var i=e(21),s=null;t.exports=r},{21:21}],129:[function(e,t,n){"use strict";function r(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}t.exports=r},{}],130:[function(e,t,n){function r(e){return e.replace(i,"-$1").toLowerCase()}var i=/([A-Z])/g;t.exports=r},{}],131:[function(e,t,n){"use strict";function r(e){return i(e).replace(s,"-ms-")}var i=e(130),s=/^ms-/;t.exports=r},{130:130}],132:[function(e,t,n){"use strict";function r(e){return"function"==typeof e&&"undefined"!=typeof e.prototype&&"function"==typeof e.prototype.mountComponent&&"function"==typeof e.prototype.receiveComponent}function i(e,t){var n;if((null===e||e===!1)&&(e=o.emptyElement),"object"==typeof e){var i=e;n=t===i.type&&"string"==typeof i.type?u.createInternalComponent(i):r(i.type)?new i.type(i):new l}else"string"==typeof e||"number"==typeof e?n=u.createInstanceForText(e):f(!1);return n.construct(e),n._mountIndex=0,n._mountImage=null,n}var s=e(37),o=e(57),u=e(71),a=e(27),f=e(133),l=(e(150),function(){});a(l.prototype,s.Mixin,{_instantiateReactComponent:i}),t.exports=i},{133:133,150:150,27:27,37:37,57:57,71:71}],133:[function(e,t,n){"use strict";var r=function(e,t,n,r,i,s,o,u){if(!e){var a;if(void 0===t)a=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var f=[n,r,i,s,o,u],l=0;a=new Error("Invariant Violation: "+t.replace(/%s/g,function(){return f[l++]}))}throw a.framesToPop=1,a}};t.exports=r},{}],134:[function(e,t,n){"use strict";function r(e,t){if(!s.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,r=n in document;if(!r){var u=document.createElement("div");u.setAttribute(n,"return;"),r="function"==typeof u[n]}return!r&&i&&"wheel"===e&&(r=document.implementation.hasFeature("Events.wheel","3.0")),r}var i,s=e(21);s.canUseDOM&&(i=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),t.exports=r},{21:21}],135:[function(e,t,n){function r(e){return!!e&&("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName)}t.exports=r},{}],136:[function(e,t,n){"use strict";function r(e){return e&&("INPUT"===e.nodeName&&i[e.type]||"TEXTAREA"===e.nodeName)}var i={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};t.exports=r},{}],137:[function(e,t,n){function r(e){return i(e)&&3==e.nodeType}var i=e(135);t.exports=r},{135:135}],138:[function(e,t,n){"use strict";var r=e(133),i=function(e){var t,n={};r(e instanceof Object&&!Array.isArray(e));for(t in e)e.hasOwnProperty(t)&&(n[t]=t);return n};t.exports=i},{133:133}],139:[function(e,t,n){var r=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};t.exports=r},{}],140:[function(e,t,n){"use strict";function r(e,t,n){if(!e)return null;var r={};for(var s in e)i.call(e,s)&&(r[s]=t.call(n,e[s],s,e));return r}var i=Object.prototype.hasOwnProperty;t.exports=r},{}],141:[function(e,t,n){"use strict";function r(e){var t={};return function(n){return t.hasOwnProperty(n)||(t[n]=e.call(this,n)),t[n]}}t.exports=r},{}],142:[function(e,t,n){"use strict";function r(e){return s(i.isValidElement(e)),e}var i=e(55),s=e(133);t.exports=r},{133:133,55:55}],143:[function(e,t,n){"use strict";function r(e){return'"'+i(e)+'"'}var i=e(114);t.exports=r},{114:114}],144:[function(e,t,n){"use strict";var r=e(21),i=/^[ \r\n\t\f]/,s=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,o=function(e,t){e.innerHTML=t};if("undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction&&(o=function(e,t){MSApp.execUnsafeLocalFunction(function(){e.innerHTML=t})}),r.canUseDOM){var u=document.createElement("div");u.innerHTML=" ",""===u.innerHTML&&(o=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),i.test(t)||"<"===t[0]&&s.test(t)){e.innerHTML=""+t;var n=e.firstChild;1===n.data.length?e.removeChild(n):n.deleteData(0,1)}else e.innerHTML=t})}t.exports=o},{21:21}],145:[function(e,t,n){"use strict";var r=e(21),i=e(114),s=e(144),o=function(e,t){e.textContent=t};r.canUseDOM&&("textContent"in document.documentElement||(o=function(e,t){s(e,i(t))})),t.exports=o},{114:114,144:144,21:21}],146:[function(e,t,n){"use strict";function r(e,t){if(e===t)return!0;var n;for(n in e)if(e.hasOwnProperty(n)&&(!t.hasOwnProperty(n)||e[n]!==t[n]))return!1;for(n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0}t.exports=r},{}],147:[function(e,t,n){"use strict";function r(e,t){if(null!=e&&null!=t){var n=typeof e,r=typeof t;if("string"===n||"number"===n)return"string"===r||"number"===r;if("object"===r&&e.type===t.type&&e.key===t.key){var i=e._owner===t._owner;return i}}return!1}e(150),t.exports=r},{150:150}],148:[function(e,t,n){function r(e){var t=e.length;if(i(!Array.isArray(e)&&("object"==typeof e||"function"==typeof e)),i("number"==typeof t),i(0===t||t-1 in e),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(n){}for(var r=Array(t),s=0;t>s;s++)r[s]=e[s];return r}var i=e(133);t.exports=r},{133:133}],149:[function(e,t,n){"use strict";function r(e){return m[e]}function i(e,t){return e&&null!=e.key?o(e.key):t.toString(36)}function s(e){return(""+e).replace(g,r)}function o(e){return"$"+s(e)}function u(e,t,n,r,s){var a=typeof e;if(("undefined"===a||"boolean"===a)&&(e=null),null===e||"string"===a||"number"===a||f.isValidElement(e))return r(s,e,""===t?d+i(e,0):t,n),1;var c,m,g,y=0;if(Array.isArray(e))for(var b=0;b<e.length;b++)c=e[b],m=(""!==t?t+v:d)+i(c,b),g=n+y,y+=u(c,m,g,r,s);else{var w=h(e);if(w){var E,S=w.call(e);if(w!==e.entries)for(var x=0;!(E=S.next()).done;)c=E.value,m=(""!==t?t+v:d)+i(c,x++),g=n+y,y+=u(c,m,g,r,s);else for(;!(E=S.next()).done;){var T=E.value;T&&(c=T[1],m=(""!==t?t+v:d)+o(T[0])+v+i(c,0),g=n+y,y+=u(c,m,g,r,s))}}else if("object"===a){p(1!==e.nodeType);var N=l.extract(e);for(var C in N)N.hasOwnProperty(C)&&(c=N[C],m=(""!==t?t+v:d)+o(C)+v+i(c,0),g=n+y,y+=u(c,m,g,r,s))}}return y}function a(e,t,n){return null==e?0:u(e,"",0,t,n)}var f=e(55),l=e(61),c=e(64),h=e(124),p=e(133),d=(e(150),c.SEPARATOR),v=":",m={"=":"=0",".":"=1",":":"=2"},g=/[=.:]/g;t.exports=a},{124:124,133:133,150:150,55:55,61:61,64:64}],150:[function(e,t,n){"use strict";var r=e(112),i=r;t.exports=i},{112:112}]},{},[1])(1)}),define("underscore",[],function(){return window._}),define("jquery",[],function(){return window.jQuery}),define("api/ce",["exports","jquery"],function(e,t){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function i(e){var t=baseUrl+"/api/ce/queue";return r["default"].get(t,e)}function s(e){var t=baseUrl+"/api/ce/activity";return r["default"].get(t,e)}function o(e){var t=baseUrl+"/api/ce/task";return r["default"].get(t,{id:e})}function u(e){var t=baseUrl+"/api/ce/cancel";return r["default"].post(t,{id:e}).then(o.bind(null,e))}function a(){var e=baseUrl+"/api/ce/cancel_all";return r["default"].post(e)}function f(e){var t=baseUrl+"/api/ce/component";return r["default"].get(t,{componentId:e})}Object.defineProperty(e,"__esModule",{value:!0}),e.getQueue=i,e.getActivity=s,e.getTask=o,e.cancelTask=u,e.cancelAllTasks=a,e.getTasksForComponent=f;var r=n(t)}),define("apps/background-tasks/constants",["exports"],function(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var t={ALL:"__ALL__",PENDING:"PENDING",IN_PROGRESS:"IN_PROGRESS",SUCCESS:"SUCCESS",FAILED:"FAILED",CANCELED:"CANCELED"};e.STATUSES=t;var n={ALL:"__ALL__",ONLY_CURRENTS:"CURRENTS"};e.CURRENTS=n;var r={ANY:"ANY",TODAY:"TODAY",CUSTOM:"CUSTOM"};e.DATE=r;var i="YYYY-MM-DD";e.DATE_FORMAT=i;var s=250;e.DEBOUNCE_DELAY=s}),define("apps/background-tasks/header",["exports","module","react"],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var i=r(n);t.exports=i["default"].createClass({displayName:"header",render:function(){return i["default"].createElement("header",{className:"page-header"},i["default"].createElement("h1",{className:"page-title"},window.t("background_tasks.page")),i["default"].createElement("p",{className:"page-description"},window.t("background_tasks.page.description")))}})}),define("apps/background-tasks/helpers",["exports"],function(e){"use strict";function r(e,t){return""+e+t}function i(e){if(!e)return"";if(e>=n){var i=Math.round(e/n);return r(i,"min")}if(e>=t){var s=Math.round(e/t);return r(s,"s")}return r(e,"ms")}Object.defineProperty(e,"__esModule",{value:!0}),e.formatDuration=i;var t=1e3,n=60*t}),define("apps/background-tasks/stats",["exports","module","react","./helpers"],function(e,t,n,r){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}var s=i(n);t.exports=s["default"].createClass({displayName:"stats",onPendingCanceled:function(t){t.preventDefault(),this.props.cancelPending()},onFailuresClick:function(t){t.preventDefault(),this.props.showFailures()},renderInProgressDuration:function(){return this.props.inProgressDuration?s["default"].createElement("span",{className:"huge-spacer-left",title:window.t("background_tasks.in_progress_duration"),"data-toggle":"tooltip"},s["default"].createElement("i",{className:"spinner spacer-right",style:{verticalAlign:"text-top"}}),s["default"].createElement("span",{ref:"inProgressDuration",className:"emphasised-measure"},(0,r.formatDuration)(this.props.inProgressDuration))):null},renderPending:function(){return this.props.pendingCount==null?null:this.props.pendingCount>0?s["default"].createElement("span",null,s["default"].createElement("span",{ref:"pendingCount",className:"emphasised-measure"},this.props.pendingCount)," ",window.t("background_tasks.pending"),s["default"].createElement("a",{ref:"cancelPending",onClick:this.onPendingCanceled,className:"icon-delete spacer-left",title:window.t("background_tasks.cancel_all_tasks"),"data-toggle":"tooltip",href:"#"})):s["default"].createElement("span",null,s["default"].createElement("span",{ref:"pendingCount",className:"emphasised-measure"},this.props.pendingCount)," ",window.t("background_tasks.pending"))},renderFailures:function(){return this.props.failuresCount==null?null:this.props.failuresCount>0?s["default"].createElement("span",null,s["default"].createElement("a",{ref:"failureCount",onClick:this.onFailuresClick,className:"emphasised-measure",title:"Count of projects where processing of most recent analysis report failed",href:"#"},this.props.failuresCount)," ",window.t("background_tasks.failures")):s["default"].createElement("span",null,s["default"].createElement("span",{ref:"failureCount",className:"emphasised-measure",title:"Count of projects where processing of most recent analysis report failed"},this.props.failuresCount)," ",window.t("background_tasks.failures"))},render:function(){return s["default"].createElement("section",{className:"big-spacer-top big-spacer-bottom"},s["default"].createElement("span",null,this.renderPending()),s["default"].createElement("span",{className:"huge-spacer-left"},this.renderFailures()),this.renderInProgressDuration())}})}),define("components/shared/radio-toggle",["exports","module","react"],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var i=r(n);t.exports=i["default"].createClass({displayName:"radio-toggle",propTypes:{value:i["default"].PropTypes.string,options:i["default"].PropTypes.array.isRequired,name:i["default"].PropTypes.string.isRequired,onCheck:i["default"].PropTypes.func.isRequired},getDefaultProps:function(){return{disabled:!1,value:null}},onChange:function(t){var n=t.currentTarget.value;this.props.onCheck(n)},renderOption:function(t){var n=t.value===this.props.value,r=this.props.name+"__"+t.value;return i["default"].createElement("li",{key:t.value},i["default"].createElement("input",{onChange:this.onChange,type:"radio",name:this.props.name,value:t.value,id:r,checked:n,disabled:this.props.disabled}),i["default"].createElement("label",{htmlFor:r},t.label))},render:function(){var t=this.props.options.map(this.renderOption);return i["default"].createElement("ul",{className:"radio-toggle"},t)}})}),define("apps/background-tasks/search",["exports","module","jquery","underscore","react","../../components/shared/radio-toggle","./constants"],function(e,t,n,r,i,s,o){"use strict";function u(e){return e&&e.__esModule?e:{"default":e}}var a=u(n),f=u(r),l=u(i),c=u(s);t.exports=l["default"].createClass({displayName:"search",componentDidUpdate:function(){this.attachDatePicker()},componentDidMount:function(){this.attachDatePicker()},componentWillMount:function(){this.onSearch=f["default"].debounce(this.onSearch,o.DEBOUNCE_DELAY)},getCurrentsOptions:function(){return[{value:o.CURRENTS.ALL,label:window.t("background_tasks.currents_filter.ALL")},{value:o.CURRENTS.ONLY_CURRENTS,label:window.t("background_tasks.currents_filter.ONLY_CURRENTS")}]},getStatusOptions:function(){return[{value:o.STATUSES.ALL,label:window.t("background_task.status.ALL")},{value:o.STATUSES.SUCCESS,label:window.t("background_task.status.SUCCESS")},{value:o.STATUSES.FAILED,label:window.t("background_task.status.FAILED")},{value:o.STATUSES.CANCELED,label:window.t("background_task.status.CANCELED")}]},getDateOptions:function(){return[{value:o.DATE.ANY,label:window.t("background_tasks.date_filter.ALL")},{value:o.DATE.TODAY,label:window.t("background_tasks.date_filter.TODAY")},{value:o.DATE.CUSTOM,label:window.t("background_tasks.date_filter.CUSTOM")}]},onDateChange:function(t){if(t===o.DATE.CUSTOM){var n=l["default"].findDOMNode(this.refs.minDate).value,r=l["default"].findDOMNode(this.refs.maxDate).value,i=moment(n,o.DATE_FORMAT,!0),s=moment(r,o.DATE_FORMAT,!0);this.props.onDateChange(t,i.isValid()?i:null,s.isValid()?s:null)}else this.props.onDateChange(t)},onDateInputChange:function(){this.onDateChange(o.DATE.CUSTOM)},attachDatePicker:function(){var t={dateFormat:"yy-mm-dd",changeMonth:!0,changeYear:!0,onSelect:this.onDateInputChange};a["default"].fn.datepicker&&((0,a["default"])(l["default"].findDOMNode(this.refs.minDate)).datepicker(t),(0,a["default"])(l["default"].findDOMNode(this.refs.maxDate)).datepicker(t))},renderCustomDateInput:function(){var t=this.props.dateFilter===o.DATE.CUSTOM,n=t?"spacer-top":"spacer-top hidden";return l["default"].createElement("div",{className:n},"from ",l["default"].createElement("input",{onChange:this.onDateInputChange,ref:"minDate",type:"text"})," to ",l["default"].createElement("input",{onChange:this.onDateInputChange,ref:"maxDate",type:"text"}))},onSearchFormSubmit:function(t){t.preventDefault(),this.onSearch()},onSearch:function(){var t=l["default"].findDOMNode(this.refs.searchInput),n=t.value;this.props.onSearch(n)},renderSearchBox:function(){return this.props.options.componentId?null:l["default"].createElement("form",{onSubmit:this.onSearchFormSubmit,className:"search-box"},l["default"].createElement("button",{className:"search-box-submit button-clean"},l["default"].createElement("i",{className:"icon-search"})),l["default"].createElement("input",{onChange:this.onSearch,ref:"searchInput",className:"search-box-input",type:"search",placeholder:"Search"}))},refresh:function(t){t.preventDefault(),this.props.refresh();var n=t.target;n.disabled=!0,setTimeout(function(){return n.disabled=!1},500)},render:function(){return l["default"].createElement("section",{className:"big-spacer-top big-spacer-bottom"},l["default"].createElement("ul",{className:"list-inline"},l["default"].createElement("li",null,l["default"].createElement(c["default"],{options:this.getStatusOptions(),value:this.props.statusFilter,name:"background-task-status",onCheck:this.props.onStatusChange})),l["default"].createElement("li",null,l["default"].createElement(c["default"],{options:this.getCurrentsOptions(),value:this.props.currentsFilter,name:"background-task-currents",onCheck:this.props.onCurrentsChange})),l["default"].createElement("li",null,l["default"].createElement(c["default"],{options:this.getDateOptions(),value:this.props.dateFilter,name:"background-task-date",onCheck:this.onDateChange}),this.renderCustomDateInput()),l["default"].createElement("li",null,this.renderSearchBox()),l["default"].createElement("li",{className:"pull-right"},l["default"].createElement("button",{onClick:this.refresh,ref:"reloadButton"},window.t("reload")))))}})}),define("moment",[],function(){return window.moment}),define("helpers/Url",["exports"],function(e){"use strict";function t(e){if(typeof e!="string")throw new TypeError("Project ID or KEY should be passed");return window.baseUrl+"/dashboard?id="+encodeURIComponent(e)}Object.defineProperty(e,"__esModule",{value:!0}),e.getProjectUrl=t}),define("components/shared/qualifier-icon",["exports","module","react"],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var i=r(n);t.exports=i["default"].createClass({displayName:"qualifier-icon",render:function(){if(!this.props.qualifier)return null;var t="icon-qualifier-"+this.props.qualifier.toLowerCase();return i["default"].createElement("i",{className:t})}})}),define("components/shared/pending-icon",["exports","module","react"],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var i=r(n);t.exports=i["default"].createClass({displayName:"pending-icon",render:function(){return i["default"].createElement("svg",{width:"16",height:"16",className:"icon-pending"},i["default"].createElement("g",{transform:"matrix(0.0364583,0,0,0.0364583,1,-0.166667)"},i["default"].createElement("path",{d:"M224,136L224,248C224,250.333 223.25,252.25 221.75,253.75C220.25,255.25 218.333,256 216,256L136,256C133.667,256 131.75,255.25 130.25,253.75C128.75,252.25 128,250.333 128,248L128,232C128,229.667 128.75,227.75 130.25,226.25C131.75,224.75 133.667,224 136,224L192,224L192,136C192,133.667 192.75,131.75 194.25,130.25C195.75,128.75 197.667,128 200,128L216,128C218.333,128 220.25,128.75 221.75,130.25C223.25,131.75 224,133.667 224,136ZM328,224C328,199.333 321.917,176.583 309.75,155.75C297.583,134.917 281.083,118.417 260.25,106.25C239.417,94.083 216.667,88 192,88C167.333,88 144.583,94.083 123.75,106.25C102.917,118.417 86.417,134.917 74.25,155.75C62.083,176.583 56,199.333 56,224C56,248.667 62.083,271.417 74.25,292.25C86.417,313.083 102.917,329.583 123.75,341.75C144.583,353.917 167.333,360 192,360C216.667,360 239.417,353.917 260.25,341.75C281.083,329.583 297.583,313.083 309.75,292.25C321.917,271.417 328,248.667 328,224ZM384,224C384,258.833 375.417,290.958 358.25,320.375C341.083,349.792 317.792,373.083 288.375,390.25C258.958,407.417 226.833,416 192,416C157.167,416 125.042,407.417 95.625,390.25C66.208,373.083 42.917,349.792 25.75,320.375C8.583,290.958 0,258.833 0,224C0,189.167 8.583,157.042 25.75,127.625C42.917,98.208 66.208,74.917 95.625,57.75C125.042,40.583 157.167,32 192,32C226.833,32 258.958,40.583 288.375,57.75C317.792,74.917 341.083,98.208 358.25,127.625C375.417,157.042 384,189.167 384,224Z"})))}})}),define("apps/background-tasks/tasks",["exports","module","moment","react","../../helpers/Url","../../components/shared/qualifier-icon","../../components/shared/pending-icon","./constants","./helpers"],function(e,t,n,r,i,s,o,u,a){"use strict";function f(e){return e&&e.__esModule?e:{"default":e}}var l=f(n),c=f(r),h=f(s),p=f(o);t.exports=c["default"].createClass({displayName:"tasks",propTypes:{tasks:c["default"].PropTypes.arrayOf(c["default"].PropTypes.object).isRequired},onTaskCanceled:function(t,n){n.preventDefault(),this.props.onTaskCanceled(t)},renderTaskStatus:function(t){var n=undefined;switch(t.status){case u.STATUSES.PENDING:n=c["default"].createElement(p["default"],null);break;case u.STATUSES.IN_PROGRESS:n=c["default"].createElement("i",{className:"spinner"});break;case u.STATUSES.SUCCESS:n=c["default"].createElement("span",{className:"badge badge-success"},window.t("background_task.status.SUCCESS"));break;case u.STATUSES.FAILED:n=c["default"].createElement("span",{className:"badge badge-danger"},window.t("background_task.status.FAILED"));break;case u.STATUSES.CANCELED:n=c["default"].createElement("span",{className:"badge badge-muted"},window.t("background_task.status.CANCELED"));break;default:n=""}return c["default"].createElement("td",{className:"thin spacer-right",title:window.t("background_task.status",t.status),"data-toggle":"tooltip"},n)},renderTaskComponent:function(t){return t.componentKey?c["default"].createElement("td",null,c["default"].createElement("span",{className:"little-spacer-right"},c["default"].createElement(h["default"],{qualifier:t.componentQualifier})),c["default"].createElement("a",{href:(0,i.getProjectUrl)(t.componentKey)},t.componentName)):c["default"].createElement("td",null,c["default"].createElement("span",{className:"note"},t.id))},renderTaskDate:function(t,n){var r=arguments.length<=2||arguments[2]===undefined?"LLL":arguments[2],i=t[n];return c["default"].createElement("td",{className:"thin nowrap text-right"},i?(0,l["default"])(i).format(r):"")},renderTaskDay:function(t,n){var r=!n||this.isAnotherDay(t.submittedAt,n.submittedAt);return c["default"].createElement("td",{className:"thin nowrap text-right"},r?(0,l["default"])(t.submittedAt).format("LL"):"")},renderTaskExecutionTime:function(t){return c["default"].createElement("td",{className:"thin nowrap text-right"},(0,a.formatDuration)(t.executionTimeMs))},isAnotherDay:function(t,n){return!(0,l["default"])(t).isSame((0,l["default"])(n),"day")},renderCancelButton:function(t){return t.status===u.STATUSES.PENDING?c["default"].createElement("a",{onClick:this.onTaskCanceled.bind(this,t),className:"icon-delete",title:window.t("background_tasks.cancel_task"),"data-toggle":"tooltip",href:"#"}):null},renderLogsLink:function(t){if(t.logs){var n=window.baseUrl+"/api/ce/logs?taskId="+t.id;return c["default"].createElement("a",{target:"_blank",href:n},window.t("background_tasks.logs"))}return null},renderTask:function(t,n,r){var i=n>0?r[n-1]:null;return c["default"].createElement("tr",{key:t.id},this.renderTaskStatus(t),this.renderTaskComponent(t),this.renderTaskDay(t,i),this.renderTaskDate(t,"submittedAt","LTS"),this.renderTaskDate(t,"startedAt","LTS"),this.renderTaskDate(t,"executedAt","LTS"),this.renderTaskExecutionTime(t),c["default"].createElement("td",{className:"thin nowrap text-right"},this.renderLogsLink(t),this.renderCancelButton(t)))},render:function(){if(!this.props.tasks.length)return null;var t=this.props.tasks.map(this.renderTask);return c["default"].createElement("table",{className:"data zebra background-tasks"},c["default"].createElement("thead",null,c["default"].createElement("tr",null,c["default"].createElement("th",null," "),c["default"].createElement("th",null," "),c["default"].createElement("th",null," "),c["default"].createElement("th",null,window.t("background_tasks.table.submitted")),c["default"].createElement("th",null,window.t("background_tasks.table.started")),c["default"].createElement("th",null,window.t("background_tasks.table.finished")),c["default"].createElement("th",null,window.t("background_tasks.table.duration")),c["default"].createElement("th",null," "))),c["default"].createElement("tbody",null,t))}})}),define("components/shared/list-footer",["exports","module","react"],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var i=r(n);t.exports=i["default"].createClass({displayName:"list-footer",propTypes:{count:i["default"].PropTypes.number.isRequired,total:i["default"].PropTypes.number.isRequired,loadMore:i["default"].PropTypes.func},canLoadMore:function(){return typeof this.props.loadMore=="function"},loadMoreProxy:function(t){t.preventDefault(),this.canLoadMore()&&this.props.loadMore()},render:function(){var t=this.props.total>this.props.count,n=i["default"].createElement("a",{onClick:this.loadMoreProxy,className:"spacer-left",href:"#"},"show more");return i["default"].createElement("footer",{className:"spacer-top note text-center"},this.props.count,"/",this.props.total," shown",this.canLoadMore()&&t?n:null)}})}),define("apps/background-tasks/main",["exports","module","underscore","react","../../api/ce","./constants","./header","./stats","./search","./tasks","../../components/shared/list-footer"],function(e,t,n,r,i,s,o,u,a,f,l){"use strict";function h(e){return e&&e.__esModule?e:{"default":e}}var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=h(n),d=h(r),v=h(o),m=h(u),g=h(a),y=h(f),b=h(l),w=200;t.exports=d["default"].createClass({displayName:"main",getInitialState:function(){return{queue:[],activity:[],activityTotal:0,activityPage:1,statusFilter:s.STATUSES.ALL,currentsFilter:s.CURRENTS.ALL,dateFilter:s.DATE.ANY,searchQuery:""}},componentDidMount:function(){this.requestData()},getComponentFilter:function(){return this.props.options.componentId?{componentId:this.props.options.componentId}:{}},getDateFilter:function(){var t="YYYY-MM-DD",n={};switch(this.state.dateFilter){case s.DATE.TODAY:n.minSubmittedAt=moment().startOf("day").format(t);break;case s.DATE.CUSTOM:this.state.minDate&&(n.minSubmittedAt=moment(this.state.minDate).format(t)),this.state.maxDate&&(n.maxExecutedAt=moment(this.state.maxDate).format(t));break;default:}return n},getCurrentFilters:function(){var t={};return this.state.statusFilter!==s.STATUSES.ALL&&(t.status=this.state.statusFilter),this.state.currentsFilter!==s.STATUSES.ALL&&(t.onlyCurrents=!0),this.state.dateFilter!==s.DATE.ANY&&p["default"].extend(t,this.getDateFilter()),this.state.searchQuery&&p["default"].extend(t,{componentQuery:this.state.searchQuery}),t},requestData:function(){this.requestQueue(),this.requestActivity(),this.requestFailures()},requestQueue:function(){var t=this,n=this.getComponentFilter();Object.keys(this.getCurrentFilters()).length?this.setState({queue:[]}):(0,i.getQueue)(n).done(function(e){var n=e.tasks;t.setState({queue:t.orderTasks(n),pendingCount:t.countPending(n),inProgressDuration:t.getInProgressDuration(n)})})},requestActivity:function(){var t=this,n=p["default"].extend(this.getCurrentFilters(),this.getComponentFilter(),{p:this.state.activityPage,ps:w});(0,i.getActivity)(n).done(function(e){var n=e.paging.pageIndex===1?e.tasks:[].concat(t.state.activity,e.tasks);t.setState({activity:t.orderTasks(n),activityTotal:e.paging.total,activityPage:e.paging.pageIndex})})},requestFailures:function(){var t=this,n=p["default"].extend(this.getComponentFilter(),{ps:1,onlyCurrents:!0,status:s.STATUSES.FAILED});(0,i.getActivity)(n).done(function(e){t.setState({failuresCount:e.paging.total})})},countPending:function(t){return p["default"].where(t,{status:s.STATUSES.PENDING}).length},orderTasks:function(t){return p["default"].sortBy(t,function(e){return-moment(e.submittedAt).unix()})},getInProgressDuration:function(t){var n=p["default"].findWhere(t,{status:s.STATUSES.IN_PROGRESS});return n?moment().diff(n.startedAt):null},onStatusChange:function(t){this.setState({statusFilter:t,activityPage:1},this.requestData)},onCurrentsChange:function(t){this.setState({currentsFilter:t,activityPage:1},this.requestData)},onDateChange:function(t,n,r){this.setState({dateFilter:t,minDate:n,maxDate:r,activityPage:1},this.requestData)},onSearch:function(t){this.setState({searchQuery:t},this.requestData)},loadMore:function(){this.setState({activityPage:this.state.activityPage+1},this.requestActivity)},showFailures:function(){this.setState({statusFilter:s.STATUSES.FAILED,currentsFilter:s.CURRENTS.ONLY_CURRENTS,activityPage:1},this.requestActivity)},onTaskCanceled:function(t){(0,i.cancelTask)(t.id).then(this.requestData)},cancelPending:function(){(0,i.cancelAllTasks)().then(this.requestData)},render:function(){return d["default"].createElement("div",{className:"page"},d["default"].createElement(v["default"],null),d["default"].createElement(m["default"],c({},this.state,{cancelPending:this.cancelPending,showFailures:this.showFailures})),d["default"].createElement(g["default"],c({},this.props,this.state,{refresh:this.requestData,onStatusChange:this.onStatusChange,onCurrentsChange:this.onCurrentsChange,onDateChange:this.onDateChange,onSearch:this.onSearch})),d["default"].createElement(y["default"],{tasks:[].concat(this.state.queue,this.state.activity),onTaskCanceled:this.onTaskCanceled}),d["default"].createElement(b["default"],{count:this.state.queue.length+this.state.activity.length,total:this.state.queue.length+this.state.activityTotal,loadMore:this.loadMore}))}})}),define("apps/background-tasks/app",["exports","module","react","./main"],function(e,t,n,r){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}var s=i(n),o=i(r);t.exports={start:function(t){window.requestMessages().done(function(){var e=document.querySelector(t.el);s["default"].render(s["default"].createElement(o["default"],{options:t}),e)})}}});
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( /*#__PURE__*/React.createElement("path", { d: "M18 2.01L6 2c-1.1 0-2 .89-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.11-.9-1.99-2-1.99zM17 20H7c-.55 0-1-.45-1-1v-7.02c0-.55.45-1 1-1h10c.55 0 1 .45 1 1V19c0 .55-.45 1-1 1zm0-11H7c-.55 0-1-.45-1-1V5c0-.55.45-1 1-1h10c.55 0 1 .45 1 1v3c0 .55-.45 1-1 1zM9 5c.55 0 1 .45 1 1v1c0 .55-.45 1-1 1s-1-.45-1-1V6c0-.55.45-1 1-1zm0 7c.55 0 1 .45 1 1v3c0 .55-.45 1-1 1s-1-.45-1-1v-3c0-.55.45-1 1-1z" }), 'KitchenRounded');
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See http://js.arcgis.com/3.15/esri/copyright.txt and http://www.arcgis.com/apps/webappbuilder/copyright.txt for details. //>>built define({"widgets/Search/nls/strings":{_widgetLabel:"Ie\u0161koti",searchResult:"Paie\u0161kos rezultatas",showAllResults:"Rodyti rezultatus, susijusius su ",showAll:"Rodyti paie\u0161kos rezultatus",more:"daugiau",untitled:"Bevardis",_localized:{}}});
/* globals gettext:false, trackEvent:false, jQuery */ /* * users.js * Make public emails clickable. */ (function ($) { function makeEmailsClickable() { // bail if no emails on page var $emails = $('.email'); if ($emails.length === 0) { return false; } $emails.each(function () { var email_val = $(this).text(); var $a = $('<a/>').attr('href', 'mailto:' + email_val) .html(email_val); $(this).html($a); }); } var CONFIRM_TEXT = gettext('WARNING! Are you sure you want to deactivate this user? This cannot be undone!'); function confirmUserDeactivation() { $('.deactivate').submit(function() { return confirm(CONFIRM_TEXT); // eslint-disable-line }); } $(function() { makeEmailsClickable(); confirmUserDeactivation(); if ($('body').is('.register') && window.location.search.indexOf('reg=aaq') > -1) { trackEvent('Ask A Question Flow', 'step 3 confirmed page'); } }); })(jQuery);
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 template from './edit.entity.template.html'; export const graphicalEditEntityState = { name: 'main.graphical.edit.entity', url: '/entity', template: template, };
/* global define */ ;(function (root, factory) { if (typeof define === 'function' && define.amd) { // eslint-disable-line // AMD. Register as an anonymous module. define(['exports', 'echarts'], factory) // eslint-disable-line } else if ( typeof exports === 'object' && typeof exports.nodeName !== 'string' ) { // CommonJS factory(exports, require('echarts')) } else { // Browser globals factory({}, root.echarts) } })(this, (exports, echarts) => { let log = function (msg) { if (typeof console !== 'undefined') { /* eslint-disable */ console && console.error && console.error(msg) } } if (!echarts) { log('ECharts is not Loaded') return } let colorPalette = [ '#c12e34', '#e6b600', '#0098d9', '#2b821d', '#005eaa', '#339ca8', '#cda819', '#32a487', ] let theme = { color: colorPalette, title: { textStyle: { fontWeight: 'normal', }, }, visualMap: { color: ['#1790cf', '#a2d4e6'], }, toolbox: { iconStyle: { normal: { borderColor: '#06467c', }, }, }, tooltip: { backgroundColor: 'rgba(0,0,0,0.6)', }, dataZoom: { dataBackgroundColor: '#dedede', fillerColor: 'rgba(154,217,247,0.2)', handleColor: '#005eaa', }, timeline: { lineStyle: { color: '#005eaa', }, controlStyle: { normal: { color: '#005eaa', borderColor: '#005eaa', }, }, }, candlestick: { itemStyle: { normal: { color: '#c12e34', color0: '#2b821d', lineStyle: { width: 1, color: '#c12e34', color0: '#2b821d', }, }, }, }, graph: { color: colorPalette, }, map: { label: { normal: { textStyle: { color: '#c12e34', }, }, emphasis: { textStyle: { color: '#c12e34', }, }, }, itemStyle: { normal: { borderColor: '#eee', areaColor: '#ddd', }, emphasis: { areaColor: '#e6b600', }, }, }, gauge: { axisLine: { show: true, lineStyle: { color: [ [0.2, '#2b821d'], [0.8, '#005eaa'], [1, '#c12e34'], ], width: 5, }, }, axisTick: { splitNumber: 10, length: 8, lineStyle: { color: 'auto', }, }, axisLabel: { textStyle: { color: 'auto', }, }, splitLine: { length: 12, lineStyle: { color: 'auto', }, }, pointer: { length: '90%', width: 3, color: 'auto', }, title: { textStyle: { color: '#333', }, }, detail: { textStyle: { color: 'auto', }, }, }, } echarts.registerTheme('shine', theme) })
import { graphql, useStaticQuery } from 'gatsby' import Img from 'gatsby-image' import React from 'react' /* * This component is built using `gatsby-image` to automatically serve optimized * images with lazy loading and reduced file sizes. The image is loaded using a * `useStaticQuery`, which allows us to load the image from directly within this * component, rather than having to pass the image data down from pages. * * For more information, see the docs: * - `gatsby-image`: https://gatsby.dev/gatsby-image * - `useStaticQuery`: https://www.gatsbyjs.org/docs/use-static-query/ */ const Avatar = () => { const data = useStaticQuery(graphql` query { placeholderImage: file(relativePath: {eq: "gustavo-kich.jpg"}) { childImageSharp { fluid(maxWidth: 256) { ...GatsbyImageSharpFluid } } } } `) return ( <Img fluid={data.placeholderImage.childImageSharp.fluid} className="rounded-full" alt="Gustavo Kich" /> ) } export default Avatar
(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},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 r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},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="/fela-vue/dist/",n(n.s="f19f")})({"30db":function(e,t,n){"use strict";(function(e,r){n.d(t,"c",function(){return g}),n.d(t,"b",function(){return v}),n.d(t,"a",function(){return b});var i="en",o=!1,s=!1,a=!1,u=!1,c=!1,l=void 0,f="undefined"!==typeof e&&"undefined"!==typeof e.versions&&"undefined"!==typeof e.versions.electron&&"renderer"===e.type;if("object"!==typeof navigator||f){if("object"===typeof e){o="win32"===e.platform,s="darwin"===e.platform,a="linux"===e.platform,l=i,i;var h=Object({NODE_ENV:"production",BASE_URL:"/fela-vue/dist/"})["VSCODE_NLS_CONFIG"];if(h)try{var d=JSON.parse(h),p=d.availableLanguages["*"];l=d.locale,p||i,d._translationsConfigFile}catch(_){}u=!0}}else{var m=navigator.userAgent;o=m.indexOf("Windows")>=0,s=m.indexOf("Macintosh")>=0,a=m.indexOf("Linux")>=0,c=!0,l=navigator.language,l}var g=o,v=c,y="object"===typeof self?self:"object"===typeof r?r:{},b=y}).call(this,n("4362"),n("c8ba"))},4362:function(e,t,n){t.nextTick=function(e){setTimeout(e,0)},t.platform=t.arch=t.execPath=t.title="browser",t.pid=1,t.browser=!0,t.env={},t.argv=[],t.binding=function(e){throw new Error("No such module. (Possibly not yet loaded)")},function(){var e,r="/";t.cwd=function(){return r},t.chdir=function(t){e||(e=n("df7c")),r=e.resolve(t,r)}}(),t.exit=t.kill=t.umask=t.dlopen=t.uptime=t.memoryUsage=t.uvCounters=function(){},t.features={}},5110:function(e,t,n){(function(e){ /*! Copyright (c) 2014 Taylor Hakes Copyright (c) 2014 Forbes Lindesay */ (function(e,t){t()})(0,function(){"use strict";function t(e){var t=this.constructor;return this.then(function(n){return t.resolve(e()).then(function(){return n})},function(n){return t.resolve(e()).then(function(){return t.reject(n)})})}var n=setTimeout;function r(){}function i(e,t){return function(){e.apply(t,arguments)}}function o(e){if(!(this instanceof o))throw new TypeError("Promises must be constructed via new");if("function"!==typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],f(e,this)}function s(e,t){while(3===e._state)e=e._value;0!==e._state?(e._handled=!0,o._immediateFn(function(){var n=1===e._state?t.onFulfilled:t.onRejected;if(null!==n){var r;try{r=n(e._value)}catch(i){return void u(t.promise,i)}a(t.promise,r)}else(1===e._state?a:u)(t.promise,e._value)})):e._deferreds.push(t)}function a(e,t){try{if(t===e)throw new TypeError("A promise cannot be resolved with itself.");if(t&&("object"===typeof t||"function"===typeof t)){var n=t.then;if(t instanceof o)return e._state=3,e._value=t,void c(e);if("function"===typeof n)return void f(i(n,t),e)}e._state=1,e._value=t,c(e)}catch(r){u(e,r)}}function u(e,t){e._state=2,e._value=t,c(e)}function c(e){2===e._state&&0===e._deferreds.length&&o._immediateFn(function(){e._handled||o._unhandledRejectionFn(e._value)});for(var t=0,n=e._deferreds.length;t<n;t++)s(e,e._deferreds[t]);e._deferreds=null}function l(e,t,n){this.onFulfilled="function"===typeof e?e:null,this.onRejected="function"===typeof t?t:null,this.promise=n}function f(e,t){var n=!1;try{e(function(e){n||(n=!0,a(t,e))},function(e){n||(n=!0,u(t,e))})}catch(r){if(n)return;n=!0,u(t,r)}}o.prototype["catch"]=function(e){return this.then(null,e)},o.prototype.then=function(e,t){var n=new this.constructor(r);return s(this,new l(e,t,n)),n},o.prototype["finally"]=t,o.all=function(e){return new o(function(t,n){if(!e||"undefined"===typeof e.length)throw new TypeError("Promise.all accepts an array");var r=Array.prototype.slice.call(e);if(0===r.length)return t([]);var i=r.length;function o(e,s){try{if(s&&("object"===typeof s||"function"===typeof s)){var a=s.then;if("function"===typeof a)return void a.call(s,function(t){o(e,t)},n)}r[e]=s,0===--i&&t(r)}catch(u){n(u)}}for(var s=0;s<r.length;s++)o(s,r[s])})},o.resolve=function(e){return e&&"object"===typeof e&&e.constructor===o?e:new o(function(t){t(e)})},o.reject=function(e){return new o(function(t,n){n(e)})},o.race=function(e){return new o(function(t,n){for(var r=0,i=e.length;r<i;r++)e[r].then(t,n)})},o._immediateFn="function"===typeof setImmediate&&function(e){setImmediate(e)}||function(e){n(e,0)},o._unhandledRejectionFn=function(e){"undefined"!==typeof console&&console&&console.warn("Possible Unhandled Promise Rejection:",e)};var h=function(){if("undefined"!==typeof self)return self;if("undefined"!==typeof window)return window;if("undefined"!==typeof e)return e;throw new Error("unable to locate global object")}();"Promise"in h?h.Promise.prototype["finally"]||(h.Promise.prototype["finally"]=t):h["Promise"]=o})}).call(this,n("c8ba"))},c623:function(e,t,n){"use strict";(function(e){var n,r=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();if("object"===typeof e)n="win32"===e.platform;else if("object"===typeof navigator){var i=navigator.userAgent;n=i.indexOf("Windows")>=0}var o=/^\w[\w\d+.-]*$/,s=/^\//,a=/^\/\//;function u(e){if(e.scheme&&!o.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!s.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(a.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}function c(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==f&&(t=f+t):t=f;break}return t}var l="",f="/",h=/^(([^:\/?#]+?):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,d=function(){function e(e,t,n,r,i){"object"===typeof e?(this.scheme=e.scheme||l,this.authority=e.authority||l,this.path=e.path||l,this.query=e.query||l,this.fragment=e.fragment||l):(this.scheme=e||l,this.authority=t||l,this.path=c(this.scheme,n||l),this.query=r||l,this.fragment=i||l,u(this))}return e.isUri=function(t){return t instanceof e||!!t&&("string"===typeof t.authority&&"string"===typeof t.fragment&&"string"===typeof t.path&&"string"===typeof t.query&&"string"===typeof t.scheme)},Object.defineProperty(e.prototype,"fsPath",{get:function(){return b(this)},enumerable:!0,configurable:!0}),e.prototype.with=function(e){if(!e)return this;var t=e.scheme,n=e.authority,r=e.path,i=e.query,o=e.fragment;return void 0===t?t=this.scheme:null===t&&(t=l),void 0===n?n=this.authority:null===n&&(n=l),void 0===r?r=this.path:null===r&&(r=l),void 0===i?i=this.query:null===i&&(i=l),void 0===o?o=this.fragment:null===o&&(o=l),t===this.scheme&&n===this.authority&&r===this.path&&i===this.query&&o===this.fragment?this:new m(t,n,r,i,o)},e.parse=function(e){var t=h.exec(e);return t?new m(t[2]||l,decodeURIComponent(t[4]||l),decodeURIComponent(t[5]||l),decodeURIComponent(t[7]||l),decodeURIComponent(t[9]||l)):new m(l,l,l,l,l)},e.file=function(e){var t=l;if(n&&(e=e.replace(/\\/g,f)),e[0]===f&&e[1]===f){var r=e.indexOf(f,2);-1===r?(t=e.substring(2),e=f):(t=e.substring(2,r),e=e.substring(r)||f)}return new m("file",t,e,l,l)},e.from=function(e){return new m(e.scheme,e.authority,e.path,e.query,e.fragment)},e.prototype.toString=function(e){return void 0===e&&(e=!1),_(this,e)},e.prototype.toJSON=function(){return this},e.revive=function(t){if(t){if(t instanceof e)return t;var n=new m(t);return n._fsPath=t.fsPath,n._formatted=t.external,n}return t},e}();t["a"]=d;var p,m=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._formatted=null,t._fsPath=null,t}return r(t,e),Object.defineProperty(t.prototype,"fsPath",{get:function(){return this._fsPath||(this._fsPath=b(this)),this._fsPath},enumerable:!0,configurable:!0}),t.prototype.toString=function(e){return void 0===e&&(e=!1),e?_(this,!0):(this._formatted||(this._formatted=_(this,!1)),this._formatted)},t.prototype.toJSON=function(){var e={$mid:1};return this._fsPath&&(e.fsPath=this._fsPath),this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),this.query&&(e.query=this.query),this.fragment&&(e.fragment=this.fragment),e},t}(d),g=(p={},p[58]="%3A",p[47]="%2F",p[63]="%3F",p[35]="%23",p[91]="%5B",p[93]="%5D",p[64]="%40",p[33]="%21",p[36]="%24",p[38]="%26",p[39]="%27",p[40]="%28",p[41]="%29",p[42]="%2A",p[43]="%2B",p[44]="%2C",p[59]="%3B",p[61]="%3D",p[32]="%20",p);function v(e,t){for(var n=void 0,r=-1,i=0;i<e.length;i++){var o=e.charCodeAt(i);if(o>=97&&o<=122||o>=65&&o<=90||o>=48&&o<=57||45===o||46===o||95===o||126===o||t&&47===o)-1!==r&&(n+=encodeURIComponent(e.substring(r,i)),r=-1),void 0!==n&&(n+=e.charAt(i));else{void 0===n&&(n=e.substr(0,i));var s=g[o];void 0!==s?(-1!==r&&(n+=encodeURIComponent(e.substring(r,i)),r=-1),n+=s):-1===r&&(r=i)}}return-1!==r&&(n+=encodeURIComponent(e.substring(r))),void 0!==n?n:e}function y(e){for(var t=void 0,n=0;n<e.length;n++){var r=e.charCodeAt(n);35===r||63===r?(void 0===t&&(t=e.substr(0,n)),t+=g[r]):void 0!==t&&(t+=e[n])}return void 0!==t?t:e}function b(e){var t;return t=e.authority&&e.path.length>1&&"file"===e.scheme?"//"+e.authority+e.path:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?e.path[1].toLowerCase()+e.path.substr(2):e.path,n&&(t=t.replace(/\//g,"\\")),t}function _(e,t){var n=t?y:v,r="",i=e.scheme,o=e.authority,s=e.path,a=e.query,u=e.fragment;if(i&&(r+=i,r+=":"),(o||"file"===i)&&(r+=f,r+=f),o){var c=o.indexOf("@");if(-1!==c){var l=o.substr(0,c);o=o.substr(c+1),c=l.indexOf(":"),-1===c?r+=n(l,!1):(r+=n(l.substr(0,c),!1),r+=":",r+=n(l.substr(c+1),!1)),r+="@"}o=o.toLowerCase(),c=o.indexOf(":"),-1===c?r+=n(o,!1):(r+=n(o.substr(0,c),!1),r+=o.substr(c))}if(s){if(s.length>=3&&47===s.charCodeAt(0)&&58===s.charCodeAt(2)){var h=s.charCodeAt(1);h>=65&&h<=90&&(s="/"+String.fromCharCode(h+32)+":"+s.substr(3))}else if(s.length>=2&&58===s.charCodeAt(1)){h=s.charCodeAt(0);h>=65&&h<=90&&(s=String.fromCharCode(h+32)+":"+s.substr(2))}r+=n(s,!0)}return a&&(r+="?",r+=n(a,!1)),u&&(r+="#",r+=t?u:v(u,!1)),r}}).call(this,n("4362"))},c8ba:function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(r){"object"===typeof window&&(n=window)}e.exports=n},df7c:function(e,t,n){(function(e){function n(e,t){for(var n=0,r=e.length-1;r>=0;r--){var i=e[r];"."===i?e.splice(r,1):".."===i?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n--;n)e.unshift("..");return e}var r=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,i=function(e){return r.exec(e).slice(1)};function o(e,t){if(e.filter)return e.filter(t);for(var n=[],r=0;r<e.length;r++)t(e[r],r,e)&&n.push(e[r]);return n}t.resolve=function(){for(var t="",r=!1,i=arguments.length-1;i>=-1&&!r;i--){var s=i>=0?arguments[i]:e.cwd();if("string"!==typeof s)throw new TypeError("Arguments to path.resolve must be strings");s&&(t=s+"/"+t,r="/"===s.charAt(0))}return t=n(o(t.split("/"),function(e){return!!e}),!r).join("/"),(r?"/":"")+t||"."},t.normalize=function(e){var r=t.isAbsolute(e),i="/"===s(e,-1);return e=n(o(e.split("/"),function(e){return!!e}),!r).join("/"),e||r||(e="."),e&&i&&(e+="/"),(r?"/":"")+e},t.isAbsolute=function(e){return"/"===e.charAt(0)},t.join=function(){var e=Array.prototype.slice.call(arguments,0);return t.normalize(o(e,function(e,t){if("string"!==typeof e)throw new TypeError("Arguments to path.join must be strings");return e}).join("/"))},t.relative=function(e,n){function r(e){for(var t=0;t<e.length;t++)if(""!==e[t])break;for(var n=e.length-1;n>=0;n--)if(""!==e[n])break;return t>n?[]:e.slice(t,n-t+1)}e=t.resolve(e).substr(1),n=t.resolve(n).substr(1);for(var i=r(e.split("/")),o=r(n.split("/")),s=Math.min(i.length,o.length),a=s,u=0;u<s;u++)if(i[u]!==o[u]){a=u;break}var c=[];for(u=a;u<i.length;u++)c.push("..");return c=c.concat(o.slice(a)),c.join("/")},t.sep="/",t.delimiter=":",t.dirname=function(e){var t=i(e),n=t[0],r=t[1];return n||r?(r&&(r=r.substr(0,r.length-1)),n+r):"."},t.basename=function(e,t){var n=i(e)[2];return t&&n.substr(-1*t.length)===t&&(n=n.substr(0,n.length-t.length)),n},t.extname=function(e){return i(e)[3]};var s="b"==="ab".substr(-1)?function(e,t,n){return e.substr(t,n)}:function(e,t,n){return t<0&&(t=e.length+t),e.substr(t,n)}}).call(this,n("4362"))},f19f:function(e,t,n){"use strict";n.r(t);var r=function(){function e(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(function(){if(e.stack)throw new Error(e.message+"\n\n"+e.stack);throw e},0)}}return e.prototype.emit=function(e){this.listeners.forEach(function(t){t(e)})},e.prototype.onUnexpectedError=function(e){this.unexpectedErrorHandler(e),this.emit(e)},e.prototype.onUnexpectedExternalError=function(e){this.unexpectedErrorHandler(e)},e}(),i=new r;function o(e){u(e)||i.onUnexpectedError(e)}function s(e){if(e instanceof Error){var t=e.name,n=e.message,r=e.stacktrace||e.stack;return{$isError:!0,name:t,message:n,stack:r}}return e}var a="Canceled";function u(e){return e instanceof Error&&e.name===a&&e.message===a}function c(e){return e?new Error("Illegal argument: "+e):new Error("Illegal argument")}function l(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];return Array.isArray(e)?(e.forEach(function(e){return e&&e.dispose()}),[]):0===t.length?e?(e.dispose(),e):void 0:(l(e),l(t),[])}function f(e){return{dispose:function(){return l(e)}}}function h(e){return{dispose:function(){e()}}}var d=function(){function e(){this._toDispose=[],this._lifecycle_disposable_isDisposed=!1}return e.prototype.dispose=function(){this._lifecycle_disposable_isDisposed=!0,this._toDispose=l(this._toDispose)},e.prototype._register=function(e){return this._lifecycle_disposable_isDisposed?(console.warn("Registering disposable on object that has already been disposed."),e.dispose()):this._toDispose.push(e),e},e.None=Object.freeze({dispose:function(){}}),e}(),p=(function(){function e(e){this.object=e}e.prototype.dispose=function(){}}(),n("30db"));Object.prototype.hasOwnProperty;function m(e){var t=[],n=Object.getPrototypeOf(e);while(Object.prototype!==n)t=t.concat(Object.getOwnPropertyNames(n)),n=Object.getPrototypeOf(n);return t}var g=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),v="$initialize";var y=function(){function e(e){this._workerId=-1,this._handler=e,this._lastSentReq=0,this._pendingReplies=Object.create(null)}return e.prototype.setWorkerId=function(e){this._workerId=e},e.prototype.sendMessage=function(e,t){var n=this,r=String(++this._lastSentReq);return new Promise(function(i,o){n._pendingReplies[r]={resolve:i,reject:o},n._send({vsWorker:n._workerId,req:r,method:e,args:t})})},e.prototype.handleMessage=function(e){var t;try{t=JSON.parse(e)}catch(n){return}t&&t.vsWorker&&(-1!==this._workerId&&t.vsWorker!==this._workerId||this._handleMessage(t))},e.prototype._handleMessage=function(e){var t=this;if(e.seq){var n=e;if(!this._pendingReplies[n.seq])return void console.warn("Got reply to unknown seq");var r=this._pendingReplies[n.seq];if(delete this._pendingReplies[n.seq],n.err){var i=n.err;return n.err.$isError&&(i=new Error,i.name=n.err.name,i.message=n.err.message,i.stack=n.err.stack),void r.reject(i)}r.resolve(n.res)}else{var o=e,a=o.req,u=this._handler.handleMessage(o.method,o.args);u.then(function(e){t._send({vsWorker:t._workerId,seq:a,res:e,err:void 0})},function(e){e.detail instanceof Error&&(e.detail=s(e.detail)),t._send({vsWorker:t._workerId,seq:a,res:void 0,err:s(e)})})}},e.prototype._send=function(e){var t=JSON.stringify(e);this._handler.sendMessage(t)},e}(),b=(function(e){function t(t,n){var r=e.call(this)||this,i=null;r._worker=r._register(t.create("vs/base/common/worker/simpleWorker",function(e){r._protocol.handleMessage(e)},function(e){i&&i(e)})),r._protocol=new y({sendMessage:function(e){r._worker.postMessage(e)},handleMessage:function(e,t){return Promise.resolve(null)}}),r._protocol.setWorkerId(r._worker.getId());var o=null;"undefined"!==typeof self.require&&"function"===typeof self.require.getConfig?o=self.require.getConfig():"undefined"!==typeof self.requirejs&&(o=self.requirejs.s.contexts._.config),r._onModuleLoaded=r._protocol.sendMessage(v,[r._worker.getId(),n,o]),r._lazyProxy=new Promise(function(e,t){i=t,r._onModuleLoaded.then(function(t){for(var n={},r=0,i=t;r<i.length;r++){var o=i[r];n[o]=a(o,s)}e(n)},function(e){t(e),r._onError("Worker failed to load "+n,e)})});var s=function(e,t){return r._request(e,t)},a=function(e,t){return function(){var n=Array.prototype.slice.call(arguments,0);return t(e,n)}};return r}g(t,e),t.prototype.getProxyObject=function(){return this._lazyProxy},t.prototype._request=function(e,t){var n=this;return new Promise(function(r,i){n._onModuleLoaded.then(function(){n._protocol.sendMessage(e,t).then(r,i)},i)})},t.prototype._onError=function(e,t){console.error(e),console.info(t)}}(d),function(){function e(e,t){var n=this;this._requestHandler=t,this._protocol=new y({sendMessage:function(t){e(t)},handleMessage:function(e,t){return n._handleMessage(e,t)}})}return e.prototype.onmessage=function(e){this._protocol.handleMessage(e)},e.prototype._handleMessage=function(e,t){if(e===v)return this.initialize(t[0],t[1],t[2]);if(!this._requestHandler||"function"!==typeof this._requestHandler[e])return Promise.reject(new Error("Missing requestHandler or method: "+e));try{return Promise.resolve(this._requestHandler[e].apply(this._requestHandler,t))}catch(n){return Promise.reject(n)}},e.prototype.initialize=function(e,t,n){var r=this;if(this._protocol.setWorkerId(e),this._requestHandler){for(var i=[],o=0,s=m(this._requestHandler);o<s.length;o++){var a=s[o];"function"===typeof this._requestHandler[a]&&i.push(a)}return Promise.resolve(i)}return n&&("undefined"!==typeof n.baseUrl&&delete n["baseUrl"],"undefined"!==typeof n.paths&&"undefined"!==typeof n.paths.vs&&delete n.paths["vs"],n.catchError=!0,self.require.config(n)),new Promise(function(e,n){self.require([t],function(){for(var t=[],i=0;i<arguments.length;i++)t[i]=arguments[i];var o=t[0];if(r._requestHandler=o.create(),r._requestHandler){for(var s=[],a=0,u=m(r._requestHandler);a<u.length;a++){var c=u[a];"function"===typeof r._requestHandler[c]&&s.push(c)}e(s)}else n(new Error("No RequestHandler!"))},n)})},e}());function _(e,t){return S(e,t,0,e.length-1,[]),e}function C(e,t,n,r,i,o){for(var s=n,a=r+1,u=n;u<=i;u++)o[u]=e[u];for(u=n;u<=i;u++)s>r?e[u]=o[a++]:a>i?e[u]=o[s++]:t(o[a],o[s])<0?e[u]=o[a++]:e[u]=o[s++]}function S(e,t,n,r,i){if(!(r<=n)){var o=n+(r-n)/2|0;S(e,t,n,o,i),S(e,t,o+1,r,i),t(e[o],e[o+1])<=0||C(e,t,n,o,r,i)}}var E=function(){function e(e,t,n,r){this.originalStart=e,this.originalLength=t,this.modifiedStart=n,this.modifiedLength=r}return e.prototype.getOriginalEnd=function(){return this.originalStart+this.originalLength},e.prototype.getModifiedEnd=function(){return this.modifiedStart+this.modifiedLength},e}();function x(e){return{getLength:function(){return e.length},getElementAtIndex:function(t){return e.charCodeAt(t)}}}function N(e,t,n){return new O(x(e),x(t)).ComputeDiff(n)}var w,A=function(){function e(){}return e.Assert=function(e,t){if(!e)throw new Error(t)},e}(),L=function(){function e(){}return e.Copy=function(e,t,n,r,i){for(var o=0;o<i;o++)n[r+o]=e[t+o]},e}(),k=1447,T=function(){function e(){this.m_changes=[],this.m_originalStart=Number.MAX_VALUE,this.m_modifiedStart=Number.MAX_VALUE,this.m_originalCount=0,this.m_modifiedCount=0}return e.prototype.MarkNextChange=function(){(this.m_originalCount>0||this.m_modifiedCount>0)&&this.m_changes.push(new E(this.m_originalStart,this.m_originalCount,this.m_modifiedStart,this.m_modifiedCount)),this.m_originalCount=0,this.m_modifiedCount=0,this.m_originalStart=Number.MAX_VALUE,this.m_modifiedStart=Number.MAX_VALUE},e.prototype.AddOriginalElement=function(e,t){this.m_originalStart=Math.min(this.m_originalStart,e),this.m_modifiedStart=Math.min(this.m_modifiedStart,t),this.m_originalCount++},e.prototype.AddModifiedElement=function(e,t){this.m_originalStart=Math.min(this.m_originalStart,e),this.m_modifiedStart=Math.min(this.m_modifiedStart,t),this.m_modifiedCount++},e.prototype.getChanges=function(){return(this.m_originalCount>0||this.m_modifiedCount>0)&&this.MarkNextChange(),this.m_changes},e.prototype.getReverseChanges=function(){return(this.m_originalCount>0||this.m_modifiedCount>0)&&this.MarkNextChange(),this.m_changes.reverse(),this.m_changes},e}(),O=function(){function e(e,t,n){void 0===n&&(n=null),this.OriginalSequence=e,this.ModifiedSequence=t,this.ContinueProcessingPredicate=n,this.m_forwardHistory=[],this.m_reverseHistory=[]}return e.prototype.ElementsAreEqual=function(e,t){return this.OriginalSequence.getElementAtIndex(e)===this.ModifiedSequence.getElementAtIndex(t)},e.prototype.OriginalElementsAreEqual=function(e,t){return this.OriginalSequence.getElementAtIndex(e)===this.OriginalSequence.getElementAtIndex(t)},e.prototype.ModifiedElementsAreEqual=function(e,t){return this.ModifiedSequence.getElementAtIndex(e)===this.ModifiedSequence.getElementAtIndex(t)},e.prototype.ComputeDiff=function(e){return this._ComputeDiff(0,this.OriginalSequence.getLength()-1,0,this.ModifiedSequence.getLength()-1,e)},e.prototype._ComputeDiff=function(e,t,n,r,i){var o=[!1],s=this.ComputeDiffRecursive(e,t,n,r,o);return i?this.PrettifyChanges(s):s},e.prototype.ComputeDiffRecursive=function(e,t,n,r,i){i[0]=!1;while(e<=t&&n<=r&&this.ElementsAreEqual(e,n))e++,n++;while(t>=e&&r>=n&&this.ElementsAreEqual(t,r))t--,r--;if(e>t||n>r){var o=void 0;return n<=r?(A.Assert(e===t+1,"originalStart should only be one more than originalEnd"),o=[new E(e,0,n,r-n+1)]):e<=t?(A.Assert(n===r+1,"modifiedStart should only be one more than modifiedEnd"),o=[new E(e,t-e+1,n,0)]):(A.Assert(e===t+1,"originalStart should only be one more than originalEnd"),A.Assert(n===r+1,"modifiedStart should only be one more than modifiedEnd"),o=[]),o}var s=[0],a=[0],u=this.ComputeRecursionPoint(e,t,n,r,s,a,i),c=s[0],l=a[0];if(null!==u)return u;if(!i[0]){var f=this.ComputeDiffRecursive(e,c,n,l,i),h=[];return h=i[0]?[new E(c+1,t-(c+1)+1,l+1,r-(l+1)+1)]:this.ComputeDiffRecursive(c+1,t,l+1,r,i),this.ConcatenateChanges(f,h)}return[new E(e,t-e+1,n,r-n+1)]},e.prototype.WALKTRACE=function(e,t,n,r,i,o,s,a,u,c,l,f,h,d,p,m,g,v){var y,b=null,_=null,C=new T,S=t,x=n,N=h[0]-m[0]-r,w=Number.MIN_VALUE,A=this.m_forwardHistory.length-1;do{y=N+e,y===S||y<x&&u[y-1]<u[y+1]?(l=u[y+1],d=l-N-r,l<w&&C.MarkNextChange(),w=l,C.AddModifiedElement(l+1,d),N=y+1-e):(l=u[y-1]+1,d=l-N-r,l<w&&C.MarkNextChange(),w=l-1,C.AddOriginalElement(l,d+1),N=y-1-e),A>=0&&(u=this.m_forwardHistory[A],e=u[0],S=1,x=u.length-1)}while(--A>=-1);if(b=C.getReverseChanges(),v[0]){var L=h[0]+1,k=m[0]+1;if(null!==b&&b.length>0){var O=b[b.length-1];L=Math.max(L,O.getOriginalEnd()),k=Math.max(k,O.getModifiedEnd())}_=[new E(L,f-L+1,k,p-k+1)]}else{C=new T,S=o,x=s,N=h[0]-m[0]-a,w=Number.MAX_VALUE,A=g?this.m_reverseHistory.length-1:this.m_reverseHistory.length-2;do{y=N+i,y===S||y<x&&c[y-1]>=c[y+1]?(l=c[y+1]-1,d=l-N-a,l>w&&C.MarkNextChange(),w=l+1,C.AddOriginalElement(l+1,d+1),N=y+1-i):(l=c[y-1],d=l-N-a,l>w&&C.MarkNextChange(),w=l,C.AddModifiedElement(l+1,d+1),N=y-1-i),A>=0&&(c=this.m_reverseHistory[A],i=c[0],S=1,x=c.length-1)}while(--A>=-1);_=C.getChanges()}return this.ConcatenateChanges(b,_)},e.prototype.ComputeRecursionPoint=function(e,t,n,r,i,o,s){var a,u=0,c=0,l=0,f=0,h=0,d=0;e--,n--,i[0]=0,o[0]=0,this.m_forwardHistory=[],this.m_reverseHistory=[];var p,m,g=t-e+(r-n),v=g+1,y=new Array(v),b=new Array(v),_=r-n,C=t-e,S=e-n,x=t-r,N=C-_,w=N%2===0;for(y[_]=e,b[C]=t,s[0]=!1,a=1;a<=g/2+1;a++){var A=0,T=0;for(l=this.ClipDiagonalBound(_-a,a,_,v),f=this.ClipDiagonalBound(_+a,a,_,v),p=l;p<=f;p+=2){u=p===l||p<f&&y[p-1]<y[p+1]?y[p+1]:y[p-1]+1,c=u-(p-_)-S,m=u;while(u<t&&c<r&&this.ElementsAreEqual(u+1,c+1))u++,c++;if(y[p]=u,u+c>A+T&&(A=u,T=c),!w&&Math.abs(p-C)<=a-1&&u>=b[p])return i[0]=u,o[0]=c,m<=b[p]&&k>0&&a<=k+1?this.WALKTRACE(_,l,f,S,C,h,d,x,y,b,u,t,i,c,r,o,w,s):null}var O=(A-e+(T-n)-a)/2;if(null!==this.ContinueProcessingPredicate&&!this.ContinueProcessingPredicate(A,this.OriginalSequence,O))return s[0]=!0,i[0]=A,o[0]=T,O>0&&k>0&&a<=k+1?this.WALKTRACE(_,l,f,S,C,h,d,x,y,b,u,t,i,c,r,o,w,s):(e++,n++,[new E(e,t-e+1,n,r-n+1)]);for(h=this.ClipDiagonalBound(C-a,a,C,v),d=this.ClipDiagonalBound(C+a,a,C,v),p=h;p<=d;p+=2){u=p===h||p<d&&b[p-1]>=b[p+1]?b[p+1]-1:b[p-1],c=u-(p-C)-x,m=u;while(u>e&&c>n&&this.ElementsAreEqual(u,c))u--,c--;if(b[p]=u,w&&Math.abs(p-_)<=a&&u<=y[p])return i[0]=u,o[0]=c,m>=y[p]&&k>0&&a<=k+1?this.WALKTRACE(_,l,f,S,C,h,d,x,y,b,u,t,i,c,r,o,w,s):null}if(a<=k){var P=new Array(f-l+2);P[0]=_-l+1,L.Copy(y,l,P,1,f-l+1),this.m_forwardHistory.push(P),P=new Array(d-h+2),P[0]=C-h+1,L.Copy(b,h,P,1,d-h+1),this.m_reverseHistory.push(P)}}return this.WALKTRACE(_,l,f,S,C,h,d,x,y,b,u,t,i,c,r,o,w,s)},e.prototype.PrettifyChanges=function(e){for(var t=0;t<e.length;t++){var n=e[t],r=t<e.length-1?e[t+1].originalStart:this.OriginalSequence.getLength(),i=t<e.length-1?e[t+1].modifiedStart:this.ModifiedSequence.getLength(),o=n.originalLength>0,s=n.modifiedLength>0;while(n.originalStart+n.originalLength<r&&n.modifiedStart+n.modifiedLength<i&&(!o||this.OriginalElementsAreEqual(n.originalStart,n.originalStart+n.originalLength))&&(!s||this.ModifiedElementsAreEqual(n.modifiedStart,n.modifiedStart+n.modifiedLength)))n.originalStart++,n.modifiedStart++;var a=[null];t<e.length-1&&this.ChangesOverlap(e[t],e[t+1],a)&&(e[t]=a[0],e.splice(t+1,1),t--)}for(t=e.length-1;t>=0;t--){n=e[t],r=0,i=0;if(t>0){var u=e[t-1];u.originalLength>0&&(r=u.originalStart+u.originalLength),u.modifiedLength>0&&(i=u.modifiedStart+u.modifiedLength)}o=n.originalLength>0,s=n.modifiedLength>0;for(var c=0,l=this._boundaryScore(n.originalStart,n.originalLength,n.modifiedStart,n.modifiedLength),f=1;;f++){var h=n.originalStart-f,d=n.modifiedStart-f;if(h<r||d<i)break;if(o&&!this.OriginalElementsAreEqual(h,h+n.originalLength))break;if(s&&!this.ModifiedElementsAreEqual(d,d+n.modifiedLength))break;var p=this._boundaryScore(h,n.originalLength,d,n.modifiedLength);p>l&&(l=p,c=f)}n.originalStart-=c,n.modifiedStart-=c}return e},e.prototype._OriginalIsBoundary=function(e){if(e<=0||e>=this.OriginalSequence.getLength()-1)return!0;var t=this.OriginalSequence.getElementAtIndex(e);return"string"===typeof t&&/^\s*$/.test(t)},e.prototype._OriginalRegionIsBoundary=function(e,t){if(this._OriginalIsBoundary(e)||this._OriginalIsBoundary(e-1))return!0;if(t>0){var n=e+t;if(this._OriginalIsBoundary(n-1)||this._OriginalIsBoundary(n))return!0}return!1},e.prototype._ModifiedIsBoundary=function(e){if(e<=0||e>=this.ModifiedSequence.getLength()-1)return!0;var t=this.ModifiedSequence.getElementAtIndex(e);return"string"===typeof t&&/^\s*$/.test(t)},e.prototype._ModifiedRegionIsBoundary=function(e,t){if(this._ModifiedIsBoundary(e)||this._ModifiedIsBoundary(e-1))return!0;if(t>0){var n=e+t;if(this._ModifiedIsBoundary(n-1)||this._ModifiedIsBoundary(n))return!0}return!1},e.prototype._boundaryScore=function(e,t,n,r){var i=this._OriginalRegionIsBoundary(e,t)?1:0,o=this._ModifiedRegionIsBoundary(n,r)?1:0;return i+o},e.prototype.ConcatenateChanges=function(e,t){var n=[];if(0===e.length||0===t.length)return t.length>0?t:e;if(this.ChangesOverlap(e[e.length-1],t[0],n)){var r=new Array(e.length+t.length-1);return L.Copy(e,0,r,0,e.length-1),r[e.length-1]=n[0],L.Copy(t,1,r,e.length,t.length-1),r}r=new Array(e.length+t.length);return L.Copy(e,0,r,0,e.length),L.Copy(t,0,r,e.length,t.length),r},e.prototype.ChangesOverlap=function(e,t,n){if(A.Assert(e.originalStart<=t.originalStart,"Left change is not less than or equal to right change"),A.Assert(e.modifiedStart<=t.modifiedStart,"Left change is not less than or equal to right change"),e.originalStart+e.originalLength>=t.originalStart||e.modifiedStart+e.modifiedLength>=t.modifiedStart){var r=e.originalStart,i=e.originalLength,o=e.modifiedStart,s=e.modifiedLength;return e.originalStart+e.originalLength>=t.originalStart&&(i=t.originalStart+t.originalLength-e.originalStart),e.modifiedStart+e.modifiedLength>=t.modifiedStart&&(s=t.modifiedStart+t.modifiedLength-e.modifiedStart),n[0]=new E(r,i,o,s),!0}return n[0]=null,!1},e.prototype.ClipDiagonalBound=function(e,t,n,r){if(e>=0&&e<r)return e;var i=n,o=r-n-1,s=t%2===0;if(e<0){var a=i%2===0;return s===a?0:1}var u=o%2===0;return s===u?r-1:r-2},e}(),P=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),I={done:!0,value:void 0};(function(e){var t={next:function(){return I}};function n(){return t}function r(e,t,n){return void 0===t&&(t=0),void 0===n&&(n=e.length),{next:function(){return t>=n?I:{done:!1,value:e[t++]}}}}function i(t){return t?Array.isArray(t)?e.fromArray(t):t:e.empty()}function o(e,t){return{next:function(){var n=e.next();return n.done?I:{done:!1,value:t(n.value)}}}}function s(e,t){return{next:function(){while(1){var n=e.next();if(n.done)return I;if(t(n.value))return{done:!1,value:n.value}}}}}function a(e,t){for(var n=e.next();!n.done;n=e.next())t(n.value)}function u(e){var t=[];return a(e,function(e){return t.push(e)}),t}e.empty=n,e.fromArray=r,e.from=i,e.map=o,e.filter=s,e.forEach=a,e.collect=u})(w||(w={}));var M,R=function(){function e(e,t,n,r){void 0===t&&(t=0),void 0===n&&(n=e.length),void 0===r&&(r=t-1),this.items=e,this.start=t,this.end=n,this.index=r}return e.prototype.next=function(){return this.index=Math.min(this.index+1,this.end),this.current()},e.prototype.current=function(){return this.index===this.start-1||this.index===this.end?null:this.items[this.index]},e}(),j=(function(e){function t(t,n,r,i){return void 0===n&&(n=0),void 0===r&&(r=t.length),void 0===i&&(i=n-1),e.call(this,t,n,r,i)||this}P(t,e),t.prototype.current=function(){return e.prototype.current.call(this)},t.prototype.previous=function(){return this.index=Math.max(this.index-1,this.start-1),this.current()},t.prototype.first=function(){return this.index=this.start,this.current()},t.prototype.last=function(){return this.index=this.end-1,this.current()},t.prototype.parent=function(){return null}}(R),function(){function e(e,t){this.iterator=e,this.fn=t}e.prototype.next=function(){return this.fn(this.iterator.next())}}(),function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}()),F=/^\w[\w\d+.-]*$/,V=/^\//,D=/^\/\//,U=!0;function q(e,t){if(!e.scheme){if(t||U)throw new Error('[UriError]: Scheme is missing: {scheme: "", authority: "'+e.authority+'", path: "'+e.path+'", query: "'+e.query+'", fragment: "'+e.fragment+'"}');console.warn('[UriError]: Scheme is missing: {scheme: "", authority: "'+e.authority+'", path: "'+e.path+'", query: "'+e.query+'", fragment: "'+e.fragment+'"}')}if(e.scheme&&!F.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!V.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(D.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}function K(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==B&&(t=B+t):t=B;break}return t}var W="",B="/",$=/^(([^:\/?#]+?):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,Y=function(){function e(e,t,n,r,i,o){"object"===typeof e?(this.scheme=e.scheme||W,this.authority=e.authority||W,this.path=e.path||W,this.query=e.query||W,this.fragment=e.fragment||W):(this.scheme=e||W,this.authority=t||W,this.path=K(this.scheme,n||W),this.query=r||W,this.fragment=i||W,q(this,o))}return e.isUri=function(t){return t instanceof e||!!t&&("string"===typeof t.authority&&"string"===typeof t.fragment&&"string"===typeof t.path&&"string"===typeof t.query&&"string"===typeof t.scheme&&"function"===typeof t.fsPath&&"function"===typeof t.with&&"function"===typeof t.toString)},Object.defineProperty(e.prototype,"fsPath",{get:function(){return Q(this)},enumerable:!0,configurable:!0}),e.prototype.with=function(e){if(!e)return this;var t=e.scheme,n=e.authority,r=e.path,i=e.query,o=e.fragment;return void 0===t?t=this.scheme:null===t&&(t=W),void 0===n?n=this.authority:null===n&&(n=W),void 0===r?r=this.path:null===r&&(r=W),void 0===i?i=this.query:null===i&&(i=W),void 0===o?o=this.fragment:null===o&&(o=W),t===this.scheme&&n===this.authority&&r===this.path&&i===this.query&&o===this.fragment?this:new H(t,n,r,i,o)},e.parse=function(e,t){void 0===t&&(t=!1);var n=$.exec(e);return n?new H(n[2]||W,decodeURIComponent(n[4]||W),decodeURIComponent(n[5]||W),decodeURIComponent(n[7]||W),decodeURIComponent(n[9]||W),t):new H(W,W,W,W,W)},e.file=function(e){var t=W;if(p["c"]&&(e=e.replace(/\\/g,B)),e[0]===B&&e[1]===B){var n=e.indexOf(B,2);-1===n?(t=e.substring(2),e=B):(t=e.substring(2,n),e=e.substring(n)||B)}return new H("file",t,e,W,W)},e.from=function(e){return new H(e.scheme,e.authority,e.path,e.query,e.fragment)},e.prototype.toString=function(e){return void 0===e&&(e=!1),X(this,e)},e.prototype.toJSON=function(){return this},e.revive=function(t){if(t){if(t instanceof e)return t;var n=new H(t);return n._fsPath=t.fsPath,n._formatted=t.external,n}return t},e}(),H=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._formatted=null,t._fsPath=null,t}return j(t,e),Object.defineProperty(t.prototype,"fsPath",{get:function(){return this._fsPath||(this._fsPath=Q(this)),this._fsPath},enumerable:!0,configurable:!0}),t.prototype.toString=function(e){return void 0===e&&(e=!1),e?X(this,!0):(this._formatted||(this._formatted=X(this,!1)),this._formatted)},t.prototype.toJSON=function(){var e={$mid:1};return this._fsPath&&(e.fsPath=this._fsPath),this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),this.query&&(e.query=this.query),this.fragment&&(e.fragment=this.fragment),e},t}(Y),z=(M={},M[58]="%3A",M[47]="%2F",M[63]="%3F",M[35]="%23",M[91]="%5B",M[93]="%5D",M[64]="%40",M[33]="%21",M[36]="%24",M[38]="%26",M[39]="%27",M[40]="%28",M[41]="%29",M[42]="%2A",M[43]="%2B",M[44]="%2C",M[59]="%3B",M[61]="%3D",M[32]="%20",M);function G(e,t){for(var n=void 0,r=-1,i=0;i<e.length;i++){var o=e.charCodeAt(i);if(o>=97&&o<=122||o>=65&&o<=90||o>=48&&o<=57||45===o||46===o||95===o||126===o||t&&47===o)-1!==r&&(n+=encodeURIComponent(e.substring(r,i)),r=-1),void 0!==n&&(n+=e.charAt(i));else{void 0===n&&(n=e.substr(0,i));var s=z[o];void 0!==s?(-1!==r&&(n+=encodeURIComponent(e.substring(r,i)),r=-1),n+=s):-1===r&&(r=i)}}return-1!==r&&(n+=encodeURIComponent(e.substring(r))),void 0!==n?n:e}function J(e){for(var t=void 0,n=0;n<e.length;n++){var r=e.charCodeAt(n);35===r||63===r?(void 0===t&&(t=e.substr(0,n)),t+=z[r]):void 0!==t&&(t+=e[n])}return void 0!==t?t:e}function Q(e){var t;return t=e.authority&&e.path.length>1&&"file"===e.scheme?"//"+e.authority+e.path:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?e.path[1].toLowerCase()+e.path.substr(2):e.path,p["c"]&&(t=t.replace(/\//g,"\\")),t}function X(e,t){var n=t?J:G,r="",i=e.scheme,o=e.authority,s=e.path,a=e.query,u=e.fragment;if(i&&(r+=i,r+=":"),(o||"file"===i)&&(r+=B,r+=B),o){var c=o.indexOf("@");if(-1!==c){var l=o.substr(0,c);o=o.substr(c+1),c=l.indexOf(":"),-1===c?r+=n(l,!1):(r+=n(l.substr(0,c),!1),r+=":",r+=n(l.substr(c+1),!1)),r+="@"}o=o.toLowerCase(),c=o.indexOf(":"),-1===c?r+=n(o,!1):(r+=n(o.substr(0,c),!1),r+=o.substr(c))}if(s){if(s.length>=3&&47===s.charCodeAt(0)&&58===s.charCodeAt(2)){var f=s.charCodeAt(1);f>=65&&f<=90&&(s="/"+String.fromCharCode(f+32)+":"+s.substr(3))}else if(s.length>=2&&58===s.charCodeAt(1)){f=s.charCodeAt(0);f>=65&&f<=90&&(s=String.fromCharCode(f+32)+":"+s.substr(2))}r+=n(s,!0)}return a&&(r+="?",r+=n(a,!1)),u&&(r+="#",r+=t?u:G(u,!1)),r}var Z=function(){function e(e,t){this.lineNumber=e,this.column=t}return e.prototype.with=function(t,n){return void 0===t&&(t=this.lineNumber),void 0===n&&(n=this.column),t===this.lineNumber&&n===this.column?this:new e(t,n)},e.prototype.delta=function(e,t){return void 0===e&&(e=0),void 0===t&&(t=0),this.with(this.lineNumber+e,this.column+t)},e.prototype.equals=function(t){return e.equals(this,t)},e.equals=function(e,t){return!e&&!t||!!e&&!!t&&e.lineNumber===t.lineNumber&&e.column===t.column},e.prototype.isBefore=function(t){return e.isBefore(this,t)},e.isBefore=function(e,t){return e.lineNumber<t.lineNumber||!(t.lineNumber<e.lineNumber)&&e.column<t.column},e.prototype.isBeforeOrEqual=function(t){return e.isBeforeOrEqual(this,t)},e.isBeforeOrEqual=function(e,t){return e.lineNumber<t.lineNumber||!(t.lineNumber<e.lineNumber)&&e.column<=t.column},e.compare=function(e,t){var n=0|e.lineNumber,r=0|t.lineNumber;if(n===r){var i=0|e.column,o=0|t.column;return i-o}return n-r},e.prototype.clone=function(){return new e(this.lineNumber,this.column)},e.prototype.toString=function(){return"("+this.lineNumber+","+this.column+")"},e.lift=function(t){return new e(t.lineNumber,t.column)},e.isIPosition=function(e){return e&&"number"===typeof e.lineNumber&&"number"===typeof e.column},e}(),ee=function(){function e(e,t,n,r){e>n||e===n&&t>r?(this.startLineNumber=n,this.startColumn=r,this.endLineNumber=e,this.endColumn=t):(this.startLineNumber=e,this.startColumn=t,this.endLineNumber=n,this.endColumn=r)}return e.prototype.isEmpty=function(){return e.isEmpty(this)},e.isEmpty=function(e){return e.startLineNumber===e.endLineNumber&&e.startColumn===e.endColumn},e.prototype.containsPosition=function(t){return e.containsPosition(this,t)},e.containsPosition=function(e,t){return!(t.lineNumber<e.startLineNumber||t.lineNumber>e.endLineNumber)&&(!(t.lineNumber===e.startLineNumber&&t.column<e.startColumn)&&!(t.lineNumber===e.endLineNumber&&t.column>e.endColumn))},e.prototype.containsRange=function(t){return e.containsRange(this,t)},e.containsRange=function(e,t){return!(t.startLineNumber<e.startLineNumber||t.endLineNumber<e.startLineNumber)&&(!(t.startLineNumber>e.endLineNumber||t.endLineNumber>e.endLineNumber)&&(!(t.startLineNumber===e.startLineNumber&&t.startColumn<e.startColumn)&&!(t.endLineNumber===e.endLineNumber&&t.endColumn>e.endColumn)))},e.prototype.plusRange=function(t){return e.plusRange(this,t)},e.plusRange=function(t,n){var r,i,o,s;return n.startLineNumber<t.startLineNumber?(r=n.startLineNumber,i=n.startColumn):n.startLineNumber===t.startLineNumber?(r=n.startLineNumber,i=Math.min(n.startColumn,t.startColumn)):(r=t.startLineNumber,i=t.startColumn),n.endLineNumber>t.endLineNumber?(o=n.endLineNumber,s=n.endColumn):n.endLineNumber===t.endLineNumber?(o=n.endLineNumber,s=Math.max(n.endColumn,t.endColumn)):(o=t.endLineNumber,s=t.endColumn),new e(r,i,o,s)},e.prototype.intersectRanges=function(t){return e.intersectRanges(this,t)},e.intersectRanges=function(t,n){var r=t.startLineNumber,i=t.startColumn,o=t.endLineNumber,s=t.endColumn,a=n.startLineNumber,u=n.startColumn,c=n.endLineNumber,l=n.endColumn;return r<a?(r=a,i=u):r===a&&(i=Math.max(i,u)),o>c?(o=c,s=l):o===c&&(s=Math.min(s,l)),r>o?null:r===o&&i>s?null:new e(r,i,o,s)},e.prototype.equalsRange=function(t){return e.equalsRange(this,t)},e.equalsRange=function(e,t){return!!e&&!!t&&e.startLineNumber===t.startLineNumber&&e.startColumn===t.startColumn&&e.endLineNumber===t.endLineNumber&&e.endColumn===t.endColumn},e.prototype.getEndPosition=function(){return new Z(this.endLineNumber,this.endColumn)},e.prototype.getStartPosition=function(){return new Z(this.startLineNumber,this.startColumn)},e.prototype.toString=function(){return"["+this.startLineNumber+","+this.startColumn+" -> "+this.endLineNumber+","+this.endColumn+"]"},e.prototype.setEndPosition=function(t,n){return new e(this.startLineNumber,this.startColumn,t,n)},e.prototype.setStartPosition=function(t,n){return new e(t,n,this.endLineNumber,this.endColumn)},e.prototype.collapseToStart=function(){return e.collapseToStart(this)},e.collapseToStart=function(t){return new e(t.startLineNumber,t.startColumn,t.startLineNumber,t.startColumn)},e.fromPositions=function(t,n){return void 0===n&&(n=t),new e(t.lineNumber,t.column,n.lineNumber,n.column)},e.lift=function(t){return t?new e(t.startLineNumber,t.startColumn,t.endLineNumber,t.endColumn):null},e.isIRange=function(e){return e&&"number"===typeof e.startLineNumber&&"number"===typeof e.startColumn&&"number"===typeof e.endLineNumber&&"number"===typeof e.endColumn},e.areIntersectingOrTouching=function(e,t){return!(e.endLineNumber<t.startLineNumber||e.endLineNumber===t.startLineNumber&&e.endColumn<t.startColumn)&&!(t.endLineNumber<e.startLineNumber||t.endLineNumber===e.startLineNumber&&t.endColumn<e.startColumn)},e.areIntersecting=function(e,t){return!(e.endLineNumber<t.startLineNumber||e.endLineNumber===t.startLineNumber&&e.endColumn<=t.startColumn)&&!(t.endLineNumber<e.startLineNumber||t.endLineNumber===e.startLineNumber&&t.endColumn<=e.startColumn)},e.compareRangesUsingStarts=function(e,t){if(e&&t){var n=0|e.startLineNumber,r=0|t.startLineNumber;if(n===r){var i=0|e.startColumn,o=0|t.startColumn;if(i===o){var s=0|e.endLineNumber,a=0|t.endLineNumber;if(s===a){var u=0|e.endColumn,c=0|t.endColumn;return u-c}return s-a}return i-o}return n-r}var l=e?1:0,f=t?1:0;return l-f},e.compareRangesUsingEnds=function(e,t){return e.endLineNumber===t.endLineNumber?e.endColumn===t.endColumn?e.startLineNumber===t.startLineNumber?e.startColumn-t.startColumn:e.startLineNumber-t.startLineNumber:e.endColumn-t.endColumn:e.endLineNumber-t.endLineNumber},e.spansMultipleLines=function(e){return e.endLineNumber>e.startLineNumber},e}();function te(e){for(var t=0,n=e.length;t<n;t++){var r=e.charCodeAt(t);if(32!==r&&9!==r)return t}return-1}function ne(e,t){void 0===t&&(t=e.length-1);for(var n=t;n>=0;n--){var r=e.charCodeAt(n);if(32!==r&&9!==r)return n}return-1}String.fromCharCode(65279);var re=5e3,ie=3;function oe(e,t,n,r){var i=new O(e,t,n);return i.ComputeDiff(r)}var se=function(){function e(t){for(var n=[],r=[],i=0,o=t.length;i<o;i++)n[i]=e._getFirstNonBlankColumn(t[i],1),r[i]=e._getLastNonBlankColumn(t[i],1);this._lines=t,this._startColumns=n,this._endColumns=r}return e.prototype.getLength=function(){return this._lines.length},e.prototype.getElementAtIndex=function(e){return this._lines[e].substring(this._startColumns[e]-1,this._endColumns[e]-1)},e.prototype.getStartLineNumber=function(e){return e+1},e.prototype.getEndLineNumber=function(e){return e+1},e._getFirstNonBlankColumn=function(e,t){var n=te(e);return-1===n?t:n+1},e._getLastNonBlankColumn=function(e,t){var n=ne(e);return-1===n?t:n+2},e.prototype.getCharSequence=function(e,t,n){for(var r=[],i=[],o=[],s=0,a=t;a<=n;a++)for(var u=this._lines[a],c=e?this._startColumns[a]:1,l=e?this._endColumns[a]:u.length+1,f=c;f<l;f++)r[s]=u.charCodeAt(f-1),i[s]=a+1,o[s]=f,s++;return new ae(r,i,o)},e}(),ae=function(){function e(e,t,n){this._charCodes=e,this._lineNumbers=t,this._columns=n}return e.prototype.getLength=function(){return this._charCodes.length},e.prototype.getElementAtIndex=function(e){return this._charCodes[e]},e.prototype.getStartLineNumber=function(e){return this._lineNumbers[e]},e.prototype.getStartColumn=function(e){return this._columns[e]},e.prototype.getEndLineNumber=function(e){return this._lineNumbers[e]},e.prototype.getEndColumn=function(e){return this._columns[e]+1},e}(),ue=function(){function e(e,t,n,r,i,o,s,a){this.originalStartLineNumber=e,this.originalStartColumn=t,this.originalEndLineNumber=n,this.originalEndColumn=r,this.modifiedStartLineNumber=i,this.modifiedStartColumn=o,this.modifiedEndLineNumber=s,this.modifiedEndColumn=a}return e.createFromDiffChange=function(t,n,r){var i,o,s,a,u,c,l,f;return 0===t.originalLength?(i=0,o=0,s=0,a=0):(i=n.getStartLineNumber(t.originalStart),o=n.getStartColumn(t.originalStart),s=n.getEndLineNumber(t.originalStart+t.originalLength-1),a=n.getEndColumn(t.originalStart+t.originalLength-1)),0===t.modifiedLength?(u=0,c=0,l=0,f=0):(u=r.getStartLineNumber(t.modifiedStart),c=r.getStartColumn(t.modifiedStart),l=r.getEndLineNumber(t.modifiedStart+t.modifiedLength-1),f=r.getEndColumn(t.modifiedStart+t.modifiedLength-1)),new e(i,o,s,a,u,c,l,f)},e}();function ce(e){if(e.length<=1)return e;for(var t=[e[0]],n=t[0],r=1,i=e.length;r<i;r++){var o=e[r],s=o.originalStart-(n.originalStart+n.originalLength),a=o.modifiedStart-(n.modifiedStart+n.modifiedLength),u=Math.min(s,a);u<ie?(n.originalLength=o.originalStart+o.originalLength-n.originalStart,n.modifiedLength=o.modifiedStart+o.modifiedLength-n.modifiedStart):(t.push(o),n=o)}return t}var le=function(){function e(e,t,n,r,i){this.originalStartLineNumber=e,this.originalEndLineNumber=t,this.modifiedStartLineNumber=n,this.modifiedEndLineNumber=r,this.charChanges=i}return e.createFromDiffResult=function(t,n,r,i,o,s,a){var u,c,l,f,h=void 0;if(0===n.originalLength?(u=r.getStartLineNumber(n.originalStart)-1,c=0):(u=r.getStartLineNumber(n.originalStart),c=r.getEndLineNumber(n.originalStart+n.originalLength-1)),0===n.modifiedLength?(l=i.getStartLineNumber(n.modifiedStart)-1,f=0):(l=i.getStartLineNumber(n.modifiedStart),f=i.getEndLineNumber(n.modifiedStart+n.modifiedLength-1)),s&&0!==n.originalLength&&0!==n.modifiedLength&&o()){var d=r.getCharSequence(t,n.originalStart,n.originalStart+n.originalLength-1),p=i.getCharSequence(t,n.modifiedStart,n.modifiedStart+n.modifiedLength-1),m=oe(d,p,o,!0);a&&(m=ce(m)),h=[];for(var g=0,v=m.length;g<v;g++)h.push(ue.createFromDiffChange(m[g],d,p))}return new e(u,c,l,f,h)},e}(),fe=function(){function e(e,t,n){this.shouldComputeCharChanges=n.shouldComputeCharChanges,this.shouldPostProcessCharChanges=n.shouldPostProcessCharChanges,this.shouldIgnoreTrimWhitespace=n.shouldIgnoreTrimWhitespace,this.shouldMakePrettyDiff=n.shouldMakePrettyDiff,this.maximumRunTimeMs=re,this.originalLines=e,this.modifiedLines=t,this.original=new se(e),this.modified=new se(t)}return e.prototype.computeDiff=function(){if(1===this.original.getLength()&&0===this.original.getElementAtIndex(0).length)return[{originalStartLineNumber:1,originalEndLineNumber:1,modifiedStartLineNumber:1,modifiedEndLineNumber:this.modified.getLength(),charChanges:[{modifiedEndColumn:0,modifiedEndLineNumber:0,modifiedStartColumn:0,modifiedStartLineNumber:0,originalEndColumn:0,originalEndLineNumber:0,originalStartColumn:0,originalStartLineNumber:0}]}];if(1===this.modified.getLength()&&0===this.modified.getElementAtIndex(0).length)return[{originalStartLineNumber:1,originalEndLineNumber:this.original.getLength(),modifiedStartLineNumber:1,modifiedEndLineNumber:1,charChanges:[{modifiedEndColumn:0,modifiedEndLineNumber:0,modifiedStartColumn:0,modifiedStartLineNumber:0,originalEndColumn:0,originalEndLineNumber:0,originalStartColumn:0,originalStartLineNumber:0}]}];this.computationStartTime=(new Date).getTime();var e=oe(this.original,this.modified,this._continueProcessingPredicate.bind(this),this.shouldMakePrettyDiff);if(this.shouldIgnoreTrimWhitespace){for(var t=[],n=0,r=e.length;n<r;n++)t.push(le.createFromDiffResult(this.shouldIgnoreTrimWhitespace,e[n],this.original,this.modified,this._continueProcessingPredicate.bind(this),this.shouldComputeCharChanges,this.shouldPostProcessCharChanges));return t}for(var i=[],o=0,s=0,a=(n=-1,e.length);n<a;n++){var u=n+1<a?e[n+1]:null,c=u?u.originalStart:this.originalLines.length,l=u?u.modifiedStart:this.modifiedLines.length;while(o<c&&s<l){var f=this.originalLines[o],h=this.modifiedLines[s];if(f!==h){var d=se._getFirstNonBlankColumn(f,1),p=se._getFirstNonBlankColumn(h,1);while(d>1&&p>1){var m=f.charCodeAt(d-2),g=h.charCodeAt(p-2);if(m!==g)break;d--,p--}(d>1||p>1)&&this._pushTrimWhitespaceCharChange(i,o+1,1,d,s+1,1,p);var v=se._getLastNonBlankColumn(f,1),y=se._getLastNonBlankColumn(h,1),b=f.length+1,_=h.length+1;while(v<b&&y<_){m=f.charCodeAt(v-1),g=f.charCodeAt(y-1);if(m!==g)break;v++,y++}(v<b||y<_)&&this._pushTrimWhitespaceCharChange(i,o+1,v,b,s+1,y,_)}o++,s++}u&&(i.push(le.createFromDiffResult(this.shouldIgnoreTrimWhitespace,u,this.original,this.modified,this._continueProcessingPredicate.bind(this),this.shouldComputeCharChanges,this.shouldPostProcessCharChanges)),o+=u.originalLength,s+=u.modifiedLength)}return i},e.prototype._pushTrimWhitespaceCharChange=function(e,t,n,r,i,o,s){if(!this._mergeTrimWhitespaceCharChange(e,t,n,r,i,o,s)){var a=void 0;this.shouldComputeCharChanges&&(a=[new ue(t,n,t,r,i,o,i,s)]),e.push(new le(t,t,i,i,a))}},e.prototype._mergeTrimWhitespaceCharChange=function(e,t,n,r,i,o,s){var a=e.length;if(0===a)return!1;var u=e[a-1];return 0!==u.originalEndLineNumber&&0!==u.modifiedEndLineNumber&&(u.originalEndLineNumber+1===t&&u.modifiedEndLineNumber+1===i&&(u.originalEndLineNumber=t,u.modifiedEndLineNumber=i,this.shouldComputeCharChanges&&u.charChanges.push(new ue(t,n,t,r,i,o,i,s)),!0))},e.prototype._continueProcessingPredicate=function(){if(0===this.maximumRunTimeMs)return!0;var e=(new Date).getTime();return e-this.computationStartTime<this.maximumRunTimeMs},e}(),he=function(){function e(e,t,n){for(var r=new Uint8Array(e*t),i=0,o=e*t;i<o;i++)r[i]=n;this._data=r,this.rows=e,this.cols=t}return e.prototype.get=function(e,t){return this._data[e*this.cols+t]},e.prototype.set=function(e,t,n){this._data[e*this.cols+t]=n},e}();function de(e){return e<0?0:e>255?255:0|e}function pe(e){return e<0?0:e>4294967295?4294967295:0|e}var me=function(){function e(e,t){this.index=e,this.remainder=t}return e}(),ge=function(){function e(e){this.values=e,this.prefixSum=new Uint32Array(e.length),this.prefixSumValidIndex=new Int32Array(1),this.prefixSumValidIndex[0]=-1}return e.prototype.getCount=function(){return this.values.length},e.prototype.insertValues=function(e,t){e=pe(e);var n=this.values,r=this.prefixSum,i=t.length;return 0!==i&&(this.values=new Uint32Array(n.length+i),this.values.set(n.subarray(0,e),0),this.values.set(n.subarray(e),e+i),this.values.set(t,e),e-1<this.prefixSumValidIndex[0]&&(this.prefixSumValidIndex[0]=e-1),this.prefixSum=new Uint32Array(this.values.length),this.prefixSumValidIndex[0]>=0&&this.prefixSum.set(r.subarray(0,this.prefixSumValidIndex[0]+1)),!0)},e.prototype.changeValue=function(e,t){return e=pe(e),t=pe(t),this.values[e]!==t&&(this.values[e]=t,e-1<this.prefixSumValidIndex[0]&&(this.prefixSumValidIndex[0]=e-1),!0)},e.prototype.removeValues=function(e,t){e=pe(e),t=pe(t);var n=this.values,r=this.prefixSum;if(e>=n.length)return!1;var i=n.length-e;return t>=i&&(t=i),0!==t&&(this.values=new Uint32Array(n.length-t),this.values.set(n.subarray(0,e),0),this.values.set(n.subarray(e+t),e),this.prefixSum=new Uint32Array(this.values.length),e-1<this.prefixSumValidIndex[0]&&(this.prefixSumValidIndex[0]=e-1),this.prefixSumValidIndex[0]>=0&&this.prefixSum.set(r.subarray(0,this.prefixSumValidIndex[0]+1)),!0)},e.prototype.getTotalValue=function(){return 0===this.values.length?0:this._getAccumulatedValue(this.values.length-1)},e.prototype.getAccumulatedValue=function(e){return e<0?0:(e=pe(e),this._getAccumulatedValue(e))},e.prototype._getAccumulatedValue=function(e){if(e<=this.prefixSumValidIndex[0])return this.prefixSum[e];var t=this.prefixSumValidIndex[0]+1;0===t&&(this.prefixSum[0]=this.values[0],t++),e>=this.values.length&&(e=this.values.length-1);for(var n=t;n<=e;n++)this.prefixSum[n]=this.prefixSum[n-1]+this.values[n];return this.prefixSumValidIndex[0]=Math.max(this.prefixSumValidIndex[0],e),this.prefixSum[e]},e.prototype.getIndexOf=function(e){e=Math.floor(e),this.getTotalValue();var t=0,n=this.values.length-1,r=0,i=0,o=0;while(t<=n)if(r=t+(n-t)/2|0,i=this.prefixSum[r],o=i-this.values[r],e<o)n=r-1;else{if(!(e>=i))break;t=r+1}return new me(r,e-o)},e}(),ve=(function(){function e(e){this._cacheAccumulatedValueStart=0,this._cache=null,this._actual=new ge(e),this._bustCache()}e.prototype._bustCache=function(){this._cacheAccumulatedValueStart=0,this._cache=null},e.prototype.insertValues=function(e,t){this._actual.insertValues(e,t)&&this._bustCache()},e.prototype.changeValue=function(e,t){this._actual.changeValue(e,t)&&this._bustCache()},e.prototype.removeValues=function(e,t){this._actual.removeValues(e,t)&&this._bustCache()},e.prototype.getTotalValue=function(){return this._actual.getTotalValue()},e.prototype.getAccumulatedValue=function(e){return this._actual.getAccumulatedValue(e)},e.prototype.getIndexOf=function(e){if(e=Math.floor(e),null!==this._cache){var t=e-this._cacheAccumulatedValueStart;if(t>=0&&t<this._cache.length)return this._cache[t]}return this._actual.getIndexOf(e)},e.prototype.warmUpCache=function(e,t){for(var n=[],r=e;r<=t;r++)n[r-e]=this.getIndexOf(r);this._cache=n,this._cacheAccumulatedValueStart=e}}(),function(){function e(e,t,n,r){this._uri=e,this._lines=t,this._eol=n,this._versionId=r,this._lineStarts=null}return e.prototype.dispose=function(){this._lines.length=0},e.prototype.getText=function(){return this._lines.join(this._eol)},e.prototype.onEvents=function(e){e.eol&&e.eol!==this._eol&&(this._eol=e.eol,this._lineStarts=null);for(var t=e.changes,n=0,r=t;n<r.length;n++){var i=r[n];this._acceptDeleteRange(i.range),this._acceptInsertText(new Z(i.range.startLineNumber,i.range.startColumn),i.text)}this._versionId=e.versionId},e.prototype._ensureLineStarts=function(){if(!this._lineStarts){for(var e=this._eol.length,t=this._lines.length,n=new Uint32Array(t),r=0;r<t;r++)n[r]=this._lines[r].length+e;this._lineStarts=new ge(n)}},e.prototype._setLineText=function(e,t){this._lines[e]=t,this._lineStarts&&this._lineStarts.changeValue(e,this._lines[e].length+this._eol.length)},e.prototype._acceptDeleteRange=function(e){if(e.startLineNumber!==e.endLineNumber)this._setLineText(e.startLineNumber-1,this._lines[e.startLineNumber-1].substring(0,e.startColumn-1)+this._lines[e.endLineNumber-1].substring(e.endColumn-1)),this._lines.splice(e.startLineNumber,e.endLineNumber-e.startLineNumber),this._lineStarts&&this._lineStarts.removeValues(e.startLineNumber,e.endLineNumber-e.startLineNumber);else{if(e.startColumn===e.endColumn)return;this._setLineText(e.startLineNumber-1,this._lines[e.startLineNumber-1].substring(0,e.startColumn-1)+this._lines[e.startLineNumber-1].substring(e.endColumn-1))}},e.prototype._acceptInsertText=function(e,t){if(0!==t.length){var n=t.split(/\r\n|\r|\n/);if(1!==n.length){n[n.length-1]+=this._lines[e.lineNumber-1].substring(e.column-1),this._setLineText(e.lineNumber-1,this._lines[e.lineNumber-1].substring(0,e.column-1)+n[0]);for(var r=new Uint32Array(n.length-1),i=1;i<n.length;i++)this._lines.splice(e.lineNumber+i-1,0,n[i]),r[i-1]=n[i].length+this._eol.length;this._lineStarts&&this._lineStarts.insertValues(e.lineNumber,r)}else this._setLineText(e.lineNumber-1,this._lines[e.lineNumber-1].substring(0,e.column-1)+n[0]+this._lines[e.lineNumber-1].substring(e.column-1))}},e}()),ye="`~!@#$%^&*()-=+[{]}\\|;:'\",.<>/?";function be(e){void 0===e&&(e="");for(var t="(-?\\d*\\.\\d\\w*)|([^",n=0,r=ye;n<r.length;n++){var i=r[n];e.indexOf(i)>=0||(t+="\\"+i)}return t+="\\s]+)",new RegExp(t,"g")}var _e=be();function Ce(e){var t=_e;if(e&&e instanceof RegExp)if(e.global)t=e;else{var n="g";e.ignoreCase&&(n+="i"),e.multiline&&(n+="m"),e.unicode&&(n+="u"),t=new RegExp(e.source,n)}return t.lastIndex=0,t}function Se(e,t,n,r){var i,o=e-1-r,s=n.lastIndexOf(" ",o-1)+1;t.lastIndex=s;while(i=t.exec(n)){var a=i.index||0;if(a<=o&&t.lastIndex>=o)return{word:i[0],startColumn:r+1+a,endColumn:r+1+t.lastIndex}}return null}function Ee(e,t,n,r){var i,o=e-1-r;t.lastIndex=0;while(i=t.exec(n)){var s=i.index||0;if(s>o)return null;if(t.lastIndex>=o)return{word:i[0],startColumn:r+1+s,endColumn:r+1+t.lastIndex}}return null}function xe(e,t,n,r){t.lastIndex=0;var i=t.exec(n);if(!i)return null;var o=i[0].indexOf(" ")>=0?Ee(e,t,n,r):Se(e,t,n,r);return t.lastIndex=0,o}var Ne=function(){function e(t){var n=de(t);this._defaultValue=n,this._asciiMap=e._createAsciiMap(n),this._map=new Map}return e._createAsciiMap=function(e){for(var t=new Uint8Array(256),n=0;n<256;n++)t[n]=e;return t},e.prototype.set=function(e,t){var n=de(t);e>=0&&e<256?this._asciiMap[e]=n:this._map.set(e,n)},e.prototype.get=function(e){return e>=0&&e<256?this._asciiMap[e]:this._map.get(e)||this._defaultValue},e}(),we=(function(){function e(){this._actual=new Ne(0)}e.prototype.add=function(e){this._actual.set(e,1)},e.prototype.has=function(e){return 1===this._actual.get(e)}}(),function(){function e(e){for(var t=0,n=0,r=0,i=e.length;r<i;r++){var o=e[r],s=o[0],a=o[1],u=o[2];a>t&&(t=a),s>n&&(n=s),u>n&&(n=u)}t++,n++;var c=new he(n,t,0);for(r=0,i=e.length;r<i;r++){var l=e[r];s=l[0],a=l[1],u=l[2];c.set(s,a,u)}this._states=c,this._maxCharCode=t}return e.prototype.nextState=function(e,t){return t<0||t>=this._maxCharCode?0:this._states.get(e,t)},e}()),Ae=null;function Le(){return null===Ae&&(Ae=new we([[1,104,2],[1,72,2],[1,102,6],[1,70,6],[2,116,3],[2,84,3],[3,116,4],[3,84,4],[4,112,5],[4,80,5],[5,115,9],[5,83,9],[5,58,10],[6,105,7],[6,73,7],[7,108,8],[7,76,8],[8,101,9],[8,69,9],[9,58,10],[10,47,11],[11,47,12]])),Ae}var ke=null;function Te(){if(null===ke){ke=new Ne(0);for(var e=" \t<>'\"、。。、,.:;?!@#$%&*‘“〈《「『【〔([{「」}])〕】』」》〉”’`~…",t=0;t<e.length;t++)ke.set(e.charCodeAt(t),1);var n=".,;";for(t=0;t<n.length;t++)ke.set(n.charCodeAt(t),2)}return ke}var Oe=function(){function e(){}return e._createLink=function(e,t,n,r,i){var o=i-1;do{var s=t.charCodeAt(o),a=e.get(s);if(2!==a)break;o--}while(o>r);if(r>0){var u=t.charCodeAt(r-1),c=t.charCodeAt(o);(40===u&&41===c||91===u&&93===c||123===u&&125===c)&&o--}return{range:{startLineNumber:n,startColumn:r+1,endLineNumber:n,endColumn:o+2},url:t.substring(r,o+1)}},e.computeLinks=function(t,n){void 0===n&&(n=Le());for(var r=Te(),i=[],o=1,s=t.getLineCount();o<=s;o++){var a=t.getLineContent(o),u=a.length,c=0,l=0,f=0,h=1,d=!1,p=!1,m=!1;while(c<u){var g=!1,v=a.charCodeAt(c);if(13===h){var y=void 0;switch(v){case 40:d=!0,y=0;break;case 41:y=d?0:1;break;case 91:p=!0,y=0;break;case 93:y=p?0:1;break;case 123:m=!0,y=0;break;case 125:y=m?0:1;break;case 39:y=34===f||96===f?0:1;break;case 34:y=39===f||96===f?0:1;break;case 96:y=39===f||34===f?0:1;break;default:y=r.get(v)}1===y&&(i.push(e._createLink(r,a,o,l,c)),g=!0)}else if(12===h){y=void 0;91===v?(p=!0,y=0):y=r.get(v),1===y?g=!0:h=13}else h=n.nextState(h,v),0===h&&(g=!0);g&&(h=1,d=!1,p=!1,m=!1,l=c+1,f=v),c++}13===h&&i.push(e._createLink(r,a,o,l,u))}return i},e}();function Pe(e){return e&&"function"===typeof e.getLineCount&&"function"===typeof e.getLineContent?Oe.computeLinks(e):[]}var Ie=function(){function e(){this._defaultValueSet=[["true","false"],["True","False"],["Private","Public","Friend","ReadOnly","Partial","Protected","WriteOnly"],["public","protected","private"]]}return e.prototype.navigateValueSet=function(e,t,n,r,i){if(e&&t){var o=this.doNavigateValueSet(t,i);if(o)return{range:e,value:o}}if(n&&r){o=this.doNavigateValueSet(r,i);if(o)return{range:n,value:o}}return null},e.prototype.doNavigateValueSet=function(e,t){var n=this.numberReplace(e,t);return null!==n?n:this.textReplace(e,t)},e.prototype.numberReplace=function(e,t){var n=Math.pow(10,e.length-(e.lastIndexOf(".")+1)),r=Number(e),i=parseFloat(e);return isNaN(r)||isNaN(i)||r!==i?null:0!==r||t?(r=Math.floor(r*n),r+=t?n:-n,String(r/n)):null},e.prototype.textReplace=function(e,t){return this.valueSetsReplace(this._defaultValueSet,e,t)},e.prototype.valueSetsReplace=function(e,t,n){for(var r=null,i=0,o=e.length;null===r&&i<o;i++)r=this.valueSetReplace(e[i],t,n);return r},e.prototype.valueSetReplace=function(e,t,n){var r=e.indexOf(t);return r>=0?(r+=n?1:-1,r<0?r=e.length-1:r%=e.length,e[r]):null},e.INSTANCE=new e,e}();n("5110");function Me(e){var t,n=this,r=!1;return function(){return r?t:(r=!0,t=e.apply(n,arguments),t)}}var Re,je=function(){function e(e){this.element=e}return e}(),Fe=function(){function e(){this._size=0}return Object.defineProperty(e.prototype,"size",{get:function(){return this._size},enumerable:!0,configurable:!0}),e.prototype.isEmpty=function(){return!this._first},e.prototype.unshift=function(e){return this._insert(e,!1)},e.prototype.push=function(e){return this._insert(e,!0)},e.prototype._insert=function(e,t){var n=new je(e);if(this._first)if(t){var r=this._last;this._last=n,n.prev=r,r.next=n}else{var i=this._first;this._first=n,n.next=i,i.prev=n}else this._first=n,this._last=n;return this._size+=1,this._remove.bind(this,n)},e.prototype.shift=function(){if(this._first){var e=this._first.element;return this._remove(this._first),e}},e.prototype._remove=function(e){var t=this._first;while(t instanceof je){if(t===e){if(t.prev&&t.next){var n=t.prev;n.next=t.next,t.next.prev=n}else t.prev||t.next?t.next?t.prev||(this._first=this._first.next,this._first.prev=void 0):(this._last=this._last.prev,this._last.next=void 0):(this._first=void 0,this._last=void 0);this._size-=1;break}t=t.next}},e.prototype.iterator=function(){var e,t=this._first;return{next:function(){return t?(e?e.value=t.element:e={done:!1,value:t.element},t=t.next,e):I}}},e}();(function(e){var t={dispose:function(){}};function n(e){return function(t,n,r){void 0===n&&(n=null);var i,o=!1;return i=e(function(e){if(!o)return i?i.dispose():o=!0,t.call(n,e)},null,r),o&&i.dispose(),i}}function r(e,t){return c(function(n,r,i){return void 0===r&&(r=null),e(function(e){return n.call(r,t(e))},null,i)})}function i(e,t){return c(function(n,r,i){return void 0===r&&(r=null),e(function(e){t(e),n.call(r,e)},null,i)})}function o(e,t){return c(function(n,r,i){return void 0===r&&(r=null),e(function(e){return t(e)&&n.call(r,e)},null,i)})}function s(e){return e}function a(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return function(t,n,r){return void 0===n&&(n=null),f(e.map(function(e){return e(function(e){return t.call(n,e)},null,r)}))}}function u(e,t,n){var i=n;return r(e,function(e){return i=t(i,e),i})}function c(e){var t,n=new qe({onFirstListenerAdd:function(){t=e(n.fire,n)},onLastListenerRemove:function(){t.dispose()}});return n.event}function l(e,t,n,r,i){var o;void 0===n&&(n=100),void 0===r&&(r=!1);var s=void 0,a=void 0,u=0,c=new qe({leakWarningThreshold:i,onFirstListenerAdd:function(){o=e(function(e){u++,s=t(s,e),r&&!a&&c.fire(s),clearTimeout(a),a=setTimeout(function(){var e=s;s=void 0,a=void 0,(!r||u>1)&&c.fire(e),u=0},n)})},onLastListenerRemove:function(){o.dispose()}});return c.event}function h(e){var t=(new Date).getTime();return r(n(e),function(e){return(new Date).getTime()-t})}function d(e){var t,n=!0;return o(e,function(e){var r=n||e!==t;return n=!1,t=e,r})}function p(e,t,n){void 0===t&&(t=!1),void 0===n&&(n=[]);var r=n.slice(),i=e(function(e){r?r.push(e):s.fire(e)}),o=function(){r&&r.forEach(function(e){return s.fire(e)}),r=null},s=new qe({onFirstListenerAdd:function(){i||(i=e(function(e){return s.fire(e)}))},onFirstListenerDidAdd:function(){r&&(t?setTimeout(o):o())},onLastListenerRemove:function(){i&&i.dispose(),i=null}});return s.event}function m(e,t,n){void 0===t&&(t=!1),void 0===n&&(n=[]),n=n.slice(),e(function(e){n.push(e),i.fire(e)});var r=function(e,t){return n.forEach(function(n){return e.call(t,n)})},i=new qe({onListenerDidAdd:function(e,n,i){t?setTimeout(function(){return r(n,i)}):r(n,i)}});return i.event}e.None=function(){return t},e.once=n,e.map=r,e.forEach=i,e.filter=o,e.signal=s,e.any=a,e.reduce=u,e.snapshot=c,e.debounce=l,e.stopwatch=h,e.latch=d,e.buffer=p,e.echo=m;var g=function(){function e(e){this.event=e}return e.prototype.map=function(t){return new e(r(this.event,t))},e.prototype.forEach=function(t){return new e(i(this.event,t))},e.prototype.filter=function(t){return new e(o(this.event,t))},e.prototype.reduce=function(t,n){return new e(u(this.event,t,n))},e.prototype.latch=function(){return new e(d(this.event))},e.prototype.on=function(e,t,n){return this.event(e,t,n)},e.prototype.once=function(e,t,r){return n(this.event)(e,t,r)},e}();function v(e){return new g(e)}function y(e,t,n){void 0===n&&(n=function(e){return e});var r=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return s.fire(n.apply(void 0,e))},i=function(){return e.on(t,r)},o=function(){return e.removeListener(t,r)},s=new qe({onFirstListenerAdd:i,onLastListenerRemove:o});return s.event}function b(e){var t=new qe,n=!1;return e.then(void 0,function(){return null}).then(function(){n?t.fire(void 0):setTimeout(function(){return t.fire(void 0)},0)}),n=!0,t.event}function _(e){return new Promise(function(t){return n(e)(t)})}e.chain=v,e.fromNodeEventEmitter=y,e.fromPromise=b,e.toPromise=_})(Re||(Re={}));var Ve,De=-1,Ue=function(){function e(e,t){void 0===t&&(t=Math.random().toString(18).slice(2,5)),this.customThreshold=e,this.name=t,this._warnCountdown=0}return e.prototype.dispose=function(){this._stacks&&this._stacks.clear()},e.prototype.check=function(e){var t=this,n=De;if("number"===typeof this.customThreshold&&(n=this.customThreshold),!(n<=0||e<n)){this._stacks||(this._stacks=new Map);var r=(new Error).stack.split("\n").slice(3).join("\n"),i=this._stacks.get(r)||0;if(this._stacks.set(r,i+1),this._warnCountdown-=1,this._warnCountdown<=0){var o;this._warnCountdown=.5*n;var s=0;this._stacks.forEach(function(e,t){(!o||s<e)&&(o=t,s=e)}),console.warn("["+this.name+"] potential listener LEAK detected, having "+e+" listeners already. MOST frequent listener ("+s+"):"),console.warn(o)}return function(){var e=t._stacks.get(r)||0;t._stacks.set(r,e-1)}}},e}(),qe=function(){function e(e){this._disposed=!1,this._options=e,this._leakageMon=De>0?new Ue(this._options&&this._options.leakWarningThreshold):void 0}return Object.defineProperty(e.prototype,"event",{get:function(){var t=this;return this._event||(this._event=function(n,r,i){t._listeners||(t._listeners=new Fe);var o=t._listeners.isEmpty();o&&t._options&&t._options.onFirstListenerAdd&&t._options.onFirstListenerAdd(t);var s,a,u=t._listeners.push(r?[n,r]:n);return o&&t._options&&t._options.onFirstListenerDidAdd&&t._options.onFirstListenerDidAdd(t),t._options&&t._options.onListenerDidAdd&&t._options.onListenerDidAdd(t,n,r),t._leakageMon&&(s=t._leakageMon.check(t._listeners.size)),a={dispose:function(){if(s&&s(),a.dispose=e._noop,!t._disposed&&(u(),t._options&&t._options.onLastListenerRemove)){var n=t._listeners&&!t._listeners.isEmpty();n||t._options.onLastListenerRemove(t)}}},Array.isArray(i)&&i.push(a),a}),this._event},enumerable:!0,configurable:!0}),e.prototype.fire=function(e){if(this._listeners){this._deliveryQueue||(this._deliveryQueue=[]);for(var t=this._listeners.iterator(),n=t.next();!n.done;n=t.next())this._deliveryQueue.push([n.value,e]);while(this._deliveryQueue.length>0){var r=this._deliveryQueue.shift(),i=r[0],s=r[1];try{"function"===typeof i?i.call(void 0,s):i[0].call(i[1],s)}catch(n){o(n)}}}},e.prototype.dispose=function(){this._listeners&&(this._listeners=void 0),this._deliveryQueue&&(this._deliveryQueue.length=0),this._leakageMon&&this._leakageMon.dispose(),this._disposed=!0},e._noop=function(){},e}(),Ke=(function(){function e(){var e=this;this.hasListeners=!1,this.events=[],this.emitter=new qe({onFirstListenerAdd:function(){return e.onFirstListenerAdd()},onLastListenerRemove:function(){return e.onLastListenerRemove()}})}Object.defineProperty(e.prototype,"event",{get:function(){return this.emitter.event},enumerable:!0,configurable:!0}),e.prototype.add=function(e){var t=this,n={event:e,listener:null};this.events.push(n),this.hasListeners&&this.hook(n);var r=function(){t.hasListeners&&t.unhook(n);var e=t.events.indexOf(n);t.events.splice(e,1)};return h(Me(r))},e.prototype.onFirstListenerAdd=function(){var e=this;this.hasListeners=!0,this.events.forEach(function(t){return e.hook(t)})},e.prototype.onLastListenerRemove=function(){var e=this;this.hasListeners=!1,this.events.forEach(function(t){return e.unhook(t)})},e.prototype.hook=function(e){var t=this;e.listener=e.event(function(e){return t.emitter.fire(e)})},e.prototype.unhook=function(e){e.listener&&e.listener.dispose(),e.listener=null},e.prototype.dispose=function(){this.emitter.dispose()}}(),function(){function e(){this.buffers=[]}e.prototype.wrapEvent=function(e){var t=this;return function(n,r,i){return e(function(e){var i=t.buffers[t.buffers.length-1];i?i.push(function(){return n.call(r,e)}):n.call(r,e)},void 0,i)}},e.prototype.bufferEvents=function(e){var t=[];this.buffers.push(t);var n=e();return this.buffers.pop(),t.forEach(function(e){return e()}),n}}(),function(){function e(){var e=this;this.listening=!1,this.inputEvent=Re.None,this.inputEventListener=d.None,this.emitter=new qe({onFirstListenerDidAdd:function(){e.listening=!0,e.inputEventListener=e.inputEvent(e.emitter.fire,e.emitter)},onLastListenerRemove:function(){e.listening=!1,e.inputEventListener.dispose()}}),this.event=this.emitter.event}Object.defineProperty(e.prototype,"input",{set:function(e){this.inputEvent=e,this.listening&&(this.inputEventListener.dispose(),this.inputEventListener=e(this.emitter.fire,this.emitter))},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this.inputEventListener.dispose(),this.emitter.dispose()}}(),Object.freeze(function(e,t){var n=setTimeout(e.bind(t),0);return{dispose:function(){clearTimeout(n)}}}));(function(e){function t(t){return t===e.None||t===e.Cancelled||(t instanceof Be||!(!t||"object"!==typeof t)&&("boolean"===typeof t.isCancellationRequested&&"function"===typeof t.onCancellationRequested))}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Re.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Ke})})(Ve||(Ve={}));var We,Be=function(){function e(){this._isCancelled=!1,this._emitter=null}return e.prototype.cancel=function(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))},Object.defineProperty(e.prototype,"isCancellationRequested",{get:function(){return this._isCancelled},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onCancellationRequested",{get:function(){return this._isCancelled?Ke:(this._emitter||(this._emitter=new qe),this._emitter.event)},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this._emitter&&(this._emitter.dispose(),this._emitter=null)},e}(),$e=function(){function e(){}return Object.defineProperty(e.prototype,"token",{get:function(){return this._token||(this._token=new Be),this._token},enumerable:!0,configurable:!0}),e.prototype.cancel=function(){this._token?this._token instanceof Be&&this._token.cancel():this._token=Ve.Cancelled},e.prototype.dispose=function(){this._token?this._token instanceof Be&&this._token.dispose():this._token=Ve.None},e}(),Ye=function(){function e(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}return e.prototype.define=function(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e},e.prototype.keyCodeToStr=function(e){return this._keyCodeToStr[e]},e.prototype.strToKeyCode=function(e){return this._strToKeyCode[e.toLowerCase()]||0},e}(),He=new Ye,ze=new Ye,Ge=new Ye;function Je(e,t){var n=(65535&t)<<16>>>0;return(e|n)>>>0}(function(){function e(e,t,n,r){void 0===n&&(n=t),void 0===r&&(r=n),He.define(e,t),ze.define(e,n),Ge.define(e,r)}e(0,"unknown"),e(1,"Backspace"),e(2,"Tab"),e(3,"Enter"),e(4,"Shift"),e(5,"Ctrl"),e(6,"Alt"),e(7,"PauseBreak"),e(8,"CapsLock"),e(9,"Escape"),e(10,"Space"),e(11,"PageUp"),e(12,"PageDown"),e(13,"End"),e(14,"Home"),e(15,"LeftArrow","Left"),e(16,"UpArrow","Up"),e(17,"RightArrow","Right"),e(18,"DownArrow","Down"),e(19,"Insert"),e(20,"Delete"),e(21,"0"),e(22,"1"),e(23,"2"),e(24,"3"),e(25,"4"),e(26,"5"),e(27,"6"),e(28,"7"),e(29,"8"),e(30,"9"),e(31,"A"),e(32,"B"),e(33,"C"),e(34,"D"),e(35,"E"),e(36,"F"),e(37,"G"),e(38,"H"),e(39,"I"),e(40,"J"),e(41,"K"),e(42,"L"),e(43,"M"),e(44,"N"),e(45,"O"),e(46,"P"),e(47,"Q"),e(48,"R"),e(49,"S"),e(50,"T"),e(51,"U"),e(52,"V"),e(53,"W"),e(54,"X"),e(55,"Y"),e(56,"Z"),e(57,"Meta"),e(58,"ContextMenu"),e(59,"F1"),e(60,"F2"),e(61,"F3"),e(62,"F4"),e(63,"F5"),e(64,"F6"),e(65,"F7"),e(66,"F8"),e(67,"F9"),e(68,"F10"),e(69,"F11"),e(70,"F12"),e(71,"F13"),e(72,"F14"),e(73,"F15"),e(74,"F16"),e(75,"F17"),e(76,"F18"),e(77,"F19"),e(78,"NumLock"),e(79,"ScrollLock"),e(80,";",";","OEM_1"),e(81,"=","=","OEM_PLUS"),e(82,",",",","OEM_COMMA"),e(83,"-","-","OEM_MINUS"),e(84,".",".","OEM_PERIOD"),e(85,"/","/","OEM_2"),e(86,"`","`","OEM_3"),e(110,"ABNT_C1"),e(111,"ABNT_C2"),e(87,"[","[","OEM_4"),e(88,"\\","\\","OEM_5"),e(89,"]","]","OEM_6"),e(90,"'","'","OEM_7"),e(91,"OEM_8"),e(92,"OEM_102"),e(93,"NumPad0"),e(94,"NumPad1"),e(95,"NumPad2"),e(96,"NumPad3"),e(97,"NumPad4"),e(98,"NumPad5"),e(99,"NumPad6"),e(100,"NumPad7"),e(101,"NumPad8"),e(102,"NumPad9"),e(103,"NumPad_Multiply"),e(104,"NumPad_Add"),e(105,"NumPad_Separator"),e(106,"NumPad_Subtract"),e(107,"NumPad_Decimal"),e(108,"NumPad_Divide")})(),function(e){function t(e){return He.keyCodeToStr(e)}function n(e){return He.strToKeyCode(e)}function r(e){return ze.keyCodeToStr(e)}function i(e){return Ge.keyCodeToStr(e)}function o(e){return ze.strToKeyCode(e)||Ge.strToKeyCode(e)}e.toString=t,e.fromString=n,e.toUserSettingsUS=r,e.toUserSettingsGeneral=i,e.fromUserSettings=o}(We||(We={}));(function(){function e(e,t,n,r,i){this.ctrlKey=e,this.shiftKey=t,this.altKey=n,this.metaKey=r,this.keyCode=i}e.prototype.equals=function(e){return this.ctrlKey===e.ctrlKey&&this.shiftKey===e.shiftKey&&this.altKey===e.altKey&&this.metaKey===e.metaKey&&this.keyCode===e.keyCode},e.prototype.isModifierKey=function(){return 0===this.keyCode||5===this.keyCode||57===this.keyCode||6===this.keyCode||4===this.keyCode},e.prototype.toChord=function(){return new xt([this])},e.prototype.isDuplicateModifierCase=function(){return this.ctrlKey&&5===this.keyCode||this.shiftKey&&4===this.keyCode||this.altKey&&6===this.keyCode||this.metaKey&&57===this.keyCode}})();var Qe,Xe,Ze,et,tt,nt,rt,it,ot,st,at,ut,ct,lt,ft,ht,dt,pt,mt,gt,vt,yt,bt,_t,Ct,St,Et,xt=function(){function e(e){if(0===e.length)throw c("parts");this.parts=e}return e.prototype.equals=function(e){if(null===e)return!1;if(this.parts.length!==e.parts.length)return!1;for(var t=0;t<this.parts.length;t++)if(!this.parts[t].equals(e.parts[t]))return!1;return!0},e}(),Nt=(function(){function e(e,t,n,r,i,o){this.ctrlKey=e,this.shiftKey=t,this.altKey=n,this.metaKey=r,this.keyLabel=i,this.keyAriaLabel=o}}(),function(){function e(){}}(),function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}()),wt=function(e){function t(t,n,r,i){var o=e.call(this,t,n,r,i)||this;return o.selectionStartLineNumber=t,o.selectionStartColumn=n,o.positionLineNumber=r,o.positionColumn=i,o}return Nt(t,e),t.prototype.clone=function(){return new t(this.selectionStartLineNumber,this.selectionStartColumn,this.positionLineNumber,this.positionColumn)},t.prototype.toString=function(){return"["+this.selectionStartLineNumber+","+this.selectionStartColumn+" -> "+this.positionLineNumber+","+this.positionColumn+"]"},t.prototype.equalsSelection=function(e){return t.selectionsEqual(this,e)},t.selectionsEqual=function(e,t){return e.selectionStartLineNumber===t.selectionStartLineNumber&&e.selectionStartColumn===t.selectionStartColumn&&e.positionLineNumber===t.positionLineNumber&&e.positionColumn===t.positionColumn},t.prototype.getDirection=function(){return this.selectionStartLineNumber===this.startLineNumber&&this.selectionStartColumn===this.startColumn?0:1},t.prototype.setEndPosition=function(e,n){return 0===this.getDirection()?new t(this.startLineNumber,this.startColumn,e,n):new t(e,n,this.startLineNumber,this.startColumn)},t.prototype.getPosition=function(){return new Z(this.positionLineNumber,this.positionColumn)},t.prototype.setStartPosition=function(e,n){return 0===this.getDirection()?new t(e,n,this.endLineNumber,this.endColumn):new t(this.endLineNumber,this.endColumn,e,n)},t.fromPositions=function(e,n){return void 0===n&&(n=e),new t(e.lineNumber,e.column,n.lineNumber,n.column)},t.liftSelection=function(e){return new t(e.selectionStartLineNumber,e.selectionStartColumn,e.positionLineNumber,e.positionColumn)},t.selectionsArrEqual=function(e,t){if(e&&!t||!e&&t)return!1;if(!e&&!t)return!0;if(e.length!==t.length)return!1;for(var n=0,r=e.length;n<r;n++)if(!this.selectionsEqual(e[n],t[n]))return!1;return!0},t.isISelection=function(e){return e&&"number"===typeof e.selectionStartLineNumber&&"number"===typeof e.selectionStartColumn&&"number"===typeof e.positionLineNumber&&"number"===typeof e.positionColumn},t.createWithDirection=function(e,n,r,i,o){return 0===o?new t(e,n,r,i):new t(r,i,e,n)},t}(ee),At=function(){function e(e,t,n){this.offset=0|e,this.type=t,this.language=n}return e.prototype.toString=function(){return"("+this.offset+", "+this.type+")"},e}();(function(){function e(e,t){this.tokens=e,this.endState=t}})(),function(){function e(e,t){this.tokens=e,this.endState=t}}();(function(e){e[e["Unnecessary"]=1]="Unnecessary"})(Qe||(Qe={})),function(e){e[e["Hint"]=1]="Hint",e[e["Info"]=2]="Info",e[e["Warning"]=4]="Warning",e[e["Error"]=8]="Error"}(Xe||(Xe={})),function(e){e[e["Unknown"]=0]="Unknown",e[e["Backspace"]=1]="Backspace",e[e["Tab"]=2]="Tab",e[e["Enter"]=3]="Enter",e[e["Shift"]=4]="Shift",e[e["Ctrl"]=5]="Ctrl",e[e["Alt"]=6]="Alt",e[e["PauseBreak"]=7]="PauseBreak",e[e["CapsLock"]=8]="CapsLock",e[e["Escape"]=9]="Escape",e[e["Space"]=10]="Space",e[e["PageUp"]=11]="PageUp",e[e["PageDown"]=12]="PageDown",e[e["End"]=13]="End",e[e["Home"]=14]="Home",e[e["LeftArrow"]=15]="LeftArrow",e[e["UpArrow"]=16]="UpArrow",e[e["RightArrow"]=17]="RightArrow",e[e["DownArrow"]=18]="DownArrow",e[e["Insert"]=19]="Insert",e[e["Delete"]=20]="Delete",e[e["KEY_0"]=21]="KEY_0",e[e["KEY_1"]=22]="KEY_1",e[e["KEY_2"]=23]="KEY_2",e[e["KEY_3"]=24]="KEY_3",e[e["KEY_4"]=25]="KEY_4",e[e["KEY_5"]=26]="KEY_5",e[e["KEY_6"]=27]="KEY_6",e[e["KEY_7"]=28]="KEY_7",e[e["KEY_8"]=29]="KEY_8",e[e["KEY_9"]=30]="KEY_9",e[e["KEY_A"]=31]="KEY_A",e[e["KEY_B"]=32]="KEY_B",e[e["KEY_C"]=33]="KEY_C",e[e["KEY_D"]=34]="KEY_D",e[e["KEY_E"]=35]="KEY_E",e[e["KEY_F"]=36]="KEY_F",e[e["KEY_G"]=37]="KEY_G",e[e["KEY_H"]=38]="KEY_H",e[e["KEY_I"]=39]="KEY_I",e[e["KEY_J"]=40]="KEY_J",e[e["KEY_K"]=41]="KEY_K",e[e["KEY_L"]=42]="KEY_L",e[e["KEY_M"]=43]="KEY_M",e[e["KEY_N"]=44]="KEY_N",e[e["KEY_O"]=45]="KEY_O",e[e["KEY_P"]=46]="KEY_P",e[e["KEY_Q"]=47]="KEY_Q",e[e["KEY_R"]=48]="KEY_R",e[e["KEY_S"]=49]="KEY_S",e[e["KEY_T"]=50]="KEY_T",e[e["KEY_U"]=51]="KEY_U",e[e["KEY_V"]=52]="KEY_V",e[e["KEY_W"]=53]="KEY_W",e[e["KEY_X"]=54]="KEY_X",e[e["KEY_Y"]=55]="KEY_Y",e[e["KEY_Z"]=56]="KEY_Z",e[e["Meta"]=57]="Meta",e[e["ContextMenu"]=58]="ContextMenu",e[e["F1"]=59]="F1",e[e["F2"]=60]="F2",e[e["F3"]=61]="F3",e[e["F4"]=62]="F4",e[e["F5"]=63]="F5",e[e["F6"]=64]="F6",e[e["F7"]=65]="F7",e[e["F8"]=66]="F8",e[e["F9"]=67]="F9",e[e["F10"]=68]="F10",e[e["F11"]=69]="F11",e[e["F12"]=70]="F12",e[e["F13"]=71]="F13",e[e["F14"]=72]="F14",e[e["F15"]=73]="F15",e[e["F16"]=74]="F16",e[e["F17"]=75]="F17",e[e["F18"]=76]="F18",e[e["F19"]=77]="F19",e[e["NumLock"]=78]="NumLock",e[e["ScrollLock"]=79]="ScrollLock",e[e["US_SEMICOLON"]=80]="US_SEMICOLON",e[e["US_EQUAL"]=81]="US_EQUAL",e[e["US_COMMA"]=82]="US_COMMA",e[e["US_MINUS"]=83]="US_MINUS",e[e["US_DOT"]=84]="US_DOT",e[e["US_SLASH"]=85]="US_SLASH",e[e["US_BACKTICK"]=86]="US_BACKTICK",e[e["US_OPEN_SQUARE_BRACKET"]=87]="US_OPEN_SQUARE_BRACKET",e[e["US_BACKSLASH"]=88]="US_BACKSLASH",e[e["US_CLOSE_SQUARE_BRACKET"]=89]="US_CLOSE_SQUARE_BRACKET",e[e["US_QUOTE"]=90]="US_QUOTE",e[e["OEM_8"]=91]="OEM_8",e[e["OEM_102"]=92]="OEM_102",e[e["NUMPAD_0"]=93]="NUMPAD_0",e[e["NUMPAD_1"]=94]="NUMPAD_1",e[e["NUMPAD_2"]=95]="NUMPAD_2",e[e["NUMPAD_3"]=96]="NUMPAD_3",e[e["NUMPAD_4"]=97]="NUMPAD_4",e[e["NUMPAD_5"]=98]="NUMPAD_5",e[e["NUMPAD_6"]=99]="NUMPAD_6",e[e["NUMPAD_7"]=100]="NUMPAD_7",e[e["NUMPAD_8"]=101]="NUMPAD_8",e[e["NUMPAD_9"]=102]="NUMPAD_9",e[e["NUMPAD_MULTIPLY"]=103]="NUMPAD_MULTIPLY",e[e["NUMPAD_ADD"]=104]="NUMPAD_ADD",e[e["NUMPAD_SEPARATOR"]=105]="NUMPAD_SEPARATOR",e[e["NUMPAD_SUBTRACT"]=106]="NUMPAD_SUBTRACT",e[e["NUMPAD_DECIMAL"]=107]="NUMPAD_DECIMAL",e[e["NUMPAD_DIVIDE"]=108]="NUMPAD_DIVIDE",e[e["KEY_IN_COMPOSITION"]=109]="KEY_IN_COMPOSITION",e[e["ABNT_C1"]=110]="ABNT_C1",e[e["ABNT_C2"]=111]="ABNT_C2",e[e["MAX_VALUE"]=112]="MAX_VALUE"}(Ze||(Ze={})),function(e){e[e["LTR"]=0]="LTR",e[e["RTL"]=1]="RTL"}(et||(et={})),function(e){e[e["Auto"]=1]="Auto",e[e["Hidden"]=2]="Hidden",e[e["Visible"]=3]="Visible"}(tt||(tt={})),function(e){e[e["Left"]=1]="Left",e[e["Center"]=2]="Center",e[e["Right"]=4]="Right",e[e["Full"]=7]="Full"}(nt||(nt={})),function(e){e[e["TextDefined"]=0]="TextDefined",e[e["LF"]=1]="LF",e[e["CRLF"]=2]="CRLF"}(rt||(rt={})),function(e){e[e["LF"]=1]="LF",e[e["CRLF"]=2]="CRLF"}(it||(it={})),function(e){e[e["LF"]=0]="LF",e[e["CRLF"]=1]="CRLF"}(ot||(ot={})),function(e){e[e["AlwaysGrowsWhenTypingAtEdges"]=0]="AlwaysGrowsWhenTypingAtEdges",e[e["NeverGrowsWhenTypingAtEdges"]=1]="NeverGrowsWhenTypingAtEdges",e[e["GrowsOnlyWhenTypingBefore"]=2]="GrowsOnlyWhenTypingBefore",e[e["GrowsOnlyWhenTypingAfter"]=3]="GrowsOnlyWhenTypingAfter"}(st||(st={})),function(e){e[e["Smooth"]=0]="Smooth",e[e["Immediate"]=1]="Immediate"}(at||(at={})),function(e){e[e["NotSet"]=0]="NotSet",e[e["ContentFlush"]=1]="ContentFlush",e[e["RecoverFromMarkers"]=2]="RecoverFromMarkers",e[e["Explicit"]=3]="Explicit",e[e["Paste"]=4]="Paste",e[e["Undo"]=5]="Undo",e[e["Redo"]=6]="Redo"}(ut||(ut={})),function(e){e[e["None"]=0]="None",e[e["Small"]=1]="Small",e[e["Large"]=2]="Large",e[e["SmallBlocks"]=3]="SmallBlocks",e[e["LargeBlocks"]=4]="LargeBlocks"}(ct||(ct={})),function(e){e[e["None"]=0]="None",e[e["Same"]=1]="Same",e[e["Indent"]=2]="Indent",e[e["DeepIndent"]=3]="DeepIndent"}(lt||(lt={})),function(e){e[e["Hidden"]=0]="Hidden",e[e["Blink"]=1]="Blink",e[e["Smooth"]=2]="Smooth",e[e["Phase"]=3]="Phase",e[e["Expand"]=4]="Expand",e[e["Solid"]=5]="Solid"}(ft||(ft={})),function(e){e[e["Line"]=1]="Line",e[e["Block"]=2]="Block",e[e["Underline"]=3]="Underline",e[e["LineThin"]=4]="LineThin",e[e["BlockOutline"]=5]="BlockOutline",e[e["UnderlineThin"]=6]="UnderlineThin"}(ht||(ht={})),function(e){e[e["Off"]=0]="Off",e[e["On"]=1]="On",e[e["Relative"]=2]="Relative",e[e["Interval"]=3]="Interval",e[e["Custom"]=4]="Custom"}(dt||(dt={})),function(e){e[e["EXACT"]=0]="EXACT",e[e["ABOVE"]=1]="ABOVE",e[e["BELOW"]=2]="BELOW"}(pt||(pt={})),function(e){e[e["TOP_RIGHT_CORNER"]=0]="TOP_RIGHT_CORNER",e[e["BOTTOM_RIGHT_CORNER"]=1]="BOTTOM_RIGHT_CORNER",e[e["TOP_CENTER"]=2]="TOP_CENTER"}(mt||(mt={})),function(e){e[e["UNKNOWN"]=0]="UNKNOWN",e[e["TEXTAREA"]=1]="TEXTAREA",e[e["GUTTER_GLYPH_MARGIN"]=2]="GUTTER_GLYPH_MARGIN",e[e["GUTTER_LINE_NUMBERS"]=3]="GUTTER_LINE_NUMBERS",e[e["GUTTER_LINE_DECORATIONS"]=4]="GUTTER_LINE_DECORATIONS",e[e["GUTTER_VIEW_ZONE"]=5]="GUTTER_VIEW_ZONE",e[e["CONTENT_TEXT"]=6]="CONTENT_TEXT",e[e["CONTENT_EMPTY"]=7]="CONTENT_EMPTY",e[e["CONTENT_VIEW_ZONE"]=8]="CONTENT_VIEW_ZONE",e[e["CONTENT_WIDGET"]=9]="CONTENT_WIDGET",e[e["OVERVIEW_RULER"]=10]="OVERVIEW_RULER",e[e["SCROLLBAR"]=11]="SCROLLBAR",e[e["OVERLAY_WIDGET"]=12]="OVERLAY_WIDGET",e[e["OUTSIDE_EDITOR"]=13]="OUTSIDE_EDITOR"}(gt||(gt={})),function(e){e[e["None"]=0]="None",e[e["Indent"]=1]="Indent",e[e["IndentOutdent"]=2]="IndentOutdent",e[e["Outdent"]=3]="Outdent"}(vt||(vt={})),function(e){e[e["Method"]=0]="Method",e[e["Function"]=1]="Function",e[e["Constructor"]=2]="Constructor",e[e["Field"]=3]="Field",e[e["Variable"]=4]="Variable",e[e["Class"]=5]="Class",e[e["Struct"]=6]="Struct",e[e["Interface"]=7]="Interface",e[e["Module"]=8]="Module",e[e["Property"]=9]="Property",e[e["Event"]=10]="Event",e[e["Operator"]=11]="Operator",e[e["Unit"]=12]="Unit",e[e["Value"]=13]="Value",e[e["Constant"]=14]="Constant",e[e["Enum"]=15]="Enum",e[e["EnumMember"]=16]="EnumMember",e[e["Keyword"]=17]="Keyword",e[e["Text"]=18]="Text",e[e["Color"]=19]="Color",e[e["File"]=20]="File",e[e["Reference"]=21]="Reference",e[e["Customcolor"]=22]="Customcolor",e[e["Folder"]=23]="Folder",e[e["TypeParameter"]=24]="TypeParameter",e[e["Snippet"]=25]="Snippet"}(yt||(yt={})),function(e){e[e["KeepWhitespace"]=1]="KeepWhitespace",e[e["InsertAsSnippet"]=4]="InsertAsSnippet"}(bt||(bt={})),function(e){e[e["Invoke"]=0]="Invoke",e[e["TriggerCharacter"]=1]="TriggerCharacter",e[e["TriggerForIncompleteCompletions"]=2]="TriggerForIncompleteCompletions"}(_t||(_t={})),function(e){e[e["Invoke"]=1]="Invoke",e[e["TriggerCharacter"]=2]="TriggerCharacter",e[e["ContentChange"]=3]="ContentChange"}(Ct||(Ct={})),function(e){e[e["Text"]=0]="Text",e[e["Read"]=1]="Read",e[e["Write"]=2]="Write"}(St||(St={})),function(e){e[e["File"]=0]="File",e[e["Module"]=1]="Module",e[e["Namespace"]=2]="Namespace",e[e["Package"]=3]="Package",e[e["Class"]=4]="Class",e[e["Method"]=5]="Method",e[e["Property"]=6]="Property",e[e["Field"]=7]="Field",e[e["Constructor"]=8]="Constructor",e[e["Enum"]=9]="Enum",e[e["Interface"]=10]="Interface",e[e["Function"]=11]="Function",e[e["Variable"]=12]="Variable",e[e["Constant"]=13]="Constant",e[e["String"]=14]="String",e[e["Number"]=15]="Number",e[e["Boolean"]=16]="Boolean",e[e["Array"]=17]="Array",e[e["Object"]=18]="Object",e[e["Key"]=19]="Key",e[e["Null"]=20]="Null",e[e["EnumMember"]=21]="EnumMember",e[e["Struct"]=22]="Struct",e[e["Event"]=23]="Event",e[e["Operator"]=24]="Operator",e[e["TypeParameter"]=25]="TypeParameter"}(Et||(Et={}));var Lt=function(){function e(){}return e.chord=function(e,t){return Je(e,t)},e.CtrlCmd=2048,e.Shift=1024,e.Alt=512,e.WinCtrl=256,e}();function kt(){return{editor:void 0,languages:void 0,CancellationTokenSource:$e,Emitter:qe,KeyCode:Ze,KeyMod:Lt,Position:Z,Range:ee,Selection:wt,SelectionDirection:et,MarkerSeverity:Xe,MarkerTag:Qe,Uri:Y,Token:At}}var Tt=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Ot=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Tt(t,e),Object.defineProperty(t.prototype,"uri",{get:function(){return this._uri},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"version",{get:function(){return this._versionId},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"eol",{get:function(){return this._eol},enumerable:!0,configurable:!0}),t.prototype.getValue=function(){return this.getText()},t.prototype.getLinesContent=function(){return this._lines.slice(0)},t.prototype.getLineCount=function(){return this._lines.length},t.prototype.getLineContent=function(e){return this._lines[e-1]},t.prototype.getWordAtPosition=function(e,t){var n=xe(e.column,Ce(t),this._lines[e.lineNumber-1],0);return n?new ee(e.lineNumber,n.startColumn,e.lineNumber,n.endColumn):null},t.prototype.getWordUntilPosition=function(e,t){var n=this.getWordAtPosition(e,t);return n?{word:this._lines[e.lineNumber-1].substring(n.startColumn-1,e.column-1),startColumn:n.startColumn,endColumn:e.column}:{word:"",startColumn:e.column,endColumn:e.column}},t.prototype.createWordIterator=function(e){var t,n,r=this,i=0,o=0,s=[],a=function(){if(o<s.length){var u=n.substring(s[o].start,s[o].end);return o+=1,t?t.value=u:t={done:!1,value:u},t}return i>=r._lines.length?I:(n=r._lines[i],s=r._wordenize(n,e),o=0,i+=1,a())};return{next:a}},t.prototype.getLineWords=function(e,t){for(var n=this._lines[e-1],r=this._wordenize(n,t),i=[],o=0,s=r;o<s.length;o++){var a=s[o];i.push({word:n.substring(a.start,a.end),startColumn:a.start+1,endColumn:a.end+1})}return i},t.prototype._wordenize=function(e,t){var n,r=[];t.lastIndex=0;while(n=t.exec(e)){if(0===n[0].length)break;r.push({start:n.index,end:n.index+n[0].length})}return r},t.prototype.getValueInRange=function(e){if(e=this._validateRange(e),e.startLineNumber===e.endLineNumber)return this._lines[e.startLineNumber-1].substring(e.startColumn-1,e.endColumn-1);var t=this._eol,n=e.startLineNumber-1,r=e.endLineNumber-1,i=[];i.push(this._lines[n].substring(e.startColumn-1));for(var o=n+1;o<r;o++)i.push(this._lines[o]);return i.push(this._lines[r].substring(0,e.endColumn-1)),i.join(t)},t.prototype.offsetAt=function(e){return e=this._validatePosition(e),this._ensureLineStarts(),this._lineStarts.getAccumulatedValue(e.lineNumber-2)+(e.column-1)},t.prototype.positionAt=function(e){e=Math.floor(e),e=Math.max(0,e),this._ensureLineStarts();var t=this._lineStarts.getIndexOf(e),n=this._lines[t.index].length;return{lineNumber:1+t.index,column:1+Math.min(t.remainder,n)}},t.prototype._validateRange=function(e){var t=this._validatePosition({lineNumber:e.startLineNumber,column:e.startColumn}),n=this._validatePosition({lineNumber:e.endLineNumber,column:e.endColumn});return t.lineNumber!==e.startLineNumber||t.column!==e.startColumn||n.lineNumber!==e.endLineNumber||n.column!==e.endColumn?{startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:n.lineNumber,endColumn:n.column}:e},t.prototype._validatePosition=function(e){if(!Z.isIPosition(e))throw new Error("bad position");var t=e.lineNumber,n=e.column,r=!1;if(t<1)t=1,n=1,r=!0;else if(t>this._lines.length)t=this._lines.length,n=this._lines[t-1].length+1,r=!0;else{var i=this._lines[t-1].length+1;n<1?(n=1,r=!0):n>i&&(n=i,r=!0)}return r?{lineNumber:t,column:n}:e},t}(ve),Pt=function(){function e(e){this._foreignModuleFactory=e,this._foreignModule=null}return e.prototype.computeDiff=function(e,t,n){var r=this._getModel(e),i=this._getModel(t);if(!r||!i)return Promise.resolve(null);var o=r.getLinesContent(),s=i.getLinesContent(),a=new fe(o,s,{shouldComputeCharChanges:!0,shouldPostProcessCharChanges:!0,shouldIgnoreTrimWhitespace:n,shouldMakePrettyDiff:!0}),u=a.computeDiff(),c=!(u.length>0)&&this._modelsAreIdentical(r,i);return Promise.resolve({identical:c,changes:u})},e.prototype._modelsAreIdentical=function(e,t){var n=e.getLineCount(),r=t.getLineCount();if(n!==r)return!1;for(var i=1;i<=n;i++){var o=e.getLineContent(i),s=t.getLineContent(i);if(o!==s)return!1}return!0},e.prototype.computeMoreMinimalEdits=function(t,n){var r=this._getModel(t);if(!r)return Promise.resolve(n);var i=[],o=void 0;n=_(n,function(e,t){if(e.range&&t.range)return ee.compareRangesUsingStarts(e.range,t.range);var n=e.range?0:1,r=t.range?0:1;return n-r});for(var s=0,a=n;s<a.length;s++){var u=a[s],c=u.range,l=u.text,f=u.eol;if("number"===typeof f&&(o=f),!ee.isEmpty(c)||l){var h=r.getValueInRange(c);if(l=l.replace(/\r\n|\n|\r/g,r.eol),h!==l)if(Math.max(l.length,h.length)>e._diffLimit)i.push({range:c,text:l});else for(var d=N(h,l,!1),p=r.offsetAt(ee.lift(c).getStartPosition()),m=0,g=d;m<g.length;m++){var v=g[m],y=r.positionAt(p+v.originalStart),b=r.positionAt(p+v.originalStart+v.originalLength),C={text:l.substr(v.modifiedStart,v.modifiedLength),range:{startLineNumber:y.lineNumber,startColumn:y.column,endLineNumber:b.lineNumber,endColumn:b.column}};r.getValueInRange(C.range)!==C.text&&i.push(C)}}}return"number"===typeof o&&i.push({eol:o,text:"",range:{startLineNumber:0,startColumn:0,endLineNumber:0,endColumn:0}}),Promise.resolve(i)},e.prototype.computeLinks=function(e){var t=this._getModel(e);return t?Promise.resolve(Pe(t)):Promise.resolve(null)},e.prototype.textualSuggest=function(t,n,r,i){var o=this._getModel(t);if(!o)return Promise.resolve(null);var s=[],a=new RegExp(r,i),u=o.getWordUntilPosition(n,a),c=Object.create(null);c[u.word]=!0;for(var l=o.createWordIterator(a),f=l.next();!f.done&&s.length<=e._suggestionsLimit;f=l.next()){var h=f.value;c[h]||(c[h]=!0,isNaN(Number(h))&&s.push({kind:18,label:h,insertText:h,range:{startLineNumber:n.lineNumber,startColumn:u.startColumn,endLineNumber:n.lineNumber,endColumn:u.endColumn}}))}return Promise.resolve({suggestions:s})},e.prototype.computeWordRanges=function(e,t,n,r){var i=this._getModel(e);if(!i)return Promise.resolve(Object.create(null));for(var o=new RegExp(n,r),s=Object.create(null),a=t.startLineNumber;a<t.endLineNumber;a++)for(var u=i.getLineWords(a,o),c=0,l=u;c<l.length;c++){var f=l[c];if(isNaN(Number(f.word))){var h=s[f.word];h||(h=[],s[f.word]=h),h.push({startLineNumber:a,startColumn:f.startColumn,endLineNumber:a,endColumn:f.endColumn})}}return Promise.resolve(s)},e.prototype.navigateValueSet=function(e,t,n,r,i){var o=this._getModel(e);if(!o)return Promise.resolve(null);var s=new RegExp(r,i);t.startColumn===t.endColumn&&(t={startLineNumber:t.startLineNumber,startColumn:t.startColumn,endLineNumber:t.endLineNumber,endColumn:t.endColumn+1});var a=o.getValueInRange(t),u=o.getWordAtPosition({lineNumber:t.startLineNumber,column:t.startColumn},s);if(!u)return Promise.resolve(null);var c=o.getValueInRange(u),l=Ie.INSTANCE.navigateValueSet(t,a,u,c,n);return Promise.resolve(l)},e.prototype.loadForeignModule=function(e,t){var n=this,r={getMirrorModels:function(){return n._getModels()}};if(this._foreignModuleFactory){this._foreignModule=this._foreignModuleFactory(r,t);for(var i=[],o=0,s=m(this._foreignModule);o<s.length;o++){var a=s[o];"function"===typeof this._foreignModule[a]&&i.push(a)}return Promise.resolve(i)}return Promise.reject(new Error("Unexpected usage"))},e.prototype.fmr=function(e,t){if(!this._foreignModule||"function"!==typeof this._foreignModule[e])return Promise.reject(new Error("Missing requestHandler or method: "+e));try{return Promise.resolve(this._foreignModule[e].apply(this._foreignModule,t))}catch(n){return Promise.reject(n)}},e._diffLimit=1e4,e._suggestionsLimit=1e4,e}(),It=function(e){function t(t){var n=e.call(this,t)||this;return n._models=Object.create(null),n}return Tt(t,e),t.prototype.dispose=function(){this._models=Object.create(null)},t.prototype._getModel=function(e){return this._models[e]},t.prototype._getModels=function(){var e=this,t=[];return Object.keys(this._models).forEach(function(n){return t.push(e._models[n])}),t},t.prototype.acceptNewModel=function(e){this._models[e.url]=new Ot(Y.parse(e.url),e.lines,e.EOL,e.versionId)},t.prototype.acceptModelChanged=function(e,t){if(this._models[e]){var n=this._models[e];n.onEvents(t)}},t.prototype.acceptRemovedModel=function(e){this._models[e]&&delete this._models[e]},t}(Pt);"function"===typeof importScripts&&(p["a"].monaco=kt());var Mt,Rt,jt,Ft,Vt,Dt,Ut,qt,Kt,Wt,Bt,$t,Yt,Ht,zt,Gt,Jt,Qt,Xt,Zt=!1;function en(e){if(!Zt){Zt=!0;var t=new It(e),n=new b(function(e){self.postMessage(e)},t);self.onmessage=function(e){n.onmessage(e.data)}}}self.onmessage=function(e){Zt||en(null)},function(e){function t(e,t){return{line:e,character:t}}function n(e){var t=e;return kn.objectLiteral(t)&&kn.number(t.line)&&kn.number(t.character)}e.create=t,e.is=n}(Mt||(Mt={})),function(e){function t(e,t,n,r){if(kn.number(e)&&kn.number(t)&&kn.number(n)&&kn.number(r))return{start:Mt.create(e,t),end:Mt.create(n,r)};if(Mt.is(e)&&Mt.is(t))return{start:e,end:t};throw new Error("Range#create called with invalid arguments["+e+", "+t+", "+n+", "+r+"]")}function n(e){var t=e;return kn.objectLiteral(t)&&Mt.is(t.start)&&Mt.is(t.end)}e.create=t,e.is=n}(Rt||(Rt={})),function(e){function t(e,t){return{uri:e,range:t}}function n(e){var t=e;return kn.defined(t)&&Rt.is(t.range)&&(kn.string(t.uri)||kn.undefined(t.uri))}e.create=t,e.is=n}(jt||(jt={})),function(e){function t(e,t,n,r){return{targetUri:e,targetRange:t,targetSelectionRange:n,originSelectionRange:r}}function n(e){var t=e;return kn.defined(t)&&Rt.is(t.targetRange)&&kn.string(t.targetUri)&&(Rt.is(t.targetSelectionRange)||kn.undefined(t.targetSelectionRange))&&(Rt.is(t.originSelectionRange)||kn.undefined(t.originSelectionRange))}e.create=t,e.is=n}(Ft||(Ft={})),function(e){function t(e,t,n,r){return{red:e,green:t,blue:n,alpha:r}}function n(e){var t=e;return kn.number(t.red)&&kn.number(t.green)&&kn.number(t.blue)&&kn.number(t.alpha)}e.create=t,e.is=n}(Vt||(Vt={})),function(e){function t(e,t){return{range:e,color:t}}function n(e){var t=e;return Rt.is(t.range)&&Vt.is(t.color)}e.create=t,e.is=n}(Dt||(Dt={})),function(e){function t(e,t,n){return{label:e,textEdit:t,additionalTextEdits:n}}function n(e){var t=e;return kn.string(t.label)&&(kn.undefined(t.textEdit)||Ht.is(t))&&(kn.undefined(t.additionalTextEdits)||kn.typedArray(t.additionalTextEdits,Ht.is))}e.create=t,e.is=n}(Ut||(Ut={})),function(e){e["Comment"]="comment",e["Imports"]="imports",e["Region"]="region"}(qt||(qt={})),function(e){function t(e,t,n,r,i){var o={startLine:e,endLine:t};return kn.defined(n)&&(o.startCharacter=n),kn.defined(r)&&(o.endCharacter=r),kn.defined(i)&&(o.kind=i),o}function n(e){var t=e;return kn.number(t.startLine)&&kn.number(t.startLine)&&(kn.undefined(t.startCharacter)||kn.number(t.startCharacter))&&(kn.undefined(t.endCharacter)||kn.number(t.endCharacter))&&(kn.undefined(t.kind)||kn.string(t.kind))}e.create=t,e.is=n}(Kt||(Kt={})),function(e){function t(e,t){return{location:e,message:t}}function n(e){var t=e;return kn.defined(t)&&jt.is(t.location)&&kn.string(t.message)}e.create=t,e.is=n}(Wt||(Wt={})),function(e){e.Error=1,e.Warning=2,e.Information=3,e.Hint=4}(Bt||(Bt={})),function(e){function t(e,t,n,r,i,o){var s={range:e,message:t};return kn.defined(n)&&(s.severity=n),kn.defined(r)&&(s.code=r),kn.defined(i)&&(s.source=i),kn.defined(o)&&(s.relatedInformation=o),s}function n(e){var t=e;return kn.defined(t)&&Rt.is(t.range)&&kn.string(t.message)&&(kn.number(t.severity)||kn.undefined(t.severity))&&(kn.number(t.code)||kn.string(t.code)||kn.undefined(t.code))&&(kn.string(t.source)||kn.undefined(t.source))&&(kn.undefined(t.relatedInformation)||kn.typedArray(t.relatedInformation,Wt.is))}e.create=t,e.is=n}($t||($t={})),function(e){function t(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var i={title:e,command:t};return kn.defined(n)&&n.length>0&&(i.arguments=n),i}function n(e){var t=e;return kn.defined(t)&&kn.string(t.title)&&kn.string(t.command)}e.create=t,e.is=n}(Yt||(Yt={})),function(e){function t(e,t){return{range:e,newText:t}}function n(e,t){return{range:{start:e,end:e},newText:t}}function r(e){return{range:e,newText:""}}function i(e){var t=e;return kn.objectLiteral(t)&&kn.string(t.newText)&&Rt.is(t.range)}e.replace=t,e.insert=n,e.del=r,e.is=i}(Ht||(Ht={})),function(e){function t(e,t){return{textDocument:e,edits:t}}function n(e){var t=e;return kn.defined(t)&&nn.is(t.textDocument)&&Array.isArray(t.edits)}e.create=t,e.is=n}(zt||(zt={})),function(e){function t(e,t){var n={kind:"create",uri:e};return void 0===t||void 0===t.overwrite&&void 0===t.ignoreIfExists||(n.options=t),n}function n(e){var t=e;return t&&"create"===t.kind&&kn.string(t.uri)&&(void 0===t.options||(void 0===t.options.overwrite||kn.boolean(t.options.overwrite))&&(void 0===t.options.ignoreIfExists||kn.boolean(t.options.ignoreIfExists)))}e.create=t,e.is=n}(Gt||(Gt={})),function(e){function t(e,t,n){var r={kind:"rename",oldUri:e,newUri:t};return void 0===n||void 0===n.overwrite&&void 0===n.ignoreIfExists||(r.options=n),r}function n(e){var t=e;return t&&"rename"===t.kind&&kn.string(t.oldUri)&&kn.string(t.newUri)&&(void 0===t.options||(void 0===t.options.overwrite||kn.boolean(t.options.overwrite))&&(void 0===t.options.ignoreIfExists||kn.boolean(t.options.ignoreIfExists)))}e.create=t,e.is=n}(Jt||(Jt={})),function(e){function t(e,t){var n={kind:"delete",uri:e};return void 0===t||void 0===t.recursive&&void 0===t.ignoreIfNotExists||(n.options=t),n}function n(e){var t=e;return t&&"delete"===t.kind&&kn.string(t.uri)&&(void 0===t.options||(void 0===t.options.recursive||kn.boolean(t.options.recursive))&&(void 0===t.options.ignoreIfNotExists||kn.boolean(t.options.ignoreIfNotExists)))}e.create=t,e.is=n}(Qt||(Qt={})),function(e){function t(e){var t=e;return t&&(void 0!==t.changes||void 0!==t.documentChanges)&&(void 0===t.documentChanges||t.documentChanges.every(function(e){return kn.string(e.kind)?Gt.is(e)||Jt.is(e)||Qt.is(e):zt.is(e)}))}e.is=t}(Xt||(Xt={}));var tn,nn,rn,on,sn,an,un,cn,ln,fn,hn,dn,pn,mn,gn,vn,yn,bn=function(){function e(e){this.edits=e}return e.prototype.insert=function(e,t){this.edits.push(Ht.insert(e,t))},e.prototype.replace=function(e,t){this.edits.push(Ht.replace(e,t))},e.prototype.delete=function(e){this.edits.push(Ht.del(e))},e.prototype.add=function(e){this.edits.push(e)},e.prototype.all=function(){return this.edits},e.prototype.clear=function(){this.edits.splice(0,this.edits.length)},e}();(function(){function e(e){var t=this;this._textEditChanges=Object.create(null),e&&(this._workspaceEdit=e,e.documentChanges?e.documentChanges.forEach(function(e){if(zt.is(e)){var n=new bn(e.edits);t._textEditChanges[e.textDocument.uri]=n}}):e.changes&&Object.keys(e.changes).forEach(function(n){var r=new bn(e.changes[n]);t._textEditChanges[n]=r}))}Object.defineProperty(e.prototype,"edit",{get:function(){return this._workspaceEdit},enumerable:!0,configurable:!0}),e.prototype.getTextEditChange=function(e){if(nn.is(e)){if(this._workspaceEdit||(this._workspaceEdit={documentChanges:[]}),!this._workspaceEdit.documentChanges)throw new Error("Workspace edit is not configured for document changes.");var t=e,n=this._textEditChanges[t.uri];if(!n){var r=[],i={textDocument:t,edits:r};this._workspaceEdit.documentChanges.push(i),n=new bn(r),this._textEditChanges[t.uri]=n}return n}if(this._workspaceEdit||(this._workspaceEdit={changes:Object.create(null)}),!this._workspaceEdit.changes)throw new Error("Workspace edit is not configured for normal text edit changes.");n=this._textEditChanges[e];if(!n){r=[];this._workspaceEdit.changes[e]=r,n=new bn(r),this._textEditChanges[e]=n}return n},e.prototype.createFile=function(e,t){this.checkDocumentChanges(),this._workspaceEdit.documentChanges.push(Gt.create(e,t))},e.prototype.renameFile=function(e,t,n){this.checkDocumentChanges(),this._workspaceEdit.documentChanges.push(Jt.create(e,t,n))},e.prototype.deleteFile=function(e,t){this.checkDocumentChanges(),this._workspaceEdit.documentChanges.push(Qt.create(e,t))},e.prototype.checkDocumentChanges=function(){if(!this._workspaceEdit||!this._workspaceEdit.documentChanges)throw new Error("Workspace edit is not configured for document changes.")}})();(function(e){function t(e){return{uri:e}}function n(e){var t=e;return kn.defined(t)&&kn.string(t.uri)}e.create=t,e.is=n})(tn||(tn={})),function(e){function t(e,t){return{uri:e,version:t}}function n(e){var t=e;return kn.defined(t)&&kn.string(t.uri)&&(null===t.version||kn.number(t.version))}e.create=t,e.is=n}(nn||(nn={})),function(e){function t(e,t,n,r){return{uri:e,languageId:t,version:n,text:r}}function n(e){var t=e;return kn.defined(t)&&kn.string(t.uri)&&kn.string(t.languageId)&&kn.number(t.version)&&kn.string(t.text)}e.create=t,e.is=n}(rn||(rn={})),function(e){e.PlainText="plaintext",e.Markdown="markdown"}(on||(on={})),function(e){function t(t){var n=t;return n===e.PlainText||n===e.Markdown}e.is=t}(on||(on={})),function(e){function t(e){var t=e;return kn.objectLiteral(e)&&on.is(t.kind)&&kn.string(t.value)}e.is=t}(sn||(sn={})),function(e){e.Text=1,e.Method=2,e.Function=3,e.Constructor=4,e.Field=5,e.Variable=6,e.Class=7,e.Interface=8,e.Module=9,e.Property=10,e.Unit=11,e.Value=12,e.Enum=13,e.Keyword=14,e.Snippet=15,e.Color=16,e.File=17,e.Reference=18,e.Folder=19,e.EnumMember=20,e.Constant=21,e.Struct=22,e.Event=23,e.Operator=24,e.TypeParameter=25}(an||(an={})),function(e){e.PlainText=1,e.Snippet=2}(un||(un={})),function(e){function t(e){return{label:e}}e.create=t}(cn||(cn={})),function(e){function t(e,t){return{items:e||[],isIncomplete:!!t}}e.create=t}(ln||(ln={})),function(e){function t(e){return e.replace(/[\\`*_{}[\]()#+\-.!]/g,"\\$&")}function n(e){var t=e;return kn.string(t)||kn.objectLiteral(t)&&kn.string(t.language)&&kn.string(t.value)}e.fromPlainText=t,e.is=n}(fn||(fn={})),function(e){function t(e){var t=e;return!!t&&kn.objectLiteral(t)&&(sn.is(t.contents)||fn.is(t.contents)||kn.typedArray(t.contents,fn.is))&&(void 0===e.range||Rt.is(e.range))}e.is=t}(hn||(hn={})),function(e){function t(e,t){return t?{label:e,documentation:t}:{label:e}}e.create=t}(dn||(dn={})),function(e){function t(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var i={label:e};return kn.defined(t)&&(i.documentation=t),kn.defined(n)?i.parameters=n:i.parameters=[],i}e.create=t}(pn||(pn={})),function(e){e.Text=1,e.Read=2,e.Write=3}(mn||(mn={})),function(e){function t(e,t){var n={range:e};return kn.number(t)&&(n.kind=t),n}e.create=t}(gn||(gn={})),function(e){e.File=1,e.Module=2,e.Namespace=3,e.Package=4,e.Class=5,e.Method=6,e.Property=7,e.Field=8,e.Constructor=9,e.Enum=10,e.Interface=11,e.Function=12,e.Variable=13,e.Constant=14,e.String=15,e.Number=16,e.Boolean=17,e.Array=18,e.Object=19,e.Key=20,e.Null=21,e.EnumMember=22,e.Struct=23,e.Event=24,e.Operator=25,e.TypeParameter=26}(vn||(vn={})),function(e){function t(e,t,n,r,i){var o={name:e,kind:t,location:{uri:r,range:n}};return i&&(o.containerName=i),o}e.create=t}(yn||(yn={}));var _n,Cn,Sn,En,xn,Nn=function(){function e(){}return e}();(function(e){function t(e,t,n,r,i,o){var s={name:e,detail:t,kind:n,range:r,selectionRange:i};return void 0!==o&&(s.children=o),s}function n(e){var t=e;return t&&kn.string(t.name)&&kn.number(t.kind)&&Rt.is(t.range)&&Rt.is(t.selectionRange)&&(void 0===t.detail||kn.string(t.detail))&&(void 0===t.deprecated||kn.boolean(t.deprecated))&&(void 0===t.children||Array.isArray(t.children))}e.create=t,e.is=n})(Nn||(Nn={})),function(e){e.QuickFix="quickfix",e.Refactor="refactor",e.RefactorExtract="refactor.extract",e.RefactorInline="refactor.inline",e.RefactorRewrite="refactor.rewrite",e.Source="source",e.SourceOrganizeImports="source.organizeImports"}(_n||(_n={})),function(e){function t(e,t){var n={diagnostics:e};return void 0!==t&&null!==t&&(n.only=t),n}function n(e){var t=e;return kn.defined(t)&&kn.typedArray(t.diagnostics,$t.is)&&(void 0===t.only||kn.typedArray(t.only,kn.string))}e.create=t,e.is=n}(Cn||(Cn={})),function(e){function t(e,t,n){var r={title:e};return Yt.is(t)?r.command=t:r.edit=t,void 0!==n&&(r.kind=n),r}function n(e){var t=e;return t&&kn.string(t.title)&&(void 0===t.diagnostics||kn.typedArray(t.diagnostics,$t.is))&&(void 0===t.kind||kn.string(t.kind))&&(void 0!==t.edit||void 0!==t.command)&&(void 0===t.command||Yt.is(t.command))&&(void 0===t.edit||Xt.is(t.edit))}e.create=t,e.is=n}(Sn||(Sn={})),function(e){function t(e,t){var n={range:e};return kn.defined(t)&&(n.data=t),n}function n(e){var t=e;return kn.defined(t)&&Rt.is(t.range)&&(kn.undefined(t.command)||Yt.is(t.command))}e.create=t,e.is=n}(En||(En={})),function(e){function t(e,t){return{tabSize:e,insertSpaces:t}}function n(e){var t=e;return kn.defined(t)&&kn.number(t.tabSize)&&kn.boolean(t.insertSpaces)}e.create=t,e.is=n}(xn||(xn={}));var wn=function(){function e(){}return e}();(function(e){function t(e,t,n){return{range:e,target:t,data:n}}function n(e){var t=e;return kn.defined(t)&&Rt.is(t.range)&&(kn.undefined(t.target)||kn.string(t.target))}e.create=t,e.is=n})(wn||(wn={}));var An,Ln;(function(e){function t(e,t,n,r){return new On(e,t,n,r)}function n(e){var t=e;return!!(kn.defined(t)&&kn.string(t.uri)&&(kn.undefined(t.languageId)||kn.string(t.languageId))&&kn.number(t.lineCount)&&kn.func(t.getText)&&kn.func(t.positionAt)&&kn.func(t.offsetAt))}function r(e,t){for(var n=e.getText(),r=i(t,function(e,t){var n=e.range.start.line-t.range.start.line;return 0===n?e.range.start.character-t.range.start.character:n}),o=n.length,s=r.length-1;s>=0;s--){var a=r[s],u=e.offsetAt(a.range.start),c=e.offsetAt(a.range.end);if(!(c<=o))throw new Error("Overlapping edit");n=n.substring(0,u)+a.newText+n.substring(c,n.length),o=u}return n}function i(e,t){if(e.length<=1)return e;var n=e.length/2|0,r=e.slice(0,n),o=e.slice(n);i(r,t),i(o,t);var s=0,a=0,u=0;while(s<r.length&&a<o.length){var c=t(r[s],o[a]);e[u++]=c<=0?r[s++]:o[a++]}while(s<r.length)e[u++]=r[s++];while(a<o.length)e[u++]=o[a++];return e}e.create=t,e.is=n,e.applyEdits=r})(An||(An={})),function(e){e.Manual=1,e.AfterDelay=2,e.FocusOut=3}(Ln||(Ln={}));var kn,Tn,On=function(){function e(e,t,n,r){this._uri=e,this._languageId=t,this._version=n,this._content=r,this._lineOffsets=null}return Object.defineProperty(e.prototype,"uri",{get:function(){return this._uri},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"languageId",{get:function(){return this._languageId},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"version",{get:function(){return this._version},enumerable:!0,configurable:!0}),e.prototype.getText=function(e){if(e){var t=this.offsetAt(e.start),n=this.offsetAt(e.end);return this._content.substring(t,n)}return this._content},e.prototype.update=function(e,t){this._content=e.text,this._version=t,this._lineOffsets=null},e.prototype.getLineOffsets=function(){if(null===this._lineOffsets){for(var e=[],t=this._content,n=!0,r=0;r<t.length;r++){n&&(e.push(r),n=!1);var i=t.charAt(r);n="\r"===i||"\n"===i,"\r"===i&&r+1<t.length&&"\n"===t.charAt(r+1)&&r++}n&&t.length>0&&e.push(t.length),this._lineOffsets=e}return this._lineOffsets},e.prototype.positionAt=function(e){e=Math.max(Math.min(e,this._content.length),0);var t=this.getLineOffsets(),n=0,r=t.length;if(0===r)return Mt.create(0,e);while(n<r){var i=Math.floor((n+r)/2);t[i]>e?r=i:n=i+1}var o=n-1;return Mt.create(o,e-t[o])},e.prototype.offsetAt=function(e){var t=this.getLineOffsets();if(e.line>=t.length)return this._content.length;if(e.line<0)return 0;var n=t[e.line],r=e.line+1<t.length?t[e.line+1]:this._content.length;return Math.max(Math.min(n+e.character,r),n)},Object.defineProperty(e.prototype,"lineCount",{get:function(){return this.getLineOffsets().length},enumerable:!0,configurable:!0}),e}();function Pn(e,t){void 0===t&&(t=!1);var n=0,r=e.length,i="",o=0,s=16,a=0;function u(t,r){var i=0,o=0;while(i<t||!r){var s=e.charCodeAt(n);if(s>=48&&s<=57)o=16*o+s-48;else if(s>=65&&s<=70)o=16*o+s-65+10;else{if(!(s>=97&&s<=102))break;o=16*o+s-97+10}n++,i++}return i<t&&(o=-1),o}function c(e){n=e,i="",o=0,s=16,a=0}function l(){var t=n;if(48===e.charCodeAt(n))n++;else{n++;while(n<e.length&&Rn(e.charCodeAt(n)))n++}if(n<e.length&&46===e.charCodeAt(n)){if(n++,!(n<e.length&&Rn(e.charCodeAt(n))))return a=3,e.substring(t,n);n++;while(n<e.length&&Rn(e.charCodeAt(n)))n++}var r=n;if(n<e.length&&(69===e.charCodeAt(n)||101===e.charCodeAt(n)))if(n++,(n<e.length&&43===e.charCodeAt(n)||45===e.charCodeAt(n))&&n++,n<e.length&&Rn(e.charCodeAt(n))){n++;while(n<e.length&&Rn(e.charCodeAt(n)))n++;r=n}else a=3;return e.substring(t,r)}function f(){var t="",i=n;while(1){if(n>=r){t+=e.substring(i,n),a=2;break}var o=e.charCodeAt(n);if(34===o){t+=e.substring(i,n),n++;break}if(92!==o){if(o>=0&&o<=31){if(Mn(o)){t+=e.substring(i,n),a=2;break}a=6}n++}else{if(t+=e.substring(i,n),n++,n>=r){a=2;break}switch(o=e.charCodeAt(n++),o){case 34:t+='"';break;case 92:t+="\\";break;case 47:t+="/";break;case 98:t+="\b";break;case 102:t+="\f";break;case 110:t+="\n";break;case 114:t+="\r";break;case 116:t+="\t";break;case 117:var s=u(4,!0);s>=0?t+=String.fromCharCode(s):a=4;break;default:a=5}i=n}}return t}function h(){if(i="",a=0,o=n,n>=r)return o=r,s=17;var t=e.charCodeAt(n);if(In(t)){do{n++,i+=String.fromCharCode(t),t=e.charCodeAt(n)}while(In(t));return s=15}if(Mn(t))return n++,i+=String.fromCharCode(t),13===t&&10===e.charCodeAt(n)&&(n++,i+="\n"),s=14;switch(t){case 123:return n++,s=1;case 125:return n++,s=2;case 91:return n++,s=3;case 93:return n++,s=4;case 58:return n++,s=6;case 44:return n++,s=5;case 34:return n++,i=f(),s=10;case 47:var u=n-1;if(47===e.charCodeAt(n+1)){n+=2;while(n<r){if(Mn(e.charCodeAt(n)))break;n++}return i=e.substring(u,n),s=12}if(42===e.charCodeAt(n+1)){n+=2;var c=r-1,h=!1;while(n<c){var p=e.charCodeAt(n);if(42===p&&47===e.charCodeAt(n+1)){n+=2,h=!0;break}n++}return h||(n++,a=1),i=e.substring(u,n),s=13}return i+=String.fromCharCode(t),n++,s=16;case 45:if(i+=String.fromCharCode(t),n++,n===r||!Rn(e.charCodeAt(n)))return s=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return i+=l(),s=11;default:while(n<r&&d(t))n++,t=e.charCodeAt(n);if(o!==n){switch(i=e.substring(o,n),i){case"true":return s=8;case"false":return s=9;case"null":return s=7}return s=16}return i+=String.fromCharCode(t),n++,s=16}}function d(e){if(In(e)||Mn(e))return!1;switch(e){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function p(){var e;do{e=h()}while(e>=12&&e<=15);return e}return{setPosition:c,getPosition:function(){return n},scan:t?p:h,getToken:function(){return s},getTokenValue:function(){return i},getTokenOffset:function(){return o},getTokenLength:function(){return n-o},getTokenError:function(){return a}}}function In(e){return 32===e||9===e||11===e||12===e||160===e||5760===e||e>=8192&&e<=8203||8239===e||8287===e||12288===e||65279===e}function Mn(e){return 10===e||13===e||8232===e||8233===e}function Rn(e){return e>=48&&e<=57}function jn(e,t,n){var r,i,o,s,a;if(t){s=t.offset,a=s+t.length,o=s;while(o>0&&!Un(e,o-1))o--;var u=a;while(u<e.length&&!Un(e,u))u++;i=e.substring(o,u),r=Vn(i,n)}else i=e,r=0,o=0,s=0,a=e.length;var c,l=Dn(n,e),f=!1,h=0;c=n.insertSpaces?Fn(" ",n.tabSize||4):"\t";var d=Pn(i,!1),p=!1;function m(){return l+Fn(c,r+h)}function g(){var e=d.scan();f=!1;while(15===e||14===e)f=f||14===e,e=d.scan();return p=16===e||0!==d.getTokenError(),e}var v=[];function y(t,n,r){!p&&n<a&&r>s&&e.substring(n,r)!==t&&v.push({offset:n,length:r-n,content:t})}var b=g();if(17!==b){var _=d.getTokenOffset()+o,C=Fn(c,r);y(C,o,_)}while(17!==b){var S=d.getTokenOffset()+d.getTokenLength()+o,E=g(),x="";while(!f&&(12===E||13===E)){var N=d.getTokenOffset()+o;y(" ",S,N),S=d.getTokenOffset()+d.getTokenLength()+o,x=12===E?m():"",E=g()}if(2===E)1!==b&&(h--,x=m());else if(4===E)3!==b&&(h--,x=m());else{switch(b){case 3:case 1:h++,x=m();break;case 5:case 12:x=m();break;case 13:x=f?m():" ";break;case 6:x=" ";break;case 10:if(6===E){x="";break}case 7:case 8:case 9:case 11:case 2:case 4:12===E||13===E?x=" ":5!==E&&17!==E&&(p=!0);break;case 16:p=!0;break}!f||12!==E&&13!==E||(x=m())}var w=d.getTokenOffset()+o;y(x,S,w),b=E}return v}function Fn(e,t){for(var n="",r=0;r<t;r++)n+=e;return n}function Vn(e,t){var n=0,r=0,i=t.tabSize||4;while(n<e.length){var o=e.charAt(n);if(" "===o)r++;else{if("\t"!==o)break;r+=i}n++}return Math.floor(r/i)}function Dn(e,t){for(var n=0;n<t.length;n++){var r=t.charAt(n);if("\r"===r)return n+1<t.length&&"\n"===t.charAt(n+1)?"\r\n":"\r";if("\n"===r)return"\n"}return e&&e.eol||"\n"}function Un(e,t){return-1!=="\r\n".indexOf(e.charAt(t))}function qn(e,t,n){void 0===t&&(t=[]),void 0===n&&(n=Tn.DEFAULT);var r=null,i=[],o=[];function s(e){Array.isArray(i)?i.push(e):r&&(i[r]=e)}var a={onObjectBegin:function(){var e={};s(e),o.push(i),i=e,r=null},onObjectProperty:function(e){r=e},onObjectEnd:function(){i=o.pop()},onArrayBegin:function(){var e=[];s(e),o.push(i),i=e,r=null},onArrayEnd:function(){i=o.pop()},onLiteralValue:s,onError:function(e,n,r){t.push({error:e,offset:n,length:r})}};return Yn(e,a,n),i[0]}function Kn(e){if(!e.parent||!e.parent.children)return[];var t=Kn(e.parent);if("property"===e.parent.type){var n=e.parent.children[0].value;t.push(n)}else if("array"===e.parent.type){var r=e.parent.children.indexOf(e);-1!==r&&t.push(r)}return t}function Wn(e){switch(e.type){case"array":return e.children.map(Wn);case"object":for(var t=Object.create(null),n=0,r=e.children;n<r.length;n++){var i=r[n],o=i.children[1];o&&(t[i.children[0].value]=Wn(o))}return t;case"null":case"string":case"number":case"boolean":return e.value;default:return}}function Bn(e,t,n){return void 0===n&&(n=!1),t>=e.offset&&t<e.offset+e.length||n&&t===e.offset+e.length}function $n(e,t,n){if(void 0===n&&(n=!1),Bn(e,t,n)){var r=e.children;if(Array.isArray(r))for(var i=0;i<r.length&&r[i].offset<=t;i++){var o=$n(r[i],t,n);if(o)return o}return e}}function Yn(e,t,n){void 0===n&&(n=Tn.DEFAULT);var r=Pn(e,!1);function i(e){return e?function(){return e(r.getTokenOffset(),r.getTokenLength())}:function(){return!0}}function o(e){return e?function(t){return e(t,r.getTokenOffset(),r.getTokenLength())}:function(){return!0}}var s=i(t.onObjectBegin),a=o(t.onObjectProperty),u=i(t.onObjectEnd),c=i(t.onArrayBegin),l=i(t.onArrayEnd),f=o(t.onLiteralValue),h=o(t.onSeparator),d=i(t.onComment),p=o(t.onError),m=n&&n.disallowComments,g=n&&n.allowTrailingComma;function v(){while(1){var e=r.scan();switch(r.getTokenError()){case 4:y(14);break;case 5:y(15);break;case 3:y(13);break;case 1:m||y(11);break;case 2:y(12);break;case 6:y(16);break}switch(e){case 12:case 13:m?y(10):d();break;case 16:y(1);break;case 15:case 14:break;default:return e}}}function y(e,t,n){if(void 0===t&&(t=[]),void 0===n&&(n=[]),p(e),t.length+n.length>0){var i=r.getToken();while(17!==i){if(-1!==t.indexOf(i)){v();break}if(-1!==n.indexOf(i))break;i=v()}}}function b(e){var t=r.getTokenValue();return e?f(t):a(t),v(),!0}function _(){switch(r.getToken()){case 11:var e=0;try{e=JSON.parse(r.getTokenValue()),"number"!==typeof e&&(y(2),e=0)}catch(t){y(2)}f(e);break;case 7:f(null);break;case 8:f(!0);break;case 9:f(!1);break;default:return!1}return v(),!0}function C(){return 10!==r.getToken()?(y(3,[],[2,5]),!1):(b(!1),6===r.getToken()?(h(":"),v(),x()||y(4,[],[2,5])):y(5,[],[2,5]),!0)}function S(){s(),v();var e=!1;while(2!==r.getToken()&&17!==r.getToken()){if(5===r.getToken()){if(e||y(4,[],[]),h(","),v(),2===r.getToken()&&g)break}else e&&y(6,[],[]);C()||y(4,[],[2,5]),e=!0}return u(),2!==r.getToken()?y(7,[2],[]):v(),!0}function E(){c(),v();var e=!1;while(4!==r.getToken()&&17!==r.getToken()){if(5===r.getToken()){if(e||y(4,[],[]),h(","),v(),4===r.getToken()&&g)break}else e&&y(6,[],[]);x()||y(4,[],[4,5]),e=!0}return l(),4!==r.getToken()?y(8,[4],[]):v(),!0}function x(){switch(r.getToken()){case 3:return E();case 1:return S();case 10:return b(!0);default:return _()}}return v(),17===r.getToken()||(x()?(17!==r.getToken()&&y(9,[],[]),!0):(y(4,[],[]),!1))}(function(e){var t=Object.prototype.toString;function n(e){return"undefined"!==typeof e}function r(e){return"undefined"===typeof e}function i(e){return!0===e||!1===e}function o(e){return"[object String]"===t.call(e)}function s(e){return"[object Number]"===t.call(e)}function a(e){return"[object Function]"===t.call(e)}function u(e){return null!==e&&"object"===typeof e}function c(e,t){return Array.isArray(e)&&e.every(t)}e.defined=n,e.undefined=r,e.boolean=i,e.string=o,e.number=s,e.func=a,e.objectLiteral=u,e.typedArray=c})(kn||(kn={})),function(e){e.DEFAULT={allowTrailingComma:!1}}(Tn||(Tn={}));var Hn,zn,Gn,Jn=Pn,Qn=qn,Xn=$n,Zn=Kn,er=Wn;function tr(e,t,n){return jn(e,t,n)}function nr(e,t){if(e===t)return!0;if(null===e||void 0===e||null===t||void 0===t)return!1;if(typeof e!==typeof t)return!1;if("object"!==typeof e)return!1;if(Array.isArray(e)!==Array.isArray(t))return!1;var n,r;if(Array.isArray(e)){if(e.length!==t.length)return!1;for(n=0;n<e.length;n++)if(!nr(e[n],t[n]))return!1}else{var i=[];for(r in e)i.push(r);i.sort();var o=[];for(r in t)o.push(r);if(o.sort(),!nr(i,o))return!1;for(n=0;n<i.length;n++)if(!nr(e[i[n]],t[i[n]]))return!1}return!0}function rr(e){return"number"===typeof e}function ir(e){return"undefined"!==typeof e}function or(e){return"boolean"===typeof e}function sr(e){return"string"===typeof e}function ar(e,t){var n;return n=0===t.length?e:e.replace(/\{(\d+)\}/g,function(e,n){var r=n[0];return"undefined"!==typeof t[r]?t[r]:e}),n}function ur(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return ar(t,n)}function cr(e){return ur}(function(e){e["Empty"]="",e["Statement"]="statement",e["Declaration"]="declaration"})(Hn||(Hn={})),function(e){e[e["Undefined"]=0]="Undefined",e[e["EnumValueMismatch"]=1]="EnumValueMismatch",e[e["UnexpectedEndOfComment"]=257]="UnexpectedEndOfComment",e[e["UnexpectedEndOfString"]=258]="UnexpectedEndOfString",e[e["UnexpectedEndOfNumber"]=259]="UnexpectedEndOfNumber",e[e["InvalidUnicode"]=260]="InvalidUnicode",e[e["InvalidEscapeCharacter"]=261]="InvalidEscapeCharacter",e[e["InvalidCharacter"]=262]="InvalidCharacter",e[e["PropertyExpected"]=513]="PropertyExpected",e[e["CommaExpected"]=514]="CommaExpected",e[e["ColonExpected"]=515]="ColonExpected",e[e["ValueExpected"]=516]="ValueExpected",e[e["CommaOrCloseBacketExpected"]=517]="CommaOrCloseBacketExpected",e[e["CommaOrCloseBraceExpected"]=518]="CommaOrCloseBraceExpected",e[e["TrailingComma"]=519]="TrailingComma",e[e["DuplicateKey"]=520]="DuplicateKey",e[e["CommentNotPermitted"]=521]="CommentNotPermitted",e[e["SchemaResolveError"]=768]="SchemaResolveError"}(zn||(zn={})),function(e){e.LATEST={textDocument:{completion:{completionItem:{documentationFormat:[on.Markdown,on.PlainText]}}}}}(Gn||(Gn={}));var lr,fr=n("c623"),hr=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),dr=cr(),pr=/^#([0-9A-Fa-f]{3,4}|([0-9A-Fa-f]{2}){3,4})$/,mr=/^(([^<>()\[\]\\.,;:\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,}))$/,gr=function(){function e(e,t,n){this.offset=t,this.length=n,this.parent=e}return Object.defineProperty(e.prototype,"children",{get:function(){return[]},enumerable:!0,configurable:!0}),e.prototype.toString=function(){return"type: "+this.type+" ("+this.offset+"/"+this.length+")"+(this.parent?" parent: {"+this.parent.toString()+"}":"")},e}(),vr=function(e){function t(t,n){var r=e.call(this,t,n)||this;return r.type="null",r.value=null,r}return hr(t,e),t}(gr),yr=function(e){function t(t,n,r){var i=e.call(this,t,r)||this;return i.type="boolean",i.value=n,i}return hr(t,e),t}(gr),br=function(e){function t(t,n){var r=e.call(this,t,n)||this;return r.type="array",r.items=[],r}return hr(t,e),Object.defineProperty(t.prototype,"children",{get:function(){return this.items},enumerable:!0,configurable:!0}),t}(gr),_r=function(e){function t(t,n){var r=e.call(this,t,n)||this;return r.type="number",r.isInteger=!0,r.value=Number.NaN,r}return hr(t,e),t}(gr),Cr=function(e){function t(t,n,r){var i=e.call(this,t,n,r)||this;return i.type="string",i.value="",i}return hr(t,e),t}(gr),Sr=function(e){function t(t,n){var r=e.call(this,t,n)||this;return r.type="property",r.colonOffset=-1,r}return hr(t,e),Object.defineProperty(t.prototype,"children",{get:function(){return this.valueNode?[this.keyNode,this.valueNode]:[this.keyNode]},enumerable:!0,configurable:!0}),t}(gr),Er=function(e){function t(t,n){var r=e.call(this,t,n)||this;return r.type="object",r.properties=[],r}return hr(t,e),Object.defineProperty(t.prototype,"children",{get:function(){return this.properties},enumerable:!0,configurable:!0}),t}(gr);function xr(e){return or(e)?e?{}:{not:{}}:e}(function(e){e[e["Key"]=0]="Key",e[e["Enum"]=1]="Enum"})(lr||(lr={}));var Nr=function(){function e(e,t){void 0===e&&(e=-1),void 0===t&&(t=null),this.focusOffset=e,this.exclude=t,this.schemas=[]}return e.prototype.add=function(e){this.schemas.push(e)},e.prototype.merge=function(e){var t;(t=this.schemas).push.apply(t,e.schemas)},e.prototype.include=function(e){return(-1===this.focusOffset||Or(e,this.focusOffset))&&e!==this.exclude},e.prototype.newSub=function(){return new e(-1,this.exclude)},e}(),wr=function(){function e(){}return Object.defineProperty(e.prototype,"schemas",{get:function(){return[]},enumerable:!0,configurable:!0}),e.prototype.add=function(e){},e.prototype.merge=function(e){},e.prototype.include=function(e){return!0},e.prototype.newSub=function(){return this},e.instance=new e,e}(),Ar=function(){function e(){this.problems=[],this.propertiesMatches=0,this.propertiesValueMatches=0,this.primaryValueMatches=0,this.enumValueMatch=!1,this.enumValues=null}return e.prototype.hasProblems=function(){return!!this.problems.length},e.prototype.mergeAll=function(e){for(var t=0,n=e;t<n.length;t++){var r=n[t];this.merge(r)}},e.prototype.merge=function(e){this.problems=this.problems.concat(e.problems)},e.prototype.mergeEnumValues=function(e){if(!this.enumValueMatch&&!e.enumValueMatch&&this.enumValues&&e.enumValues){this.enumValues=this.enumValues.concat(e.enumValues);for(var t=0,n=this.problems;t<n.length;t++){var r=n[t];r.code===zn.EnumValueMismatch&&(r.message=dr("enumWarning","Value is not accepted. Valid values: {0}.",this.enumValues.map(function(e){return JSON.stringify(e)}).join(", ")))}}},e.prototype.mergePropertyMatch=function(e){this.merge(e),this.propertiesMatches++,(e.enumValueMatch||!e.hasProblems()&&e.propertiesMatches)&&this.propertiesValueMatches++,e.enumValueMatch&&e.enumValues&&1===e.enumValues.length&&this.primaryValueMatches++},e.prototype.compare=function(e){var t=this.hasProblems();return t!==e.hasProblems()?t?-1:1:this.enumValueMatch!==e.enumValueMatch?e.enumValueMatch?-1:1:this.primaryValueMatches!==e.primaryValueMatches?this.primaryValueMatches-e.primaryValueMatches:this.propertiesValueMatches!==e.propertiesValueMatches?this.propertiesValueMatches-e.propertiesValueMatches:this.propertiesMatches-e.propertiesMatches},e}();function Lr(e,t){return void 0===t&&(t=[]),new Pr(e,t,[])}function kr(e){return er(e)}function Tr(e){return Zn(e)}function Or(e,t,n){return void 0===n&&(n=!1),t>=e.offset&&t<e.offset+e.length||n&&t===e.offset+e.length}var Pr=function(){function e(e,t,n){void 0===t&&(t=[]),void 0===n&&(n=[]),this.root=e,this.syntaxErrors=t,this.comments=n}return e.prototype.getNodeFromOffset=function(e,t){if(void 0===t&&(t=!1),this.root)return Xn(this.root,e,t)},e.prototype.visit=function(e){if(this.root){var t=function(n){var r=e(n),i=n.children;if(Array.isArray(i))for(var o=0;o<i.length&&r;o++)r=t(i[o]);return r};t(this.root)}},e.prototype.validate=function(e,t){if(this.root&&t){var n=new Ar;return Ir(this.root,t,n,wr.instance),n.problems.map(function(t){var n=Rt.create(e.positionAt(t.location.offset),e.positionAt(t.location.offset+t.location.length));return $t.create(n,t.message,t.severity,t.code)})}return null},e.prototype.getMatchingSchemas=function(e,t,n){void 0===t&&(t=-1),void 0===n&&(n=null);var r=new Nr(t,n);return this.root&&e&&Ir(this.root,e,new Ar,r),r.schemas},e}();function Ir(e,t,n,r){if(e&&r.include(e)){switch(e.type){case"object":u(e,t,n,r);break;case"array":a(e,t,n,r);break;case"string":s(e,t,n,r);break;case"number":o(e,t,n,r);break;case"property":return Ir(e.valueNode,t,n,r)}i(),r.add({node:e,schema:t})}function i(){function i(t){return e.type===t||"integer"===t&&"number"===e.type&&e.isInteger}if(Array.isArray(t.type)?t.type.some(i)||n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:t.errorMessage||dr("typeArrayMismatchWarning","Incorrect type. Expected one of {0}.",t.type.join(", "))}):t.type&&(i(t.type)||n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:t.errorMessage||dr("typeMismatchWarning",'Incorrect type. Expected "{0}".',t.type)})),Array.isArray(t.allOf))for(var o=0,s=t.allOf;o<s.length;o++){var a=s[o];Ir(e,xr(a),n,r)}var u=xr(t.not);if(u){var c=new Ar,l=r.newSub();Ir(e,u,c,l),c.hasProblems()||n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:dr("notSchemaWarning","Matches a schema that is not allowed.")});for(var f=0,h=l.schemas;f<h.length;f++){var d=h[f];d.inverted=!d.inverted,r.add(d)}}var p=function(t,i){for(var o=[],s=null,a=0,u=t;a<u.length;a++){var c=u[a],l=xr(c),f=new Ar,h=r.newSub();if(Ir(e,l,f,h),f.hasProblems()||o.push(l),s)if(i||f.hasProblems()||s.validationResult.hasProblems()){var d=f.compare(s.validationResult);d>0?s={schema:l,validationResult:f,matchingSchemas:h}:0===d&&(s.matchingSchemas.merge(h),s.validationResult.mergeEnumValues(f))}else s.matchingSchemas.merge(h),s.validationResult.propertiesMatches+=f.propertiesMatches,s.validationResult.propertiesValueMatches+=f.propertiesValueMatches;else s={schema:l,validationResult:f,matchingSchemas:h}}return o.length>1&&i&&n.problems.push({location:{offset:e.offset,length:1},severity:Bt.Warning,message:dr("oneOfWarning","Matches multiple schemas when only one must validate.")}),null!==s&&(n.merge(s.validationResult),n.propertiesMatches+=s.validationResult.propertiesMatches,n.propertiesValueMatches+=s.validationResult.propertiesValueMatches,r.merge(s.matchingSchemas)),o.length};Array.isArray(t.anyOf)&&p(t.anyOf,!1),Array.isArray(t.oneOf)&&p(t.oneOf,!0);var m=function(t){var i=new Ar,o=r.newSub();Ir(e,xr(t),i,o),n.merge(i),n.propertiesMatches+=i.propertiesMatches,n.propertiesValueMatches+=i.propertiesValueMatches,r.merge(o)},g=function(t,n,i){var o=xr(t),s=new Ar,a=r.newSub();Ir(e,o,s,a),r.merge(a),s.hasProblems()?i&&m(i):n&&m(n)},v=xr(t.if);if(v&&g(v,xr(t.then),xr(t.else)),Array.isArray(t.enum)){for(var y=kr(e),b=!1,_=0,C=t.enum;_<C.length;_++){var S=C[_];if(nr(y,S)){b=!0;break}}n.enumValues=t.enum,n.enumValueMatch=b,b||n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,code:zn.EnumValueMismatch,message:t.errorMessage||dr("enumWarning","Value is not accepted. Valid values: {0}.",t.enum.map(function(e){return JSON.stringify(e)}).join(", "))})}if(ir(t.const)){y=kr(e);nr(y,t.const)?n.enumValueMatch=!0:(n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,code:zn.EnumValueMismatch,message:t.errorMessage||dr("constWarning","Value must be {0}.",JSON.stringify(t.const))}),n.enumValueMatch=!1),n.enumValues=[t.const]}t.deprecationMessage&&e.parent&&n.problems.push({location:{offset:e.parent.offset,length:e.parent.length},severity:Bt.Warning,message:t.deprecationMessage})}function o(e,t,n,r){var i=e.value;function o(e,t){return rr(t)?t:or(t)&&t?e:void 0}function s(e,t){if(!or(t)||!t)return e}rr(t.multipleOf)&&i%t.multipleOf!==0&&n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:dr("multipleOfWarning","Value is not divisible by {0}.",t.multipleOf)});var a=o(t.minimum,t.exclusiveMinimum);rr(a)&&i<=a&&n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:dr("exclusiveMinimumWarning","Value is below the exclusive minimum of {0}.",a)});var u=o(t.maximum,t.exclusiveMaximum);rr(u)&&i>=u&&n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:dr("exclusiveMaximumWarning","Value is above the exclusive maximum of {0}.",u)});var c=s(t.minimum,t.exclusiveMinimum);rr(c)&&i<c&&n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:dr("minimumWarning","Value is below the minimum of {0}.",c)});var l=s(t.maximum,t.exclusiveMaximum);rr(l)&&i>l&&n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:dr("maximumWarning","Value is above the maximum of {0}.",l)})}function s(e,t,n,r){if(rr(t.minLength)&&e.value.length<t.minLength&&n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:dr("minLengthWarning","String is shorter than the minimum length of {0}.",t.minLength)}),rr(t.maxLength)&&e.value.length>t.maxLength&&n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:dr("maxLengthWarning","String is longer than the maximum length of {0}.",t.maxLength)}),sr(t.pattern)){var i=new RegExp(t.pattern);i.test(e.value)||n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:t.patternErrorMessage||t.errorMessage||dr("patternWarning",'String does not match the pattern of "{0}".',t.pattern)})}if(t.format)switch(t.format){case"uri":case"uri-reference":var o=void 0;if(e.value)try{var s=fr["a"].parse(e.value);s.scheme||"uri"!==t.format||(o=dr("uriSchemeMissing","URI with a scheme is expected."))}catch(a){o=a.message}else o=dr("uriEmpty","URI expected.");o&&n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:t.patternErrorMessage||t.errorMessage||dr("uriFormatWarning","String is not a URI: {0}",o)});break;case"email":e.value.match(mr)||n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:t.patternErrorMessage||t.errorMessage||dr("emailFormatWarning","String is not an e-mail address.")});break;case"color-hex":e.value.match(pr)||n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:t.patternErrorMessage||t.errorMessage||dr("colorHexFormatWarning","Invalid color format. Use #RGB, #RGBA, #RRGGBB or #RRGGBBAA.")});break;default:}}function a(e,t,n,r){if(Array.isArray(t.items)){for(var i=t.items,o=0;o<i.length;o++){var s=i[o],a=xr(s),u=new Ar,c=e.items[o];c?(Ir(c,a,u,r),n.mergePropertyMatch(u)):e.items.length>=i.length&&n.propertiesValueMatches++}if(e.items.length>i.length)if("object"===typeof t.additionalItems)for(var l=i.length;l<e.items.length;l++){u=new Ar;Ir(e.items[l],t.additionalItems,u,r),n.mergePropertyMatch(u)}else!1===t.additionalItems&&n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:dr("additionalItemsWarning","Array has too many items according to schema. Expected {0} or fewer.",i.length)})}else{var f=xr(t.items);if(f)for(var h=0,d=e.items;h<d.length;h++){c=d[h],u=new Ar;Ir(c,f,u,r),n.mergePropertyMatch(u)}}var p=xr(t.contains);if(p){var m=e.items.some(function(e){var t=new Ar;return Ir(e,p,t,wr.instance),!t.hasProblems()});m||n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:t.errorMessage||dr("requiredItemMissingWarning","Array does not contain required item.")})}if(rr(t.minItems)&&e.items.length<t.minItems&&n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:dr("minItemsWarning","Array has too few items. Expected {0} or more.",t.minItems)}),rr(t.maxItems)&&e.items.length>t.maxItems&&n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:dr("maxItemsWarning","Array has too many items. Expected {0} or fewer.",t.maxItems)}),!0===t.uniqueItems){var g=kr(e),v=g.some(function(e,t){return t!==g.lastIndexOf(e)});v&&n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:dr("uniqueItemsWarning","Array has duplicate items.")})}}function u(e,t,n,r){for(var i=Object.create(null),o=[],s=0,a=e.properties;s<a.length;s++){var u=a[s],c=u.keyNode.value;i[c]=u.valueNode,o.push(c)}if(Array.isArray(t.required))for(var l=0,f=t.required;l<f.length;l++){var h=f[l];if(!i[h]){var d=e.parent&&"property"===e.parent.type&&e.parent.keyNode,p=d?{offset:d.offset,length:d.length}:{offset:e.offset,length:1};n.problems.push({location:p,severity:Bt.Warning,message:dr("MissingRequiredPropWarning",'Missing property "{0}".',h)})}}var m=function(e){var t=o.indexOf(e);while(t>=0)o.splice(t,1),t=o.indexOf(e)};if(t.properties)for(var g=0,v=Object.keys(t.properties);g<v.length;g++){h=v[g];m(h);var y=t.properties[h],b=i[h];if(b)if(or(y))if(y)n.propertiesMatches++,n.propertiesValueMatches++;else{u=b.parent;n.problems.push({location:{offset:u.keyNode.offset,length:u.keyNode.length},severity:Bt.Warning,message:t.errorMessage||dr("DisallowedExtraPropWarning","Property {0} is not allowed.",h)})}else{var _=new Ar;Ir(b,y,_,r),n.mergePropertyMatch(_)}}if(t.patternProperties)for(var C=0,S=Object.keys(t.patternProperties);C<S.length;C++)for(var E=S[C],x=new RegExp(E),N=0,w=o.slice(0);N<w.length;N++){h=w[N];if(x.test(h)){m(h);b=i[h];if(b){y=t.patternProperties[E];if(or(y))if(y)n.propertiesMatches++,n.propertiesValueMatches++;else{u=b.parent;n.problems.push({location:{offset:u.keyNode.offset,length:u.keyNode.length},severity:Bt.Warning,message:t.errorMessage||dr("DisallowedExtraPropWarning","Property {0} is not allowed.",h)})}else{_=new Ar;Ir(b,y,_,r),n.mergePropertyMatch(_)}}}}if("object"===typeof t.additionalProperties)for(var A=0,L=o;A<L.length;A++){h=L[A],b=i[h];if(b){_=new Ar;Ir(b,t.additionalProperties,_,r),n.mergePropertyMatch(_)}}else if(!1===t.additionalProperties&&o.length>0)for(var k=0,T=o;k<T.length;k++){h=T[k],b=i[h];if(b){u=b.parent;n.problems.push({location:{offset:u.keyNode.offset,length:u.keyNode.length},severity:Bt.Warning,message:t.errorMessage||dr("DisallowedExtraPropWarning","Property {0} is not allowed.",h)})}}if(rr(t.maxProperties)&&e.properties.length>t.maxProperties&&n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:dr("MaxPropWarning","Object has more properties than limit of {0}.",t.maxProperties)}),rr(t.minProperties)&&e.properties.length<t.minProperties&&n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:dr("MinPropWarning","Object has fewer properties than the required number of {0}",t.minProperties)}),t.dependencies)for(var O=0,P=Object.keys(t.dependencies);O<P.length;O++){c=P[O];var I=i[c];if(I){var M=t.dependencies[c];if(Array.isArray(M))for(var R=0,j=M;R<j.length;R++){var F=j[R];i[F]?n.propertiesValueMatches++:n.problems.push({location:{offset:e.offset,length:e.length},severity:Bt.Warning,message:dr("RequiredDependentPropWarning","Object is missing property {0} required by property {1}.",F,c)})}else{y=xr(M);if(y){_=new Ar;Ir(e,y,_,r),n.mergePropertyMatch(_)}}}}var V=xr(t.propertyNames);if(V)for(var D=0,U=e.properties;D<U.length;D++){var q=U[D];c=q.keyNode;c&&Ir(c,V,n,wr.instance)}}}function Mr(e,t){var n=[],r=-1,i=e.getText(),o=Jn(i,!1),s=t&&t.collectComments?[]:void 0;function a(){while(1){var t=o.scan();switch(l(),t){case 12:case 13:Array.isArray(s)&&s.push(Rt.create(e.positionAt(o.getTokenOffset()),e.positionAt(o.getTokenOffset()+o.getTokenLength())));break;case 15:case 14:break;default:return t}}}function u(t,i,o,s,a){if(void 0===a&&(a=Bt.Error),0===n.length||o!==r){var u=Rt.create(e.positionAt(o),e.positionAt(s));n.push($t.create(u,t,a,i,e.languageId)),r=o}}function c(e,t,n,r,s){void 0===n&&(n=null),void 0===r&&(r=[]),void 0===s&&(s=[]);var c=o.getTokenOffset(),l=o.getTokenOffset()+o.getTokenLength();if(c===l&&c>0){c--;while(c>0&&/\s/.test(i.charAt(c)))c--;l=c+1}if(u(e,t,c,l),n&&f(n,!1),r.length+s.length>0){var h=o.getToken();while(17!==h){if(-1!==r.indexOf(h)){a();break}if(-1!==s.indexOf(h))break;h=a()}}return n}function l(){switch(o.getTokenError()){case 4:return c(dr("InvalidUnicode","Invalid unicode sequence in string."),zn.InvalidUnicode),!0;case 5:return c(dr("InvalidEscapeCharacter","Invalid escape character in string."),zn.InvalidEscapeCharacter),!0;case 3:return c(dr("UnexpectedEndOfNumber","Unexpected end of number."),zn.UnexpectedEndOfNumber),!0;case 1:return c(dr("UnexpectedEndOfComment","Unexpected end of comment."),zn.UnexpectedEndOfComment),!0;case 2:return c(dr("UnexpectedEndOfString","Unexpected end of string."),zn.UnexpectedEndOfString),!0;case 6:return c(dr("InvalidCharacter","Invalid characters in string. Control characters must be escaped."),zn.InvalidCharacter),!0}return!1}function f(e,t){return e.length=o.getTokenOffset()+o.getTokenLength()-e.offset,t&&a(),e}function h(e){if(3!==o.getToken())return null;var t=new br(e,o.getTokenOffset());a();var n=0,r=!1;while(4!==o.getToken()&&17!==o.getToken()){if(5===o.getToken()){r||c(dr("ValueExpected","Value expected"),zn.ValueExpected);var i=o.getTokenOffset();if(a(),4===o.getToken()){r&&u(dr("TrailingComma","Trailing comma"),zn.TrailingComma,i,i+1);continue}}else r&&c(dr("ExpectedComma","Expected comma"),zn.CommaExpected);var s=y(t,n++);s?t.items.push(s):c(dr("PropertyExpected","Value expected"),zn.ValueExpected,null,[],[4,5]),r=!0}return 4!==o.getToken()?c(dr("ExpectedCloseBracket","Expected comma or closing bracket"),zn.CommaOrCloseBacketExpected,t):f(t,!0)}function d(t,n){var r=new Sr(t,o.getTokenOffset()),i=m(r);if(!i){if(16!==o.getToken())return null;c(dr("DoubleQuotesExpected","Property keys must be doublequoted"),zn.Undefined);var s=new Cr(r,o.getTokenOffset(),o.getTokenLength());s.value=o.getTokenValue(),i=s,a()}r.keyNode=i;var l=n[i.value];if(l?(u(dr("DuplicateKeyWarning","Duplicate object key"),zn.DuplicateKey,r.keyNode.offset,r.keyNode.offset+r.keyNode.length,Bt.Warning),"object"===typeof l&&u(dr("DuplicateKeyWarning","Duplicate object key"),zn.DuplicateKey,l.keyNode.offset,l.keyNode.offset+l.keyNode.length,Bt.Warning),n[i.value]=!0):n[i.value]=r,6===o.getToken())r.colonOffset=o.getTokenOffset(),a();else if(c(dr("ColonExpected","Colon expected"),zn.ColonExpected),10===o.getToken()&&e.positionAt(i.offset+i.length).line<e.positionAt(o.getTokenOffset()).line)return r.length=i.length,r;var f=y(r,i.value);return f?(r.valueNode=f,r.length=f.offset+f.length-r.offset,r):c(dr("ValueExpected","Value expected"),zn.ValueExpected,r,[],[2,5])}function p(e){if(1!==o.getToken())return null;var t=new Er(e,o.getTokenOffset()),n=Object.create(null);a();var r=!1;while(2!==o.getToken()&&17!==o.getToken()){if(5===o.getToken()){r||c(dr("PropertyExpected","Property expected"),zn.PropertyExpected);var i=o.getTokenOffset();if(a(),2===o.getToken()){r&&u(dr("TrailingComma","Trailing comma"),zn.TrailingComma,i,i+1);continue}}else r&&c(dr("ExpectedComma","Expected comma"),zn.CommaExpected);var s=d(t,n);s?t.properties.push(s):c(dr("PropertyExpected","Property expected"),zn.PropertyExpected,null,[],[2,5]),r=!0}return 2!==o.getToken()?c(dr("ExpectedCloseBrace","Expected comma or closing brace"),zn.CommaOrCloseBraceExpected,t):f(t,!0)}function m(e){if(10!==o.getToken())return null;var t=new Cr(e,o.getTokenOffset());return t.value=o.getTokenValue(),f(t,!0)}function g(e){if(11!==o.getToken())return null;var t=new _r(e,o.getTokenOffset());if(0===o.getTokenError()){var n=o.getTokenValue();try{var r=JSON.parse(n);if(!rr(r))return c(dr("InvalidNumberFormat","Invalid number format."),zn.Undefined,t);t.value=r}catch(i){return c(dr("InvalidNumberFormat","Invalid number format."),zn.Undefined,t)}t.isInteger=-1===n.indexOf(".")}return f(t,!0)}function v(e){switch(o.getToken()){case 7:return f(new vr(e,o.getTokenOffset()),!0);case 8:return f(new yr(e,!0,o.getTokenOffset()),!0);case 9:return f(new yr(e,!1,o.getTokenOffset()),!0);default:return null}}function y(e,t){return h(e)||p(e)||m(e)||g(e)||v(e)}var b=null,_=a();return 17!==_&&(b=y(null,null),b?17!==o.getToken()&&c(dr("End of file expected","End of file expected."),zn.Undefined):c(dr("Invalid symbol","Expected a JSON object, array or literal."),zn.Undefined)),new Pr(b,n,s)}function Rr(e,t,n){if(null!==e&&"object"===typeof e){var r=t+"\t";if(Array.isArray(e)){if(0===e.length)return"[]";for(var i="[\n",o=0;o<e.length;o++)i+=r+Rr(e[o],r,n),o<e.length-1&&(i+=","),i+="\n";return i+=t+"]",i}var s=Object.keys(e);if(0===s.length)return"{}";for(i="{\n",o=0;o<s.length;o++){var a=s[o];i+=r+JSON.stringify(a)+": "+Rr(e[a],r,n),o<s.length-1&&(i+=","),i+="\n"}return i+=t+"}",i}return n(e)}function jr(e,t){if(e.length<t.length)return!1;for(var n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function Fr(e,t){var n=e.length-t.length;return n>0?e.lastIndexOf(t)===n:0===n&&e===t}function Vr(e){return e.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,"\\$&").replace(/[\*]/g,".*")}var Dr=cr(),Ur=function(){function e(e,t,n,r){void 0===t&&(t=[]),void 0===n&&(n=Promise),void 0===r&&(r={}),this.schemaService=e,this.contributions=t,this.promiseConstructor=n,this.clientCapabilities=r,this.templateVarIdCounter=0}return e.prototype.doResolve=function(e){for(var t=this.contributions.length-1;t>=0;t--)if(this.contributions[t].resolveCompletion){var n=this.contributions[t].resolveCompletion(e);if(n)return n}return this.promiseConstructor.resolve(e)},e.prototype.doComplete=function(e,t,n){var r=this,i={items:[],isIncomplete:!1},o=e.offsetAt(t),s=n.getNodeFromOffset(o,!0);if(this.isInComment(e,s?s.offset:0,o))return Promise.resolve(i);var a=this.getCurrentWord(e,o),u=null;if(!s||"string"!==s.type&&"number"!==s.type&&"boolean"!==s.type&&"null"!==s.type){var c=o-a.length;c>0&&'"'===e.getText()[c-1]&&c--,u=Rt.create(e.positionAt(c),t)}else u=Rt.create(e.positionAt(s.offset),e.positionAt(s.offset+s.length));var l={},f={add:function(e){var t=l[e.label];t?t.documentation||(t.documentation=e.documentation):(l[e.label]=e,u&&(e.textEdit=Ht.replace(u,e.insertText)),i.items.push(e))},setAsIncomplete:function(){i.isIncomplete=!0},error:function(e){console.error(e)},log:function(e){console.log(e)},getNumberOfProposals:function(){return i.items.length}};return this.schemaService.getSchemaForResource(e.uri,n).then(function(t){var c=[],h=!0,d="",p=null;if(s&&"string"===s.type){var m=s.parent;m&&"property"===m.type&&m.keyNode===s&&(h=!m.valueNode,p=m,d=e.getText().substr(s.offset+1,s.length-2),m&&(s=m.parent))}if(s&&"object"===s.type){if(s.offset===o)return i;var g=s.properties;g.forEach(function(e){p&&p===e||(l[e.keyNode.value]=cn.create("__"))});var v="";h&&(v=r.evaluateSeparatorAfter(e,e.offsetAt(u.end))),t?r.getPropertyCompletions(t,n,s,h,v,f):r.getSchemaLessPropertyCompletions(n,s,d,f);var y=Tr(s);r.contributions.forEach(function(t){var n=t.collectPropertyCompletions(e.uri,y,a,h,""===v,f);n&&c.push(n)}),!t&&a.length>0&&'"'!==e.getText().charAt(o-a.length-1)&&(f.add({kind:an.Property,label:r.getLabelForValue(a),insertText:r.getInsertTextForProperty(a,null,!1,v),insertTextFormat:un.Snippet,documentation:""}),f.setAsIncomplete())}var b={};return t?r.getValueCompletions(t,n,s,o,e,f,b):r.getSchemaLessValueCompletions(n,s,o,e,f),r.contributions.length>0&&r.getContributedValueCompletions(n,s,o,e,f,c),r.promiseConstructor.all(c).then(function(){if(0===f.getNumberOfProposals()){var t=o;!s||"string"!==s.type&&"number"!==s.type&&"boolean"!==s.type&&"null"!==s.type||(t=s.offset+s.length);var n=r.evaluateSeparatorAfter(e,t);r.addFillerValueCompletions(b,n,f)}return i})})},e.prototype.getPropertyCompletions=function(e,t,n,r,i,o){var s=this,a=t.getMatchingSchemas(e.schema,n.offset);a.forEach(function(e){if(e.node===n&&!e.inverted){var t=e.schema.properties;t&&Object.keys(t).forEach(function(e){var n=t[e];if("object"===typeof n&&!n.deprecationMessage&&!n.doNotSuggest){var a={kind:an.Property,label:s.sanitizeLabel(e),insertText:s.getInsertTextForProperty(e,n,r,i),insertTextFormat:un.Snippet,filterText:s.getFilterTextForValue(e),documentation:s.fromMarkup(n.markdownDescription)||n.description||""};Fr(a.insertText,"$1"+i)&&(a.command={title:"Suggest",command:"editor.action.triggerSuggest"}),o.add(a)}})}})},e.prototype.getSchemaLessPropertyCompletions=function(e,t,n,r){var i=this,o=function(e){e.properties.forEach(function(e){var t=e.keyNode.value;r.add({kind:an.Property,label:i.sanitizeLabel(t),insertText:i.getInsertTextForValue(t,""),insertTextFormat:un.Snippet,filterText:i.getFilterTextForValue(t),documentation:""})})};if(t.parent)if("property"===t.parent.type){var s=t.parent.keyNode.value;e.visit(function(e){return"property"===e.type&&e!==t.parent&&e.keyNode.value===s&&e.valueNode&&"object"===e.valueNode.type&&o(e.valueNode),!0})}else"array"===t.parent.type&&t.parent.items.forEach(function(e){"object"===e.type&&e!==t&&o(e)});else"object"===t.type&&r.add({kind:an.Property,label:"$schema",insertText:this.getInsertTextForProperty("$schema",null,!0,""),insertTextFormat:un.Snippet,documentation:"",filterText:this.getFilterTextForValue("$schema")})},e.prototype.getSchemaLessValueCompletions=function(e,t,n,r,i){var o=this,s=n;if(!t||"string"!==t.type&&"number"!==t.type&&"boolean"!==t.type&&"null"!==t.type||(s=t.offset+t.length,t=t.parent),!t)return i.add({kind:this.getSuggestionKind("object"),label:"Empty object",insertText:this.getInsertTextForValue({},""),insertTextFormat:un.Snippet,documentation:""}),void i.add({kind:this.getSuggestionKind("array"),label:"Empty array",insertText:this.getInsertTextForValue([],""),insertTextFormat:un.Snippet,documentation:""});var a=this.evaluateSeparatorAfter(r,s),u=function(e){Or(e.parent,n,!0)||i.add({kind:o.getSuggestionKind(e.type),label:o.getLabelTextForMatchingNode(e,r),insertText:o.getInsertTextForMatchingNode(e,r,a),insertTextFormat:un.Snippet,documentation:""}),"boolean"===e.type&&o.addBooleanValueCompletion(!e.value,a,i)};if("property"===t.type&&n>t.colonOffset){var c=t.valueNode;if(c&&(n>c.offset+c.length||"object"===c.type||"array"===c.type))return;var l=t.keyNode.value;e.visit(function(e){return"property"===e.type&&e.keyNode.value===l&&e.valueNode&&u(e.valueNode),!0}),"$schema"===l&&t.parent&&!t.parent.parent&&this.addDollarSchemaCompletions(a,i)}if("array"===t.type)if(t.parent&&"property"===t.parent.type){var f=t.parent.keyNode.value;e.visit(function(e){return"property"===e.type&&e.keyNode.value===f&&e.valueNode&&"array"===e.valueNode.type&&e.valueNode.items.forEach(u),!0})}else t.items.forEach(u)},e.prototype.getValueCompletions=function(e,t,n,r,i,o,s){var a=this,u=r,c=null,l=null;if(!n||"string"!==n.type&&"number"!==n.type&&"boolean"!==n.type&&"null"!==n.type||(u=n.offset+n.length,l=n,n=n.parent),n){if("property"===n.type&&r>n.colonOffset){var f=n.valueNode;if(f&&r>f.offset+f.length)return;c=n.keyNode.value,n=n.parent}if(n&&(null!==c||"array"===n.type)){var h=this.evaluateSeparatorAfter(i,u),d=t.getMatchingSchemas(e.schema,n.offset,l);d.forEach(function(e){if(e.node===n&&!e.inverted&&e.schema){if("array"===n.type&&e.schema.items)if(Array.isArray(e.schema.items)){var t=a.findItemAtOffset(n,i,r);t<e.schema.items.length&&a.addSchemaValueCompletions(e.schema.items[t],h,o,s)}else a.addSchemaValueCompletions(e.schema.items,h,o,s);if(e.schema.properties){var u=e.schema.properties[c];u&&a.addSchemaValueCompletions(u,h,o,s)}}}),"$schema"!==c||n.parent||this.addDollarSchemaCompletions(h,o),s["boolean"]&&(this.addBooleanValueCompletion(!0,h,o),this.addBooleanValueCompletion(!1,h,o)),s["null"]&&this.addNullValueCompletion(h,o)}}else this.addSchemaValueCompletions(e.schema,"",o,s)},e.prototype.getContributedValueCompletions=function(e,t,n,r,i,o){if(t){if("string"!==t.type&&"number"!==t.type&&"boolean"!==t.type&&"null"!==t.type||(t=t.parent),"property"===t.type&&n>t.colonOffset){var s=t.keyNode.value,a=t.valueNode;if(!a||n<=a.offset+a.length){var u=Tr(t.parent);this.contributions.forEach(function(e){var t=e.collectValueCompletions(r.uri,u,s,i);t&&o.push(t)})}}}else this.contributions.forEach(function(e){var t=e.collectDefaultCompletions(r.uri,i);t&&o.push(t)})},e.prototype.addSchemaValueCompletions=function(e,t,n,r){var i=this;"object"===typeof e&&(this.addEnumValueCompletions(e,t,n),this.addDefaultValueCompletions(e,t,n),this.collectTypes(e,r),Array.isArray(e.allOf)&&e.allOf.forEach(function(e){return i.addSchemaValueCompletions(e,t,n,r)}),Array.isArray(e.anyOf)&&e.anyOf.forEach(function(e){return i.addSchemaValueCompletions(e,t,n,r)}),Array.isArray(e.oneOf)&&e.oneOf.forEach(function(e){return i.addSchemaValueCompletions(e,t,n,r)}))},e.prototype.addDefaultValueCompletions=function(e,t,n,r){var i=this;void 0===r&&(r=0);var o=!1;if(ir(e.default)){for(var s=e.type,a=e.default,u=r;u>0;u--)a=[a],s="array";n.add({kind:this.getSuggestionKind(s),label:this.getLabelForValue(a),insertText:this.getInsertTextForValue(a,t),insertTextFormat:un.Snippet,detail:Dr("json.suggest.default","Default value")}),o=!0}Array.isArray(e.examples)&&e.examples.forEach(function(s){for(var a=e.type,u=s,c=r;c>0;c--)u=[u],a="array";n.add({kind:i.getSuggestionKind(a),label:i.getLabelForValue(u),insertText:i.getInsertTextForValue(u,t),insertTextFormat:un.Snippet}),o=!0}),Array.isArray(e.defaultSnippets)&&e.defaultSnippets.forEach(function(s){var a,u,c=e.type,l=s.body,f=s.label;if(ir(l)){e.type;for(var h=r;h>0;h--)l=[l],"array";a=i.getInsertTextForSnippetValue(l,t),u=i.getFilterTextForSnippetValue(l),f=f||i.getLabelForSnippetValue(l)}else if("string"===typeof s.bodyText){var d="",p="",m="";for(h=r;h>0;h--)d=d+m+"[\n",p=p+"\n"+m+"]",m+="\t",c="array";a=d+m+s.bodyText.split("\n").join("\n"+m)+p+t,f=f||i.sanitizeLabel(a),u=a.replace(/[\n]/g,"")}n.add({kind:i.getSuggestionKind(c),label:f,documentation:i.fromMarkup(s.markdownDescription)||s.description,insertText:a,insertTextFormat:un.Snippet,filterText:u}),o=!0}),o||"object"!==typeof e.items||Array.isArray(e.items)||this.addDefaultValueCompletions(e.items,t,n,r+1)},e.prototype.addEnumValueCompletions=function(e,t,n){if(ir(e.const)&&n.add({kind:this.getSuggestionKind(e.type),label:this.getLabelForValue(e.const),insertText:this.getInsertTextForValue(e.const,t),insertTextFormat:un.Snippet,documentation:this.fromMarkup(e.markdownDescription)||e.description}),Array.isArray(e.enum))for(var r=0,i=e.enum.length;r<i;r++){var o=e.enum[r],s=this.fromMarkup(e.markdownDescription)||e.description;e.markdownEnumDescriptions&&r<e.markdownEnumDescriptions.length&&this.doesSupportMarkdown()?s=this.fromMarkup(e.markdownEnumDescriptions[r]):e.enumDescriptions&&r<e.enumDescriptions.length&&(s=e.enumDescriptions[r]),n.add({kind:this.getSuggestionKind(e.type),label:this.getLabelForValue(o),insertText:this.getInsertTextForValue(o,t),insertTextFormat:un.Snippet,documentation:s})}},e.prototype.collectTypes=function(e,t){if(!Array.isArray(e.enum)&&!ir(e.const)){var n=e.type;Array.isArray(n)?n.forEach(function(e){return t[e]=!0}):t[n]=!0}},e.prototype.addFillerValueCompletions=function(e,t,n){e["object"]&&n.add({kind:this.getSuggestionKind("object"),label:"{}",insertText:this.getInsertTextForGuessedValue({},t),insertTextFormat:un.Snippet,detail:Dr("defaults.object","New object"),documentation:""}),e["array"]&&n.add({kind:this.getSuggestionKind("array"),label:"[]",insertText:this.getInsertTextForGuessedValue([],t),insertTextFormat:un.Snippet,detail:Dr("defaults.array","New array"),documentation:""})},e.prototype.addBooleanValueCompletion=function(e,t,n){n.add({kind:this.getSuggestionKind("boolean"),label:e?"true":"false",insertText:this.getInsertTextForValue(e,t),insertTextFormat:un.Snippet,documentation:""})},e.prototype.addNullValueCompletion=function(e,t){t.add({kind:this.getSuggestionKind("null"),label:"null",insertText:"null"+e,insertTextFormat:un.Snippet,documentation:""})},e.prototype.addDollarSchemaCompletions=function(e,t){var n=this,r=this.schemaService.getRegisteredSchemaIds(function(e){return"http"===e||"https"===e});r.forEach(function(r){return t.add({kind:an.Module,label:n.getLabelForValue(r),filterText:n.getFilterTextForValue(r),insertText:n.getInsertTextForValue(r,e),insertTextFormat:un.Snippet,documentation:""})})},e.prototype.sanitizeLabel=function(e){return e=e.replace(/[\n]/g,"↵"),e.length>57&&(e=e.substr(0,57).trim()+"..."),e},e.prototype.getLabelForValue=function(e){return this.sanitizeLabel(JSON.stringify(e))},e.prototype.getFilterTextForValue=function(e){return JSON.stringify(e)},e.prototype.getFilterTextForSnippetValue=function(e){return JSON.stringify(e).replace(/\$\{\d+:([^}]+)\}|\$\d+/g,"$1")},e.prototype.getLabelForSnippetValue=function(e){var t=JSON.stringify(e);return t=t.replace(/\$\{\d+:([^}]+)\}|\$\d+/g,"$1"),this.sanitizeLabel(t)},e.prototype.getInsertTextForPlainText=function(e){return e.replace(/[\\\$\}]/g,"\\$&")},e.prototype.getInsertTextForValue=function(e,t){var n=JSON.stringify(e,null,"\t");return"{}"===n?"{$1}"+t:"[]"===n?"[$1]"+t:this.getInsertTextForPlainText(n+t)},e.prototype.getInsertTextForSnippetValue=function(e,t){var n=function(e){return"string"===typeof e&&"^"===e[0]?e.substr(1):JSON.stringify(e)};return Rr(e,"",n)+t},e.prototype.getInsertTextForGuessedValue=function(e,t){switch(typeof e){case"object":return null===e?"${1:null}"+t:this.getInsertTextForValue(e,t);case"string":var n=JSON.stringify(e);return n=n.substr(1,n.length-2),n=this.getInsertTextForPlainText(n),'"${1:'+n+'}"'+t;case"number":case"boolean":return"${1:"+JSON.stringify(e)+"}"+t}return this.getInsertTextForValue(e,t)},e.prototype.getSuggestionKind=function(e){if(Array.isArray(e)){var t=e;e=t.length>0?t[0]:null}if(!e)return an.Value;switch(e){case"string":return an.Value;case"object":return an.Module;case"property":return an.Property;default:return an.Value}},e.prototype.getLabelTextForMatchingNode=function(e,t){switch(e.type){case"array":return"[]";case"object":return"{}";default:var n=t.getText().substr(e.offset,e.length);return n}},e.prototype.getInsertTextForMatchingNode=function(e,t,n){switch(e.type){case"array":return this.getInsertTextForValue([],n);case"object":return this.getInsertTextForValue({},n);default:var r=t.getText().substr(e.offset,e.length)+n;return this.getInsertTextForPlainText(r)}},e.prototype.getInsertTextForProperty=function(e,t,n,r){var i=this.getInsertTextForValue(e,"");if(!n)return i;var o,s=i+": ",a=0;if(t){if(Array.isArray(t.defaultSnippets)){if(1===t.defaultSnippets.length){var u=t.defaultSnippets[0].body;ir(u)&&(o=this.getInsertTextForSnippetValue(u,""))}a+=t.defaultSnippets.length}if(t.enum&&(o||1!==t.enum.length||(o=this.getInsertTextForGuessedValue(t.enum[0],"")),a+=t.enum.length),ir(t.default)&&(o||(o=this.getInsertTextForGuessedValue(t.default,"")),a++),0===a){var c=Array.isArray(t.type)?t.type[0]:t.type;switch(c||(t.properties?c="object":t.items&&(c="array")),c){case"boolean":o="$1";break;case"string":o='"$1"';break;case"object":o="{$1}";break;case"array":o="[$1]";break;case"number":case"integer":o="${1:0}";break;case"null":o="${1:null}";break;default:return i}}}return(!o||a>1)&&(o="$1"),s+o+r},e.prototype.getCurrentWord=function(e,t){var n=t-1,r=e.getText();while(n>=0&&-1===' \t\n\r\v":{[,]}'.indexOf(r.charAt(n)))n--;return r.substring(n+1,t)},e.prototype.evaluateSeparatorAfter=function(e,t){var n=Jn(e.getText(),!0);n.setPosition(t);var r=n.scan();switch(r){case 5:case 2:case 4:case 17:return"";default:return","}},e.prototype.findItemAtOffset=function(e,t,n){for(var r=Jn(t.getText(),!0),i=e.items,o=i.length-1;o>=0;o--){var s=i[o];if(n>s.offset+s.length){r.setPosition(s.offset+s.length);var a=r.scan();return 5===a&&n>=r.getTokenOffset()+r.getTokenLength()?o+1:o}if(n>=s.offset)return o}return 0},e.prototype.isInComment=function(e,t,n){var r=Jn(e.getText(),!1);r.setPosition(t);var i=r.scan();while(17!==i&&r.getTokenOffset()+r.getTokenLength()<n)i=r.scan();return(12===i||13===i)&&r.getTokenOffset()<=n},e.prototype.fromMarkup=function(e){if(e&&this.doesSupportMarkdown())return{kind:on.Markdown,value:e}},e.prototype.doesSupportMarkdown=function(){if(!ir(this.supportsMarkdown)){var e=this.clientCapabilities.textDocument&&this.clientCapabilities.textDocument.completion;this.supportsMarkdown=e&&e.completionItem&&Array.isArray(e.completionItem.documentationFormat)&&-1!==e.completionItem.documentationFormat.indexOf(on.Markdown)}return this.supportsMarkdown},e}(),qr=function(){function e(e,t,n){void 0===t&&(t=[]),this.schemaService=e,this.contributions=t,this.promise=n||Promise}return e.prototype.doHover=function(e,t,n){var r=e.offsetAt(t),i=n.getNodeFromOffset(r);if(!i||("object"===i.type||"array"===i.type)&&r>i.offset+1&&r<i.offset+i.length-1)return this.promise.resolve(null);var o=i;if("string"===i.type){var s=i.parent;if(s&&"property"===s.type&&s.keyNode===i&&(i=s.valueNode,!i))return this.promise.resolve(null)}for(var a=Rt.create(e.positionAt(o.offset),e.positionAt(o.offset+o.length)),u=function(e){var t={contents:e,range:a};return t},c=Tr(i),l=this.contributions.length-1;l>=0;l--){var f=this.contributions[l],h=f.getInfoContribution(e.uri,c);if(h)return h.then(function(e){return u(e)})}return this.schemaService.getSchemaForResource(e.uri,n).then(function(e){if(e){var t=n.getMatchingSchemas(e.schema,i.offset),r=null,o=null,s=null,a=null;t.every(function(e){if(e.node===i&&!e.inverted&&e.schema&&(r=r||e.schema.title,o=o||e.schema.markdownDescription||Kr(e.schema.description),e.schema.enum)){var t=e.schema.enum.indexOf(kr(i));e.schema.markdownEnumDescriptions?s=e.schema.markdownEnumDescriptions[t]:e.schema.enumDescriptions&&(s=Kr(e.schema.enumDescriptions[t])),s&&(a=e.schema.enum[t],"string"!==typeof a&&(a=JSON.stringify(a)))}return!0});var c="";return r&&(c=Kr(r)),o&&(c.length>0&&(c+="\n\n"),c+=o),s&&(c.length>0&&(c+="\n\n"),c+="`"+Kr(a)+"`: "+s),u([c])}return null})},e}();function Kr(e){if(e){var t=e.replace(/([^\n\r])(\r?\n)([^\n\r])/gm,"$1\n\n$3");return t.replace(/[\\`*_{}[\]()#+\-.!]/g,"\\$&")}}var Wr=cr(),Br=function(){function e(e){try{this.patternRegExp=new RegExp(Vr(e)+"$")}catch(t){this.patternRegExp=null}this.schemas=[]}return e.prototype.addSchema=function(e){this.schemas.push(e)},e.prototype.matchesPattern=function(e){return this.patternRegExp&&this.patternRegExp.test(e)},e.prototype.getSchemas=function(){return this.schemas},e}(),$r=function(){function e(e,t,n){this.service=e,this.url=t,this.dependencies={},n&&(this.unresolvedSchema=this.service.promise.resolve(new Yr(n)))}return e.prototype.getUnresolvedSchema=function(){return this.unresolvedSchema||(this.unresolvedSchema=this.service.loadSchema(this.url)),this.unresolvedSchema},e.prototype.getResolvedSchema=function(){var e=this;return this.resolvedSchema||(this.resolvedSchema=this.getUnresolvedSchema().then(function(t){return e.service.resolveSchemaContent(t,e.url,e.dependencies)})),this.resolvedSchema},e.prototype.clearSchema=function(){this.resolvedSchema=null,this.unresolvedSchema=null,this.dependencies={}},e}(),Yr=function(){function e(e,t){void 0===t&&(t=[]),this.schema=e,this.errors=t}return e}(),Hr=function(){function e(e,t){void 0===t&&(t=[]),this.schema=e,this.errors=t}return e.prototype.getSection=function(e){return xr(this.getSectionRecursive(e,this.schema))},e.prototype.getSectionRecursive=function(e,t){if(!t||"boolean"===typeof t||0===e.length)return t;var n=e.shift();if(t.properties&&(t.properties[n],1))return this.getSectionRecursive(e,t.properties[n]);if(t.patternProperties)for(var r=0,i=Object.keys(t.patternProperties);r<i.length;r++){var o=i[r],s=new RegExp(o);if(s.test(n))return this.getSectionRecursive(e,t.patternProperties[o])}else{if("object"===typeof t.additionalProperties)return this.getSectionRecursive(e,t.additionalProperties);if(n.match("[0-9]+"))if(Array.isArray(t.items)){var a=parseInt(n,10);if(!isNaN(a)&&t.items[a])return this.getSectionRecursive(e,t.items[a])}else if(t.items)return this.getSectionRecursive(e,t.items)}return null},e}(),zr=function(){function e(e,t,n){this.contextService=t,this.requestService=e,this.promiseConstructor=n||Promise,this.callOnDispose=[],this.contributionSchemas={},this.contributionAssociations={},this.schemasById={},this.filePatternAssociations=[],this.filePatternAssociationById={},this.registeredSchemasIds={}}return e.prototype.getRegisteredSchemaIds=function(e){return Object.keys(this.registeredSchemasIds).filter(function(t){var n=fr["a"].parse(t).scheme;return"schemaservice"!==n&&(!e||e(n))})},Object.defineProperty(e.prototype,"promise",{get:function(){return this.promiseConstructor},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){while(this.callOnDispose.length>0)this.callOnDispose.pop()()},e.prototype.onResourceChange=function(e){var t=this,n=!1;e=this.normalizeId(e);var r=[e],i=Object.keys(this.schemasById).map(function(e){return t.schemasById[e]});while(r.length)for(var o=r.pop(),s=0;s<i.length;s++){var a=i[s];a&&(a.url===o||a.dependencies[o])&&(a.url!==o&&r.push(a.url),a.clearSchema(),i[s]=void 0,n=!0)}return n},e.prototype.normalizeId=function(e){return fr["a"].parse(e).toString()},e.prototype.setSchemaContributions=function(e){if(e.schemas){var t=e.schemas;for(var n in t){var r=this.normalizeId(n);this.contributionSchemas[r]=this.addSchemaHandle(r,t[n])}}if(e.schemaAssociations){var i=e.schemaAssociations;for(var o in i){var s=i[o];this.contributionAssociations[o]=s;for(var a=this.getOrAddFilePatternAssociation(o),u=0,c=s;u<c.length;u++){var l=c[u];n=this.normalizeId(l);a.addSchema(n)}}}},e.prototype.addSchemaHandle=function(e,t){var n=new $r(this,e,t);return this.schemasById[e]=n,n},e.prototype.getOrAddSchemaHandle=function(e,t){return this.schemasById[e]||this.addSchemaHandle(e,t)},e.prototype.getOrAddFilePatternAssociation=function(e){var t=this.filePatternAssociationById[e];return t||(t=new Br(e),this.filePatternAssociationById[e]=t,this.filePatternAssociations.push(t)),t},e.prototype.registerExternalSchema=function(e,t,n){void 0===t&&(t=null);var r=this.normalizeId(e);if(this.registeredSchemasIds[r]=!0,t)for(var i=0,o=t;i<o.length;i++){var s=o[i];this.getOrAddFilePatternAssociation(s).addSchema(r)}return n?this.addSchemaHandle(r,n):this.getOrAddSchemaHandle(r)},e.prototype.clearExternalSchemas=function(){for(var e in this.schemasById={},this.filePatternAssociations=[],this.filePatternAssociationById={},this.registeredSchemasIds={},this.contributionSchemas)this.schemasById[e]=this.contributionSchemas[e],this.registeredSchemasIds[e]=!0;for(var t in this.contributionAssociations)for(var n=this.getOrAddFilePatternAssociation(t),r=0,i=this.contributionAssociations[t];r<i.length;r++){var o=i[r];e=this.normalizeId(o);n.addSchema(e)}},e.prototype.getResolvedSchema=function(e){var t=this.normalizeId(e),n=this.schemasById[t];return n?n.getResolvedSchema():this.promise.resolve(null)},e.prototype.loadSchema=function(e){if(!this.requestService){var t=Wr("json.schema.norequestservice","Unable to load schema from '{0}'. No schema request service available",Gr(e));return this.promise.resolve(new Yr({},[t]))}return this.requestService(e).then(function(t){if(!t){var n=Wr("json.schema.nocontent","Unable to load schema from '{0}': No content.",Gr(e));return new Yr({},[n])}var r={},i=[];r=Qn(t,i);var o=i.length?[Wr("json.schema.invalidFormat","Unable to parse content from '{0}': Parse error at offset {1}.",Gr(e),i[0].offset)]:[];return new Yr(r,o)},function(e){var t=e.toString(),n=e.toString().split("Error: ");return n.length>1&&(t=n[1]),new Yr({},[t])})},e.prototype.resolveSchemaContent=function(e,t,n){var r=this,i=e.errors.slice(0),o=e.schema,s=this.contextService,a=function(e,t){if(!t)return e;var n=e;return"/"===t[0]&&(t=t.substr(1)),t.split("/").some(function(e){return n=n[e],!n}),n},u=function(e,t,n,r){var o=a(t,r);if(o)for(var s in o)o.hasOwnProperty(s)&&!e.hasOwnProperty(s)&&(e[s]=o[s]);else i.push(Wr("json.schema.invalidref","$ref '{0}' in '{1}' can not be resolved.",r,n))},c=function(e,t,n,o,a){s&&!/^\w+:\/\/.*/.test(t)&&(t=s.resolveRelativePath(t,o)),t=r.normalizeId(t);var c=r.getOrAddSchemaHandle(t);return c.getUnresolvedSchema().then(function(r){if(a[t]=!0,r.errors.length){var o=n?t+"#"+n:t;i.push(Wr("json.schema.problemloadingref","Problems loading reference '{0}': {1}",o,r.errors[0]))}return u(e,r.schema,t,n),l(e,r.schema,t,c.dependencies)})},l=function(e,t,n,i){if(!e||"object"!==typeof e)return Promise.resolve(null);var o=[e],s=[],a=[],l=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var n=0,r=e;n<r.length;n++){var i=r[n];"object"===typeof i&&o.push(i)}},f=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var n=0,r=e;n<r.length;n++){var i=r[n];if("object"===typeof i)for(var s in i){var a=i[s];"object"===typeof a&&o.push(a)}}},h=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var n=0,r=e;n<r.length;n++){var i=r[n];if(Array.isArray(i))for(var s=0,a=i;s<a.length;s++){var u=a[s];"object"===typeof u&&o.push(u)}}},d=function(e){var r=[];while(e.$ref){var o=e.$ref,s=o.split("#",2);if(delete e.$ref,s[0].length>0)return void a.push(c(e,s[0],s[1],n,i));-1===r.indexOf(o)&&(u(e,t,n,s[1]),r.push(o))}l(e.items,e.additionalProperties,e.not,e.contains,e.propertyNames,e.if,e.then,e.else),f(e.definitions,e.properties,e.patternProperties,e.dependencies),h(e.anyOf,e.allOf,e.oneOf,e.items)};while(o.length){var p=o.pop();s.indexOf(p)>=0||(s.push(p),d(p))}return r.promise.all(a)};return l(o,o,t,n).then(function(e){return new Hr(o,i)})},e.prototype.getSchemaForResource=function(e,t){if(t&&t.root&&"object"===t.root.type){var n=t.root.properties.filter(function(e){return"$schema"===e.keyNode.value&&e.valueNode&&"string"===e.valueNode.type});if(n.length>0){var r=kr(n[0].valueNode);if(r&&jr(r,".")&&this.contextService&&(r=this.contextService.resolveRelativePath(r,e)),r){var i=this.normalizeId(r);return this.getOrAddSchemaHandle(i).getResolvedSchema()}}}for(var o=Object.create(null),s=[],a=0,u=this.filePatternAssociations;a<u.length;a++){var c=u[a];if(c.matchesPattern(e))for(var l=0,f=c.getSchemas();l<f.length;l++){var h=f[l];o[h]||(s.push(h),o[h]=!0)}}return s.length>0?this.createCombinedSchema(e,s).getResolvedSchema():this.promise.resolve(null)},e.prototype.createCombinedSchema=function(e,t){if(1===t.length)return this.getOrAddSchemaHandle(t[0]);var n="schemaservice://combinedSchema/"+encodeURIComponent(e),r={allOf:t.map(function(e){return{$ref:e}})};return this.addSchemaHandle(n,r)},e}();function Gr(e){try{var t=fr["a"].parse(e);if("file"===t.scheme)return t.fsPath}catch(n){}return e}var Jr=cr(),Qr=function(){function e(e,t){this.jsonSchemaService=e,this.promise=t,this.validationEnabled=!0}return e.prototype.configure=function(e){e&&(this.validationEnabled=e.validate,this.commentSeverity=e.allowComments?void 0:Bt.Error)},e.prototype.doValidation=function(e,t,n,r){var i=this;if(!this.validationEnabled)return this.promise.resolve([]);var o=[],s={},a=function(e){var t=e.range.start.line+" "+e.range.start.character+" "+e.message;s[t]||(s[t]=!0,o.push(e))},u=function(r){var s=n?ei(n.trailingCommas):Bt.Error,u=n?ei(n.comments):i.commentSeverity;if(r){if(r.errors.length&&t.root){var c=t.root,l="object"===c.type?c.properties[0]:null;if(l&&"$schema"===l.keyNode.value){var f=l.valueNode||l,h=Rt.create(e.positionAt(f.offset),e.positionAt(f.offset+f.length));a($t.create(h,r.errors[0],Bt.Warning,zn.SchemaResolveError))}else{h=Rt.create(e.positionAt(c.offset),e.positionAt(c.offset+1));a($t.create(h,r.errors[0],Bt.Warning,zn.SchemaResolveError))}}else{var d=t.validate(e,r.schema);d&&d.forEach(a)}Zr(r.schema)&&(s=u=void 0)}for(var p=0,m=t.syntaxErrors;p<m.length;p++){var g=m[p];if(g.code===zn.TrailingComma){if("number"!==typeof s)continue;g.severity=s}a(g)}if("number"===typeof u){var v=Jr("InvalidCommentToken","Comments are not permitted in JSON.");t.comments.forEach(function(e){a($t.create(e,v,u,zn.CommentNotPermitted))})}return o};if(r){var c=r.id||"schemaservice://untitled/"+Xr++;return this.jsonSchemaService.resolveSchemaContent(new Yr(r),c,{}).then(function(e){return u(e)})}return this.jsonSchemaService.getSchemaForResource(e.uri,t).then(function(e){return u(e)})},e}(),Xr=0;function Zr(e){if(e&&"object"===typeof e){if(e.allowComments)return!0;if(e.allOf)return e.allOf.some(Zr)}return!1}function ei(e){switch(e){case"error":return Bt.Error;case"warning":return Bt.Warning;case"ignore":return}}var ti=48,ni=57,ri=65,ii=97,oi=102;function si(e){return e<ti?0:e<=ni?e-ti:(e<ii&&(e+=ii-ri),e>=ii&&e<=oi?e-ii+10:0)}function ai(e){if("#"!==e[0])return null;switch(e.length){case 4:return{red:17*si(e.charCodeAt(1))/255,green:17*si(e.charCodeAt(2))/255,blue:17*si(e.charCodeAt(3))/255,alpha:1};case 5:return{red:17*si(e.charCodeAt(1))/255,green:17*si(e.charCodeAt(2))/255,blue:17*si(e.charCodeAt(3))/255,alpha:17*si(e.charCodeAt(4))/255};case 7:return{red:(16*si(e.charCodeAt(1))+si(e.charCodeAt(2)))/255,green:(16*si(e.charCodeAt(3))+si(e.charCodeAt(4)))/255,blue:(16*si(e.charCodeAt(5))+si(e.charCodeAt(6)))/255,alpha:1};case 9:return{red:(16*si(e.charCodeAt(1))+si(e.charCodeAt(2)))/255,green:(16*si(e.charCodeAt(3))+si(e.charCodeAt(4)))/255,blue:(16*si(e.charCodeAt(5))+si(e.charCodeAt(6)))/255,alpha:(16*si(e.charCodeAt(7))+si(e.charCodeAt(8)))/255}}return null}var ui=function(){function e(e){this.schemaService=e}return e.prototype.findDocumentSymbols=function(e,t){var n=this,r=t.root;if(!r)return null;var i=e.uri;if(("vscode://defaultsettings/keybindings.json"===i||Fr(i.toLowerCase(),"/user/keybindings.json"))&&"array"===r.type){var o=[];return r.items.forEach(function(t){if("object"===t.type)for(var n=0,r=t.properties;n<r.length;n++){var i=r[n];if("key"===i.keyNode.value&&i.valueNode){if(i.valueNode){var s=jt.create(e.uri,ci(e,t));o.push({name:kr(i.valueNode),kind:vn.Function,location:s})}return}}}),o}var s=function(t,r,i){return"array"===r.type?r.items.forEach(function(e){return s(t,e,i)}):"object"===r.type&&r.properties.forEach(function(r){var o=jt.create(e.uri,ci(e,r)),a=r.valueNode;if(a){var u=i?i+"."+r.keyNode.value:r.keyNode.value;t.push({name:n.getKeyLabel(r),kind:n.getSymbolKind(a.type),location:o,containerName:i}),s(t,a,u)}}),t},a=s([],r,void 0);return a},e.prototype.findDocumentSymbols2=function(e,t){var n=this,r=t.root;if(!r)return null;var i=e.uri;if(("vscode://defaultsettings/keybindings.json"===i||Fr(i.toLowerCase(),"/user/keybindings.json"))&&"array"===r.type){var o=[];return r.items.forEach(function(t){if("object"===t.type)for(var n=0,r=t.properties;n<r.length;n++){var i=r[n];if("key"===i.keyNode.value){if(i.valueNode){var s=ci(e,t),a=ci(e,i.keyNode);o.push({name:kr(i.valueNode),kind:vn.Function,range:s,selectionRange:a})}return}}}),o}var s=function(t,r){return"array"===r.type?r.items.forEach(function(r,i){if(r){var o=ci(e,r),a=o,u=String(i),c=s([],r);t.push({name:u,kind:n.getSymbolKind(r.type),range:o,selectionRange:a,children:c})}}):"object"===r.type&&r.properties.forEach(function(r){var i=r.valueNode;if(i){var o=ci(e,r),a=ci(e,r.keyNode),u=s([],i);t.push({name:n.getKeyLabel(r),kind:n.getSymbolKind(i.type),range:o,selectionRange:a,children:u})}}),t},a=s([],r);return a},e.prototype.getSymbolKind=function(e){switch(e){case"object":return vn.Module;case"string":return vn.String;case"number":return vn.Number;case"array":return vn.Array;case"boolean":return vn.Boolean;default:return vn.Variable}},e.prototype.getKeyLabel=function(e){var t=e.keyNode.value;return t&&(t=t.replace(/[\n]/g,"↵")),t&&t.trim()?t:'"'+t+'"'},e.prototype.findDocumentColors=function(e,t){return this.schemaService.getSchemaForResource(e.uri,t).then(function(n){var r=[];if(n)for(var i=t.getMatchingSchemas(n.schema),o={},s=0,a=i;s<a.length;s++){var u=a[s];if(!u.inverted&&u.schema&&("color"===u.schema.format||"color-hex"===u.schema.format)&&u.node&&"string"===u.node.type){var c=String(u.node.offset);if(!o[c]){var l=ai(kr(u.node));if(l){var f=ci(e,u.node);r.push({color:l,range:f})}o[c]=!0}}}return r})},e.prototype.getColorPresentations=function(e,t,n,r){var i,o=[],s=Math.round(255*n.red),a=Math.round(255*n.green),u=Math.round(255*n.blue);function c(e){var t=e.toString(16);return 2!==t.length?"0"+t:t}return i=1===n.alpha?"#"+c(s)+c(a)+c(u):"#"+c(s)+c(a)+c(u)+c(Math.round(255*n.alpha)),o.push({label:i,textEdit:Ht.replace(r,JSON.stringify(i))}),o},e}();function ci(e,t){return Rt.create(e.positionAt(t.offset),e.positionAt(t.offset+t.length))}var li,fi=cr(),hi={schemaAssociations:{},schemas:{"http://json-schema.org/draft-04/schema#":{title:fi("schema.json","Describes a JSON file using a schema. See json-schema.org for more info."),$schema:"http://json-schema.org/draft-04/schema#",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},positiveInteger:{type:"integer",minimum:0},positiveIntegerDefault0:{allOf:[{$ref:"#/definitions/positiveInteger"},{default:0}]},simpleTypes:{type:"string",enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},minItems:1,uniqueItems:!0}},type:"object",properties:{id:{type:"string",format:"uri"},$schema:{type:"string",format:"uri"},title:{type:"string"},description:{type:"string"},default:{},multipleOf:{type:"number",minimum:0,exclusiveMinimum:!0},maximum:{type:"number"},exclusiveMaximum:{type:"boolean",default:!1},minimum:{type:"number"},exclusiveMinimum:{type:"boolean",default:!1},maxLength:{allOf:[{$ref:"#/definitions/positiveInteger"}]},minLength:{allOf:[{$ref:"#/definitions/positiveIntegerDefault0"}]},pattern:{type:"string",format:"regex"},additionalItems:{anyOf:[{type:"boolean"},{$ref:"#"}],default:{}},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:{}},maxItems:{allOf:[{$ref:"#/definitions/positiveInteger"}]},minItems:{allOf:[{$ref:"#/definitions/positiveIntegerDefault0"}]},uniqueItems:{type:"boolean",default:!1},maxProperties:{allOf:[{$ref:"#/definitions/positiveInteger"}]},minProperties:{allOf:[{$ref:"#/definitions/positiveIntegerDefault0"}]},required:{allOf:[{$ref:"#/definitions/stringArray"}]},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#"}],default:{}},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},enum:{type:"array",minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{anyOf:[{type:"string",enum:["date-time","uri","email","hostname","ipv4","ipv6","regex"]},{type:"string"}]},allOf:{allOf:[{$ref:"#/definitions/schemaArray"}]},anyOf:{allOf:[{$ref:"#/definitions/schemaArray"}]},oneOf:{allOf:[{$ref:"#/definitions/schemaArray"}]},not:{allOf:[{$ref:"#"}]}},dependencies:{exclusiveMaximum:["maximum"],exclusiveMinimum:["minimum"]},default:{}},"http://json-schema.org/draft-07/schema#":{title:fi("schema.json","Describes a JSON file using a schema. See json-schema.org for more info."),definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}}},di={id:fi("schema.json.id","A unique identifier for the schema."),$schema:fi("schema.json.$schema","The schema to verify this document against."),title:fi("schema.json.title","A descriptive title of the element."),description:fi("schema.json.description","A long description of the element. Used in hover menus and suggestions."),default:fi("schema.json.default","A default value. Used by suggestions."),multipleOf:fi("schema.json.multipleOf","A number that should cleanly divide the current value (i.e. have no remainder)."),maximum:fi("schema.json.maximum","The maximum numerical value, inclusive by default."),exclusiveMaximum:fi("schema.json.exclusiveMaximum","Makes the maximum property exclusive."),minimum:fi("schema.json.minimum","The minimum numerical value, inclusive by default."),exclusiveMinimum:fi("schema.json.exclusiveMininum","Makes the minimum property exclusive."),maxLength:fi("schema.json.maxLength","The maximum length of a string."),minLength:fi("schema.json.minLength","The minimum length of a string."),pattern:fi("schema.json.pattern","A regular expression to match the string against. It is not implicitly anchored."),additionalItems:fi("schema.json.additionalItems","For arrays, only when items is set as an array. If it is a schema, then this schema validates items after the ones specified by the items array. If it is false, then additional items will cause validation to fail."),items:fi("schema.json.items","For arrays. Can either be a schema to validate every element against or an array of schemas to validate each item against in order (the first schema will validate the first element, the second schema will validate the second element, and so on."),maxItems:fi("schema.json.maxItems","The maximum number of items that can be inside an array. Inclusive."),minItems:fi("schema.json.minItems","The minimum number of items that can be inside an array. Inclusive."),uniqueItems:fi("schema.json.uniqueItems","If all of the items in the array must be unique. Defaults to false."),maxProperties:fi("schema.json.maxProperties","The maximum number of properties an object can have. Inclusive."),minProperties:fi("schema.json.minProperties","The minimum number of properties an object can have. Inclusive."),required:fi("schema.json.required","An array of strings that lists the names of all properties required on this object."),additionalProperties:fi("schema.json.additionalProperties","Either a schema or a boolean. If a schema, then used to validate all properties not matched by 'properties' or 'patternProperties'. If false, then any properties not matched by either will cause this schema to fail."),definitions:fi("schema.json.definitions","Not used for validation. Place subschemas here that you wish to reference inline with $ref."),properties:fi("schema.json.properties","A map of property names to schemas for each property."),patternProperties:fi("schema.json.patternProperties","A map of regular expressions on property names to schemas for matching properties."),dependencies:fi("schema.json.dependencies","A map of property names to either an array of property names or a schema. An array of property names means the property named in the key depends on the properties in the array being present in the object in order to be valid. If the value is a schema, then the schema is only applied to the object if the property in the key exists on the object."),enum:fi("schema.json.enum","The set of literal values that are valid."),type:fi("schema.json.type","Either a string of one of the basic schema types (number, integer, null, array, object, boolean, string) or an array of strings specifying a subset of those types."),format:fi("schema.json.format","Describes the format expected for the value."),allOf:fi("schema.json.allOf","An array of schemas, all of which must match."),anyOf:fi("schema.json.anyOf","An array of schemas, where at least one must match."),oneOf:fi("schema.json.oneOf","An array of schemas, exactly one of which must match."),not:fi("schema.json.not","A schema which must not match."),$id:fi("schema.json.$id","A unique identifier for the schema."),$ref:fi("schema.json.$ref","Reference a definition hosted on any location."),$comment:fi("schema.json.$comment","Comments from schema authors to readers or maintainers of the schema."),readOnly:fi("schema.json.readOnly","Indicates that the value of the instance is managed exclusively by the owning authority."),examples:fi("schema.json.examples","Sample JSON values associated with a particular schema, for the purpose of illustrating usage."),contains:fi("schema.json.contains",'An array instance is valid against "contains" if at least one of its elements is valid against the given schema.'),propertyNames:fi("schema.json.propertyNames","If the instance is an object, this keyword validates if every property name in the instance validates against the provided schema."),const:fi("schema.json.const","An instance validates successfully against this keyword if its value is equal to the value of the keyword."),contentMediaType:fi("schema.json.contentMediaType","Describes the media type of a string property."),contentEncoding:fi("schema.json.contentEncoding","Describes the content encoding of a string property."),if:fi("schema.json.if",'The validation outcome of the "if" subschema controls which of the "then" or "else" keywords are evaluated.'),then:fi("schema.json.then",'The "if" subschema is used for validation when the "if" subschema succeeds.'),else:fi("schema.json.else",'The "else" subschema is used for validation when the "if" subschema fails.')};for(var pi in hi.schemas){var mi=hi.schemas[pi];for(var gi in mi.properties){var vi=mi.properties[gi];!0===vi&&(vi=mi.properties[gi]={});var yi=di[gi];yi?vi["description"]=yi:console.log(gi+": localize('schema.json."+gi+'\', "")')}}function bi(e,t){var n=[],r=[],i=[],o=-1,s=Jn(e.getText(),!1),a=s.scan();function u(e){n.push(e),r.push(i.length)}while(17!==a){switch(a){case 1:case 3:var c=e.positionAt(s.getTokenOffset()).line,l={startLine:c,endLine:c,kind:1===a?"object":"array"};i.push(l);break;case 2:case 4:var f=2===a?"object":"array";if(i.length>0&&i[i.length-1].kind===f){l=i.pop();var h=e.positionAt(s.getTokenOffset()).line;l&&h>l.startLine+1&&o!==l.startLine&&(l.endLine=h-1,u(l),o=l.startLine)}break;case 13:c=e.positionAt(s.getTokenOffset()).line;var d=e.positionAt(s.getTokenOffset()+s.getTokenLength()).line;1===s.getTokenError()&&c+1<e.lineCount?s.setPosition(e.offsetAt(Mt.create(c+1,0))):c<d&&(u({startLine:c,endLine:d,kind:qt.Comment}),o=c);break;case 12:var p=e.getText().substr(s.getTokenOffset(),s.getTokenLength()),m=p.match(/^\/\/\s*#(region\b)|(endregion\b)/);if(m){h=e.positionAt(s.getTokenOffset()).line;if(m[1]){l={startLine:h,endLine:h,kind:qt.Region};i.push(l)}else{var g=i.length-1;while(g>=0&&i[g].kind!==qt.Region)g--;if(g>=0){l=i[g];i.length=g,h>l.startLine&&o!==l.startLine&&(l.endLine=h,u(l),o=l.startLine)}}}break}a=s.scan()}var v=t&&t.rangeLimit;if("number"!==typeof v||n.length<=v)return n;for(var y=[],b=0,_=r;b<_.length;b++){var C=_[b];C<30&&(y[C]=(y[C]||0)+1)}var S=0,E=0;for(g=0;g<y.length;g++){var x=y[g];if(x){if(x+S>v){E=g;break}S+=x}}var N=[];for(g=0;g<n.length;g++){C=r[g];"number"===typeof C&&(C<E||C===E&&S++<v)&&N.push(n[g])}return N}function _i(e,t,n){function r(t){var r=e.offsetAt(t),o=n.getNodeFromOffset(r,!0);if(!o)return[];var a=[];while(o){switch(o.type){case"string":case"object":case"array":var u=o.offset+1,c=o.offset+o.length-1;u<c&&r>=u&&r<=c&&a.push(i(u,c)),a.push(i(o.offset,o.offset+o.length));break;case"number":case"boolean":case"null":case"property":a.push(i(o.offset,o.offset+o.length));break}if("property"===o.type||o.parent&&"array"===o.parent.type){var l=s(o.offset+o.length,5);-1!==l&&a.push(i(o.offset,l))}o=o.parent}return a}function i(t,n){return{range:Rt.create(e.positionAt(t),e.positionAt(n)),kind:Hn.Declaration}}var o=Jn(e.getText(),!0);function s(e,t){o.setPosition(e);var n=o.scan();return n===t?o.getTokenOffset()+o.getTokenLength():-1}return t.map(r)}function Ci(e){var t=e.promiseConstructor||Promise,n=new zr(e.schemaRequestService,e.workspaceContext,t);n.setSchemaContributions(hi);var r=new Ur(n,e.contributions,t,e.clientCapabilities),i=new qr(n,e.contributions,t),o=new ui(n),s=new Qr(n,t);return{configure:function(e){n.clearExternalSchemas(),e.schemas&&e.schemas.forEach(function(e){n.registerExternalSchema(e.uri,e.fileMatch,e.schema)}),s.configure(e)},resetSchema:function(e){return n.onResourceChange(e)},doValidation:s.doValidation.bind(s),parseJSONDocument:function(e){return Mr(e,{collectComments:!0})},newJSONDocument:function(e,t){return Lr(e,t)},doResolve:r.doResolve.bind(r),doComplete:r.doComplete.bind(r),findDocumentSymbols:o.findDocumentSymbols.bind(o),findDocumentSymbols2:o.findDocumentSymbols2.bind(o),findColorSymbols:function(e,t){return o.findDocumentColors(e,t).then(function(e){return e.map(function(e){return e.range})})},findDocumentColors:o.findDocumentColors.bind(o),getColorPresentations:o.getColorPresentations.bind(o),doHover:i.doHover.bind(i),getFoldingRanges:bi,getSelectionRanges:_i,format:function(e,t,n){var r=void 0;if(t){var i=e.offsetAt(t.start),o=e.offsetAt(t.end)-i;r={offset:i,length:o}}var s={tabSize:n?n.tabSize:4,insertSpaces:!n||n.insertSpaces,eol:"\n"};return tr(e.getText(),r,s).map(function(t){return Ht.replace(Rt.create(e.positionAt(t.offset),e.positionAt(t.offset+t.length)),t.content)})}}}"undefined"!==typeof fetch&&(li=function(e){return fetch(e).then(function(e){return e.text()})});var Si=function(){function e(e){this.wrapped=new Promise(e)}return e.prototype.then=function(e,t){var n=this.wrapped;return n.then(e,t)},e.prototype.getWrapped=function(){return this.wrapped},e.resolve=function(e){return Promise.resolve(e)},e.reject=function(e){return Promise.reject(e)},e.all=function(e){return Promise.all(e)},e}(),Ei=function(){function e(e,t){this._ctx=e,this._languageSettings=t.languageSettings,this._languageId=t.languageId,this._languageService=Ci({schemaRequestService:t.enableSchemaRequest&&li,promiseConstructor:Si}),this._languageService.configure(this._languageSettings)}return e.prototype.doValidation=function(e){var t=this._getTextDocument(e);if(t){var n=this._languageService.parseJSONDocument(t);return this._languageService.doValidation(t,n)}return Promise.resolve([])},e.prototype.doComplete=function(e,t){var n=this._getTextDocument(e),r=this._languageService.parseJSONDocument(n);return this._languageService.doComplete(n,t,r)},e.prototype.doResolve=function(e){return this._languageService.doResolve(e)},e.prototype.doHover=function(e,t){var n=this._getTextDocument(e),r=this._languageService.parseJSONDocument(n);return this._languageService.doHover(n,t,r)},e.prototype.format=function(e,t,n){var r=this._getTextDocument(e),i=this._languageService.format(r,t,n);return Promise.resolve(i)},e.prototype.resetSchema=function(e){return Promise.resolve(this._languageService.resetSchema(e))},e.prototype.findDocumentSymbols=function(e){var t=this._getTextDocument(e),n=this._languageService.parseJSONDocument(t),r=this._languageService.findDocumentSymbols(t,n);return Promise.resolve(r)},e.prototype.findDocumentColors=function(e){var t=this._getTextDocument(e),n=this._languageService.parseJSONDocument(t),r=this._languageService.findDocumentColors(t,n);return Promise.resolve(r)},e.prototype.getColorPresentations=function(e,t,n){var r=this._getTextDocument(e),i=this._languageService.parseJSONDocument(r),o=this._languageService.getColorPresentations(r,i,t,n);return Promise.resolve(o)},e.prototype.provideFoldingRanges=function(e,t){var n=this._getTextDocument(e),r=this._languageService.getFoldingRanges(n,t);return Promise.resolve(r)},e.prototype._getTextDocument=function(e){for(var t=this._ctx.getMirrorModels(),n=0,r=t;n<r.length;n++){var i=r[n];if(i.uri.toString()===e)return An.create(e,this._languageId,i.version,i.getValue())}return null},e}();self.onmessage=function(){en(function(e,t){return new Ei(e,t)})}}}); //# sourceMappingURL=json.worker.js.map
const { PushNotificationIOS } = require('react-native'); class AlarmServiceDriver { constructor() { this.hasPermission_ = null; this.inAppNotificationHandler_ = null; PushNotificationIOS.addEventListener('localNotification', (instance) => { if (!this.inAppNotificationHandler_) return; if (!instance || !instance._data || !instance._data.id) { console.warn('PushNotificationIOS.addEventListener: Did not receive a proper notification instance'); return; } const id = instance._data.id; this.inAppNotificationHandler_(id); }); } hasPersistentNotifications() { return true; } notificationIsSet(alarmId) { throw new Error('Available only for non-persistent alarms'); } setInAppNotificationHandler(v) { this.inAppNotificationHandler_ = v; } async hasPermissions(perm = null) { if (perm !== null) return perm.alert && perm.badge && perm.sound; if (this.hasPermission_ !== null) return this.hasPermission_; return new Promise((resolve, reject) => { PushNotificationIOS.checkPermissions(async (perm) => { const ok = await this.hasPermissions(perm); this.hasPermission_ = ok; resolve(ok); }); }); } async requestPermissions() { const newPerm = await PushNotificationIOS.requestPermissions({ alert:1, badge:1, sound:1, }); this.hasPermission_ = null; return this.hasPermissions(newPerm); } async clearNotification(id) { PushNotificationIOS.cancelLocalNotifications({ id: id + '' }); } async scheduleNotification(notification) { if (!(await this.hasPermissions())) { const ok = await this.requestPermissions(); if (!ok) return; } // ID must be a string and userInfo must be supplied otherwise cancel won't work const iosNotification = { id: notification.id + '', alertTitle: notification.title, fireDate: notification.date, userInfo: { id: notification.id + '' }, }; if ('body' in notification) iosNotification.alertBody = notification.body; PushNotificationIOS.scheduleLocalNotification(iosNotification); } } module.exports = AlarmServiceDriver;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.searchingEntries = searchingEntries; exports.searchSuccess = searchSuccess; exports.searchFailure = searchFailure; exports.querying = querying; exports.querySuccess = querySuccess; exports.queryFailure = queryFailure; exports.clearSearch = clearSearch; exports.searchEntries = searchEntries; exports.query = query; exports.SEARCH_CLEAR = exports.QUERY_FAILURE = exports.QUERY_SUCCESS = exports.QUERY_REQUEST = exports.SEARCH_ENTRIES_FAILURE = exports.SEARCH_ENTRIES_SUCCESS = exports.SEARCH_ENTRIES_REQUEST = void 0; var _backend = require("../backend"); var _integrations = require("../integrations"); var _reducers = require("../reducers"); /* * Constant Declarations */ const SEARCH_ENTRIES_REQUEST = 'SEARCH_ENTRIES_REQUEST'; exports.SEARCH_ENTRIES_REQUEST = SEARCH_ENTRIES_REQUEST; const SEARCH_ENTRIES_SUCCESS = 'SEARCH_ENTRIES_SUCCESS'; exports.SEARCH_ENTRIES_SUCCESS = SEARCH_ENTRIES_SUCCESS; const SEARCH_ENTRIES_FAILURE = 'SEARCH_ENTRIES_FAILURE'; exports.SEARCH_ENTRIES_FAILURE = SEARCH_ENTRIES_FAILURE; const QUERY_REQUEST = 'INIT_QUERY'; exports.QUERY_REQUEST = QUERY_REQUEST; const QUERY_SUCCESS = 'QUERY_OK'; exports.QUERY_SUCCESS = QUERY_SUCCESS; const QUERY_FAILURE = 'QUERY_ERROR'; exports.QUERY_FAILURE = QUERY_FAILURE; const SEARCH_CLEAR = 'SEARCH_CLEAR'; /* * Simple Action Creators (Internal) * We still need to export them for tests */ exports.SEARCH_CLEAR = SEARCH_CLEAR; function searchingEntries(searchTerm) { return { type: SEARCH_ENTRIES_REQUEST, payload: { searchTerm } }; } function searchSuccess(searchTerm, entries, page) { return { type: SEARCH_ENTRIES_SUCCESS, payload: { searchTerm, entries, page } }; } function searchFailure(searchTerm, error) { return { type: SEARCH_ENTRIES_FAILURE, payload: { searchTerm, error } }; } function querying(namespace, collection, searchFields, searchTerm) { return { type: QUERY_REQUEST, payload: { namespace, collection, searchFields, searchTerm } }; } function querySuccess(namespace, collection, searchFields, searchTerm, response) { return { type: QUERY_SUCCESS, payload: { namespace, collection, searchFields, searchTerm, response } }; } function queryFailure(namespace, collection, searchFields, searchTerm, error) { return { type: QUERY_SUCCESS, payload: { namespace, collection, searchFields, searchTerm, error } }; } /* * Exported simple Action Creators */ function clearSearch() { return { type: SEARCH_CLEAR }; } /* * Exported Thunk Action Creators */ // SearchEntries will search for complete entries in all collections. function searchEntries(searchTerm) { let page = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; return (dispatch, getState) => { dispatch(searchingEntries(searchTerm)); const state = getState(); const backend = (0, _backend.currentBackend)(state.config); const allCollections = state.collections.keySeq().toArray(); const collections = allCollections.filter(collection => (0, _reducers.selectIntegration)(state, collection, 'search')); const integration = (0, _reducers.selectIntegration)(state, collections[0], 'search'); const searchPromise = integration ? (0, _integrations.getIntegrationProvider)(state.integrations, backend.getToken, integration).search(collections, searchTerm, page) : backend.search(state.collections.valueSeq().toArray(), searchTerm); return searchPromise.then(response => dispatch(searchSuccess(searchTerm, response.entries, response.pagination)), error => dispatch(searchFailure(searchTerm, error))); }; } // Instead of searching for complete entries, query will search for specific fields // in specific collections and return raw data (no entries). function query(namespace, collectionName, searchFields, searchTerm) { return (dispatch, getState) => { dispatch(querying(namespace, collectionName, searchFields, searchTerm)); const state = getState(); const backend = (0, _backend.currentBackend)(state.config); const integration = (0, _reducers.selectIntegration)(state, collectionName, 'search'); const collection = state.collections.find(collection => collection.get('name') === collectionName); const queryPromise = integration ? (0, _integrations.getIntegrationProvider)(state.integrations, backend.getToken, integration).searchBy(searchFields.map(f => "data.".concat(f)), collectionName, searchTerm) : backend.query(collection, searchFields, searchTerm); return queryPromise.then(response => dispatch(querySuccess(namespace, collectionName, searchFields, searchTerm, response)), error => dispatch(queryFailure(namespace, collectionName, searchFields, searchTerm, error))); }; }
module.exports = function (config) { config.resolve.extensions = ['.sketch.js', '.js', '.jsx'] config.module.rules.push({ test: /\.(html)$/, use: [{ loader: "@skpm/extract-loader", }, { loader: "html-loader", options: { attrs: [ 'img:src', 'link:href' ], interpolate: true, }, }, ] }) config.module.rules.push({ test: /\.(css)$/, use: [{ loader: "@skpm/extract-loader", }, { loader: "css-loader", }, ] }) }
const path = require('path'); module.exports = { mode: 'production', entry: { index: './src/index.js', }, output: { path: path.join(__dirname, 'dist'), filename: '[name]_[hash:8].js', }, optimization: { runtimeChunk: true, splitChunks: { chunks: 'all' }, }, };
define(function(require) { 'use strict'; var _ = require('underscore') , Base = require('app/views/Base') , socket = require('app/utils/socket') , log = require('bows.min')('Views:Comments') return Base.extend({ template: _.template(require('text!tpl/Comments.html')), requiresLogin: true, className: 'comments screen' }) })
'use strict'; module.exports = { type: 'error', error: { line: 2, column: 1, message: 'Unexpected end of file. The comma \',\' at 1:13 should be followed by a target name.', }, };
import React, { useEffect, useState } from "react"; import { View } from "react-native"; import { Dimensions } from "react-native"; import { VictoryAxis, VictoryLine, VictoryScatter, VictoryBar, VictoryChart, VictoryLabel, } from "victory-native"; import { appColor } from "../configs/styles"; import * as Animatable from "react-native-animatable"; import { LANDSCAPE, SCREEN_HEIGHT, SCREEN_WIDTH } from "../configs/constants"; import { useOrientation } from "../hooks/useOrientation"; import { Button } from "react-native-elements"; const AppHBarChart = ({ renderData, labels, handleLoadData }) => { const isLanscape = useOrientation().includes(LANDSCAPE); return ( <View style={{ backgroundColor: appColor.white, borderRadius: 10, elevation: 5, height: isLanscape ? SCREEN_HEIGHT * 0.32 : SCREEN_HEIGHT * 0.35, }} > {renderData.length && labels.length ? ( <VictoryChart padding={{ top: isLanscape ? SCREEN_HEIGHT * 0.16 : SCREEN_HEIGHT * 0.12, bottom: SCREEN_HEIGHT * 0.05, left: isLanscape ? SCREEN_WIDTH * 0.15 : SCREEN_WIDTH * 0.16, right: isLanscape ? SCREEN_WIDTH * 0.3 : SCREEN_WIDTH * 0.2, }} // maxDomain={{ // y: data?.length ? Math.max(...data) * 1.2 : 0, // }} height={isLanscape ? SCREEN_HEIGHT * 0.45 : SCREEN_HEIGHT * 0.4} width={isLanscape ? SCREEN_HEIGHT * 0.95 : SCREEN_WIDTH * 0.98} style={{ parent: { marginTop: "-14%", marginLeft: "5%", }, }} > <VictoryBar horizontal style={{ data: { fill: appColor.darkBlue, }, labels: { fill: appColor.white, fontWeight: "bold" }, }} categories={{ x: labels }} labels={({ datum }) => { return datum.y > 0 ? `${(datum.y / 10000000).toString().split(".")[0]}M` : null; }} labelComponent={<VictoryLabel dy={0} dx={SCREEN_WIDTH * -0.1} />} animate={{ onExit: { duration: 500, before: () => ({ opacity: 0.3, _y: 0 }), }, onEnter: { duration: 500, before: () => ({ opacity: 0.3, _y: 0 }), after: (datum) => ({ opacity: 1, _y: datum._y, labels: datum.labels, }), }, }} data={renderData} /> <VictoryAxis style={{ axis: { stroke: "transparent" }, tickLabels: { fontWeight: "bold", fill: appColor.midBlue, }, }} /> </VictoryChart> ) : ( <View style={{ justifyContent: "center", alignItems: "center", height: "100%", }} > <Button title="View" onPress={handleLoadData} buttonStyle={{ backgroundColor: appColor.darkBlue, width: SCREEN_WIDTH * 0.5, }} /> </View> )} </View> ); }; export default AppHBarChart;
define(["./cssRule"], function(CssRule) { "use strict"; /** * Wraps a native CSSStyleSheet object with methods that help access the * native sheet object and the associated CSSRule objects. * * Examples: * * var styleSheet = new StyleSheet(styleTag); * * @param {String} styleTag is a `<style>` tag to extract rules from. */ var StyleSheet = function(styleTag) { this.styleTag = styleTag; // Only append to the HEAD tag if the element is not already attached. if (!this.styleTag.parentNode) { document.head.appendChild(this.styleTag); } }; /** * Accessor for the native sheet object. * * Examples: * * styleSheet.getStyleSheet(); * * @return {CSSStyleSheet} The native StyleSheet object. */ StyleSheet.prototype.getStyleSheet = function() { return this.styleTag.sheet; }; /** * Iterates through all of the StyleSheet's native rule objects and replaces * each with a wrapped CssRule. * * Examples: * * var rules = styleSheet.cssRules(); * * @return {Array} An array of CssRule objects. */ StyleSheet.prototype.cssRules = function() { var rules = Array.prototype.slice.call(this.getStyleSheet().cssRules); return rules.map(function(rule, index) { return new CssRule(rule, index); }); }; return StyleSheet; });
'use strict'; /* eslint no-param-reassign: 0, max-len: 0 */ const _ = require('lodash'); const History = require('./history'); module.exports = class SurveyHistory extends History { constructor() { super(['authorId', 'id', 'name', 'description', 'status']); } filterListServersByStatus(result, status = 'published') { // eslint-disable-line class-methods-use-this if (status === 'all') { return result; } const filteredResult = result.reduce((r, survey) => { if (survey.status !== status) { return r; } const surveyCopy = _.cloneDeep(survey); delete surveyCopy.status; r.push(surveyCopy); return r; }, []); return filteredResult; } listServers(fields, indices, status) { const result = super.listServers(fields, indices); return this.filterListServersByStatus(result, status); } listTranslatedServers(language, status = 'published') { const fields = ['authorId', 'id', 'name', 'description', 'status']; const result = super.listTranslatedServers(language, fields); return this.filterListServersByStatus(result, status); } makeSectionExportReady({ id, questions, sections }) { const result = { id }; if (questions) { result.questions = questions.map((qx) => { const q = _.pick(qx, ['id', 'required']); if (qx.sections) { q.sections = qx.sections.map(section => this.makeSectionExportReady(section)); } return q; }); return result; } result.sections = sections.map(section => this.makeSectionExportReady(section)); return result; } listServersByScope(options = {}) { const scope = options.scope || 'summary'; if (scope === 'summary') { const fields = ['authorId', 'id', 'name', 'description', 'status']; return this.listServers(fields, undefined, options.status); } if (scope === 'export') { const result = this.listServers(['id', 'name', 'description', 'questions', 'sections', 'status']); result.forEach((survey) => { if (!survey.sections) { const questions = survey.questions.map(({ id, required, sections: questionSections }) => { const q = { id, required }; if (questionSections) { q.sections = questionSections.map(section => this.makeSectionExportReady(section)); } return q; }); Object.assign(survey, { questions }); return; } const sections = survey.sections.map(section => this.makeSectionExportReady(section)); Object.assign(survey, { sections }); }); return result; } throw new Error('survey scope not implemented.'); } };
(function () { 'use strict'; describe('Suite 1 (Level 1)', function () { it('Suite 1, Spec 1', function () { expect(true).toEqual(true); }); it('Suite 1, Spec 2', function () { expect(true).toEqual(true); }); it('Suite 1, Spec 3', function (done) { expect(false).toEqual(true); done(); // setTimeout(function () { // expect(1).toEqual(2); // done(); // }, 1000); }); describe('Suite 2 (Level 2)', function () { it('Suite 2, Spec 1 (single)', function () { expect(false).toEqual(true); }); xdescribe('Suite 3 (Level 3)', function () { it('Suite 3, Spec 1', function () { expect(true).toEqual(true); }); it('Suite 3, Spec 2', function () { expect(false).toEqual(true); }); }); xit('Suite 2, Spec 2 (final)', function () { expect(true).toEqual(true); }); }); it('Suite 1, Spec 4 (final)', function () { expect(true).toEqual(true); pending('test pending'); }); xdescribe('Suite 4 (Level 2)', function () { it('Suite 4, Spec 1 (single)', function () { expect(true).toEqual(true); }); }); describe('Suite 5 (Level 2)', function () { it('Suite 5, Spec 1 (single)', function () { expect(true).toEqual(true); }); }); }); describe('Suite 6 (Level 1)', function () { it('Suite 6, Spec 1', function () { expect(true).toEqual(true); }); xit('Suite 6, Spec 2 (final)', function () { expect(true).toEqual(true); }); }); })();
import { terser } from 'rollup-plugin-terser'; import copy from 'rollup-plugin-copy'; export default [ { input: 'src/mathlive.js', plugins: [ terser({ sourcemap: false, compress: { drop_console: true, drop_debugger: true, ecma: 8, module: true, warnings: true, passes: 2, }, }), copy({ targets: [ { src: 'css/fonts', dest: 'dist' }, { src: 'src', dest: 'dist' }, { src: 'build/types.d.ts', dest: 'dist', rename: 'mathlive.d.ts', }, ], }), ], output: [ { // JavaScript native module sourcemap: false, file: 'dist/mathlive.mjs', format: 'es', }, { // UMD file, suitable for <script>, require(), etc... sourcemap: false, file: 'dist/mathlive.js', format: 'umd', name: 'MathLive', }, ], }, { input: 'src/vue-mathlive.js', plugins: [ terser({ sourcemap: false, compress: { drop_console: true, drop_debugger: true, ecma: 6, module: true, warnings: true, }, }), ], output: { // JavaScript native module sourcemap: false, file: 'dist/vue-mathlive.mjs', format: 'es', }, }, ];
import axios from "axios"; export default () => { return axios.create({ baseURL: `http://localhost:3001`, headers: { Authorization: 'Basic dXN1YXJpbzpzZW5oYQ==' } }); };
import chai, { expect } from 'chai' import { shallowMount, mount } from '@vue/test-utils' import Uploader from '@/uploader.vue' import sinon from 'sinon' import sinonChai from 'sinon-chai' chai.use(sinonChai) import http from '../../src/http.js' describe('Uploader.vue', () => { it('Uploader存在', () => { expect(Uploader).to.exist }) it('可以上传一个文件', (done) => { http.post = (url, options) => { setTimeout(() => { options.callback(options.name, JSON.stringify({ id: '123' }), 'success') setTimeout(() => { expect(vm.find('use').exists()).to.eq(false) expect(vm.find('img').exists()).to.eq(true) expect(vm.find('img').attributes().src).to.eq('/preview/123') done() }) }, 1500) } const vm = mount(Uploader, { propsData: { name: 'file', action: '/upload', method: 'POST', multiple: true, fileList: [], parseUrl: (response) => { let obj = JSON.parse(response) return '/preview/' + obj.id }, }, slots: { default: `<button id='x'>点击上传</button>`, }, listeners: { 'update:fileList': (fileList) => { vm.setProps({ fileList: fileList }) }, }, }) vm.find('#x').trigger('click') const inputWrapper = vm.find('input[type="file"]') const input = inputWrapper.element const file1 = new File(['this is file1'], 'xxx.txt', { type: 'image/png' }) // 给 input 添加文件 // 利用 dataTransfer const dataTransfer = new DataTransfer() dataTransfer.items.add(file1) input.files = dataTransfer.files input.dispatchEvent(new Event('change')) // 存在loading状态 setTimeout(() => { let use = vm.find('use') expect(use.exists()).to.eq(true) }, 500) }) })
export default class Rectangle{ constructor(x = 0, y = 0, width = 0, height = 0){ this.x = x; this.y = y; this.width = width; this.height = height; } }
/** * 获取音乐音质 * @param {*} info * @param {*} type */ const types = ['flac', 'ape', '320k', '192k', '128k'] export const getMusicType = (info, type) => { switch (info.source) { // case 'kg': case 'wy': case 'tx': return '128k' } const rangeType = types.slice(types.indexOf(type)) for (const type of rangeType) { if (info._types[type]) return type } return '128k' }
import React, { Component } from 'react'; import { StyleSheet, View, Text, ScrollView, Picker, TouchableNativeFeedback, TouchableOpacity, Alert, BackHandler, TextInput, DeviceEventEmitter } from 'react-native'; import { Item, Icon } from 'native-base'; import { FormLabel, FormInput } from 'react-native-elements' import ModalFilterPicker from 'react-native-modal-filter-picker' //libs import { ToolbarActionButton, LoadingIndicator } from '../../common'; import * as constants from '../../constants'; import * as util from '../../util'; import * as globalStyle from '../../styles'; import CoreService from '../../services/CoreService'; class DetailsRelation extends Component { static navigationOptions = ({ navigation }) => { const { params } = navigation.state; let title = `Solicitud (${params.Relacion})`; // if (!params.IsNewSolicitud) { // title = `Solicitud #${params.SolicitudId}`; // } return { title: title, titleStyle: { textAlign: 'center' } } }; constructor(props) { super(props); this.state = { isNewSolicitud: false, isVehiculo: false, isLoading: false, hasPrioridadChanged: false, CurrentPrioridadCodigo: '', IsEnabledPriority: false, showSelectedDealer: false, //FILL prioridades: [], tiposEmpleo: [], tiemposEmpleado: [], dealers: [], marcasVehiculo: [], modelosVehiculo: [], anosVehiculo: [], solicitud: { //DEFAULT WorkflowEstado: '', FormaPagoCodigo: 'M', PrioridadCodigo: '', ComentarioPrioridad: '', PromotorId: '1', Gastos: 0, TipoGarantiaId: 0, DescripcionGarantia: '', ValorGarantia: 0, ValorGarantiaInmueble: 0, IsSolicitudGarante: false, TipoPrestamoCategoriaId: '', //SOLICITANTE TipoPrestamo: '', TipoPrestamoId: '', SolicitudId: '', Cedula: '', NombreCompleto: '', Salario: '', OtrosIngresos: '', DescripcionOtrosIngresos: '', TipoEmpleoId: '', TiempoEmpleandoId: '', LugarDeTrabajo: '', TelefonoCasa: '', TelefonoCelular: '', Email: '', //VEHICULO PrecioVehiculo: '', DealerId: '', DealerNombre: '', MarcaVehiculoId: 0, ModeloVehiculoId: 0, AnoVehiculoId: 0, //PRESTAMO Y GARANTIA MontoPrestamo: '', Meses: '', Tasa: '', Comentario: '', NombreEmpresa: '' } }; this.saveSolicitud = this.saveSolicitud.bind(this); } onOpenSelectDealer = () => { this.setState((prevState) => { return { ...prevState, showSelectedDealer: true }; }); }; onSelect = (picked) => { if (picked) { const dealerItem = this.state.dealers.filter(item => item.key === picked)[0]; if (dealerItem) { this.setState((prevState) => { return { ...prevState, solicitud: { ...prevState.solicitud, DealerId: dealerItem.key, DealerNombre: dealerItem.label }, showSelectedDealer: false }; }); } } }; onCancel = () => { this.setState({ showSelectedDealer: false }); }; /** * Validate required fields * @param solicitud * @returns {boolean} */ validateRequiredFields = (solicitud, hasPrioridadChanged) => { let valid = true; let validationMessage = ''; if (solicitud.TipoPrestamoCategoriaId) { //categoria-vehiculo if (solicitud.TipoPrestamoCategoriaId === "1") { if (hasPrioridadChanged && !solicitud.ComentarioPrioridad) { validationMessage += "(*)Motivo Cambio Prioridad\n"; valid = false; } if (!solicitud.Salario || solicitud.Salario == "0") { validationMessage += "(*)Salario\n"; valid = false; } if (!solicitud.DescripcionOtrosIngresos) { validationMessage += "(*)Descripción Ingresos\n"; valid = false; } if (solicitud.OtrosIngresos === "") { validationMessage += "(*)Otros Ingresos\n"; valid = false; } if (!solicitud.TipoEmpleoId) { validationMessage += "(*)Tipo Empleo\n"; valid = false; } if (!solicitud.TiempoEmpleandoId) { validationMessage += "(*)Tiempo Empleando\n"; valid = false; } if (!solicitud.TelefonoCasa) { validationMessage += "(*)Telefono Casa\n"; valid = false; } if (!solicitud.TelefonoCelular) { validationMessage += "(*)Telefono Celular\n"; valid = false; } if (!solicitud.PrecioVehiculo || solicitud.PrecioVehiculo == "0") { validationMessage += "(*)Precio Vehículo\n"; valid = false; } if (!solicitud.AnoVehiculoId) { validationMessage += "(*)Año Vehículo\n"; valid = false; } if (!solicitud.MarcaVehiculoId) { validationMessage += "(*)Marca Vehículo\n"; valid = false; } if (!solicitud.ModeloVehiculoId) { validationMessage += "(*)Modelo Vehículo\n"; valid = false; } if (!solicitud.MontoPrestamo || solicitud.MontoPrestamo == "0") { validationMessage += "(*)Monto Prestamo\n"; valid = false; } if (!solicitud.Meses || solicitud.Meses == "0") { validationMessage += "(*)Meses\n"; valid = false; } if (!solicitud.Tasa || solicitud.Tasa == "0") { validationMessage += "(*)Tasa\n"; valid = false; } else { if (isNaN(solicitud.Tasa)) { validationMessage += "(*)Tasa no Valida\n"; valid = false; } } } //categoria-personal if (solicitud.TipoPrestamoCategoriaId === "2") { if (hasPrioridadChanged && !solicitud.ComentarioPrioridad) { validationMessage += "(*)Motivo Cambio Prioridad\n"; valid = false; } if (!solicitud.Salario || solicitud.Salario == "0") { validationMessage += "(*)Salario\n"; valid = false; } if (solicitud.OtrosIngresos === "") { validationMessage += "(*)Otros Ingresos\n"; valid = false; } if (!solicitud.DescripcionOtrosIngresos) { validationMessage += "(*)Descripción Ingresos\n"; valid = false; } if (!solicitud.TipoEmpleoId) { validationMessage += "(*)Tipo Empleo\n"; valid = false; } if (!solicitud.TiempoEmpleandoId) { validationMessage += "(*)Tiempo Empleando\n"; valid = false; } if (!solicitud.TelefonoCasa) { validationMessage += "(*)Telefono Casa\n"; valid = false; } if (!solicitud.TelefonoCelular) { validationMessage += "(*)Telefono Celular\n"; valid = false; } if (!solicitud.MontoPrestamo || solicitud.MontoPrestamo == "0") { validationMessage += "(*)Monto Prestamo\n"; valid = false; } if (!solicitud.Meses || solicitud.Meses == "0") { validationMessage += "(*)Meses\n"; valid = false; } if (!solicitud.Tasa || solicitud.Tasa == "0") { validationMessage += "(*)Tasa\n"; valid = false; } else { if (isNaN(solicitud.Tasa)) { validationMessage += "(*)Tasa no Valida\n"; valid = false; } } } } if (!valid) { validationMessage = `Los siguientes campos son requeridos o no están correctos:\n${validationMessage}`; } return { valid: valid, message: validationMessage }; } cancelSolicitud = () => { Alert.alert("Cerrar Formulario Solicitud", "¿Está seguro de cerrar el formulario de solicitud?", [ { text: "CERRAR", onPress: () => { this.props.navigation.goBack(null); } }, { text: "CANCELAR", onPress: () => { } } ]) }; /** * Save Solicitud */ saveSolicitud = async () => { let { solicitud, hasPrioridadChanged } = this.state; if (solicitud) { const { valid, message } = this.validateRequiredFields(solicitud, hasPrioridadChanged); if (!valid) { Alert.alert("Información Requerida", message); } else { try { this.setLoadingState(true); let result = await CoreService .post(constants.SAVE_SOLICITUD, solicitud); if (result.data) { const code = result.data.Code; const message = result.data.Message; switch (code) { case "success": util.ShowAlert("Solicitud Guardada", "Su solicitud ha sido guardada correctamente!"); this.props.navigation.goBack(null); break; case "error": util.ShowAlert(constants.ERROR_TITLE, constants.ERROR_MESSAGE); break; } } } catch (ex) { util.ShowAlert(constants.ERROR_TITLE, constants.ERROR_MESSAGE); } this.setLoadingState(false); } } } /** * On Marca ValueChange * @param itemValue * @returns {Promise<void>} */ onMarcaValueChange = async (itemValue) => { if (itemValue) { this.setState((prevSolicitud) => { return { solicitud: { ...prevSolicitud.solicitud, MarcaVehiculoId: itemValue } } }); try { let resultModelosVehiculo = await CoreService .get(`${constants.FETCH_MODELOS_VEHICULO_BY_MARCA_ID}/${itemValue}`); if (resultModelosVehiculo) { if (resultModelosVehiculo.data) { this.setState((prevState) => { return { ...prevState, modelosVehiculo: resultModelosVehiculo.data }; }); } } } catch (ex) { util.ShowAlert(constants.ERROR_TITLE, constants.ERROR_MESSAGE); } } }; /** * Set Loading State * @param isLoading */ setLoadingState(isLoading) { this.setState((prevState) => { return { ...prevState, isLoading: isLoading }; }); } /** * Fetch Solicitud * @param solicitudId * @returns {Promise<void>} */ async fetchSolicitud(solicitudId, TipoPrestamoCategoriaId, IsEnabledPriority, params) { try { this.setLoadingState(true); const result = await CoreService .get(`${constants.FETCH_SOLICITUD_BY_SOLICITUD_ID}/${solicitudId}`); if (result) { if (result.data) { let data = result.data[0]; if (data) { //Do Fetch to Load all Pickers if (TipoPrestamoCategoriaId === '1') //VEHICULO { let resultFill = await CoreService .get(constants.FETCH_FILL_TIPO_PRESTAMO_VEHICULO); if (resultFill) { //Fetch modelos by marcaID let resultModelosVehiculo = await CoreService .get(`${constants.FETCH_MODELOS_VEHICULO_BY_MARCA_ID}/${data.MarcaVehiculoId}`); if (resultModelosVehiculo) { if (resultModelosVehiculo.data) { this.setState((prevState) => { return { ...prevState, modelosVehiculo: resultModelosVehiculo.data }; }); } } this.setState((prevState) => { return { ...prevState, isVehiculo: true, isLoading: false, CurrentPrioridadCodigo: data.PrioridadCodigo, IsEnabledPriority: IsEnabledPriority, //FILL prioridades: resultFill.data.prioridades, tiposEmpleo: resultFill.data.tiposEmpleo, tiemposEmpleado: resultFill.data.tiemposEmpleado, //dealers: resultFill.data.dealers, dealers: resultFill.data.dealers.map(item => { return { key: item.IdDealer, label: item.Nombre } }), marcasVehiculo: resultFill.data.marcasVehiculo, anosVehiculo: resultFill.data.anosVehiculo, //SOLICITUD solicitud: { ...prevState.solicitud, WorkflowEstado: data.WorkflowEstado, PrioridadCodigo: data.PrioridadCodigo, TipoPrestamoCategoriaId: data.TipoPrestamoCategoriaID, TipoPrestamo: data.TipoPrestamo, TipoPrestamoId: data.TipoPrestamoId, SolicitudId: params.IsNewRelacionado ? '' : data.SolicitudId, Cedula: params.Cedula, NombreCompleto: data.NombreCompleto, Salario: params.IsNewRelacionado ? '' : data.Salario, OtrosIngresos: params.IsNewRelacionado ? '' : data.OtrosIngresos, DescripcionOtrosIngresos: params.IsNewRelacionado ? '' : data.DescripcionOtrosIngresos, TipoEmpleoId: params.IsNewRelacionado ? '' : data.TipoEmpleoId, TiempoEmpleandoId: params.IsNewRelacionado ? '' : data.TiempoEmpleadoId, LugarDeTrabajo: params.IsNewRelacionado ? '' : data.LugarDeTrabajo, TelefonoCasa: params.IsNewRelacionado ? '' : data.TelefonoCasa, TelefonoCelular: params.IsNewRelacionado ? '' : data.TelefonoCelular, Email: params.IsNewRelacionado ? '' : data.Email, NombreEmpresa: params.IsNewRelacionado ? '' : data.NombreEmpresa, IsSolicitudRelacionado: true, IsSolicitudGarante: params.IsSolicitudGarante, IsSolicitudCoDeudor: params.IsSolicitudCoDeudor, IsSolicitudFiador: params.IsSolicitudFiador, IdSolicitudDeudor: params.IdSolicitudDeudor, IsNewSolicitud: params.IsNewSolicitud, //VEHICULO PrecioVehiculo: data.ValorVehiculo, DealerId: data.DealerVehiculoId, DealerNombre: data.DealerVehiculoNombre, MarcaVehiculoId: data.MarcaVehiculoId, ModeloVehiculoId: data.ModeloVehiculoId, AnoVehiculoId: data.AnoVehiculoId, //PRESTAMO Y GARANTIA MontoPrestamo: data.MontoPrestamo, Meses: data.Meses, Tasa: data.TasaInteres, Comentario: data.Comentario } } }); } } if (TipoPrestamoCategoriaId === '2') //PERSONAL { let resultFill = await CoreService .get(constants.FETCH_FILL_TIPO_PRESTAMO_PERSONAL); if (resultFill) { this.setState((prevState) => { return { ...prevState, isVehiculo: false, isLoading: false, CurrentPrioridadCodigo: data.PrioridadCodigo, IsEnabledPriority: IsEnabledPriority, //FILL prioridades: resultFill.data.prioridades, tiposEmpleo: resultFill.data.tiposEmpleo, tiemposEmpleado: resultFill.data.tiemposEmpleado, //SOLICITUD solicitud: { ...prevState.solicitud, WorkflowEstado: data.WorkflowEstado, PrioridadCodigo: data.PrioridadCodigo, TipoPrestamoCategoriaId: data.TipoPrestamoCategoriaID, TipoPrestamo: data.TipoPrestamo, TipoPrestamoId: data.TipoPrestamoId, SolicitudId: data.SolicitudId, Cedula: data.Cedula, NombreCompleto: data.NombreCompleto, Salario: data.Salario, OtrosIngresos: data.OtrosIngresos, DescripcionOtrosIngresos: data.DescripcionOtrosIngresos, TipoEmpleoId: data.TipoEmpleoId, TiempoEmpleandoId: data.TiempoEmpleadoId, LugarDeTrabajo: data.LugarDeTrabajo, TelefonoCasa: data.TelefonoCasa, TelefonoCelular: data.TelefonoCelular, Email: data.Email, NombreEmpresa: data.NombreEmpresa, //PRESTAMO Y GARANTIA MontoPrestamo: data.MontoPrestamo, Meses: data.Meses, Tasa: data.TasaInteres, Comentario: data.Comentario, } } }); } } } } } } catch (ex) { util.ShowAlert(constants.ERROR_TITLE, constants.ERROR_MESSAGE); this.setLoadingState(false); } this.setLoadingState(false); } _renderWorkflowEstadoView = () => { const { WorkflowEstado } = this.state.solicitud; let viewStyle = { flex: 1, backgroundColor: '#ecf0f1', borderBottomColor: '#b2bec3', borderBottomWidth: 1, justifyContent: 'center', alignItems: 'center' }; let textStyle = {}; let textText = ''; switch (WorkflowEstado) { case "1": textText = "RECIBIDO"; textStyle = { color: '#3c8dbc', fontWeight: 'bold', fontSize: 12 }; break; case "2": textText = "EN TRAMITE"; textStyle = { color: '#e67e22', fontWeight: 'bold', fontSize: 12 }; break; case "3": textText = "DETENIDA"; textStyle = { color: '#7f8c8d', fontWeight: 'bold', fontSize: 12 }; break; case "4": textText = "DESEMBOLSADA"; textStyle = { color: '#7cb6c3', fontWeight: 'bold', fontSize: 12 }; break; case "5": textText = "APROBADA"; textStyle = { color: '#00a65a', fontWeight: 'bold', fontSize: 12 }; break; case "6": textText = "RECHAZADA"; textStyle = { color: '#dd4b39', fontWeight: 'bold', fontSize: 12 }; break; case "7": textText = "EN REVISION"; textStyle = { color: '#e67e22', fontWeight: 'bold', fontSize: 12 }; break; case "8": textText = "ANULADA"; textStyle = { color: '#7f8c8d', fontWeight: 'bold', fontSize: 12 }; break; case "9": textText = "DECLINADA"; textStyle = { color: '#eca465', fontWeight: 'bold', fontSize: 12 }; break; case "10": textText = "PRE-APROBADA"; textStyle = { color: '#00a65a', fontWeight: 'bold', fontSize: 12 }; break; case "11": textText = "RECHAZADA POR COMITE"; textStyle = { color: '#dd4b39', fontWeight: 'bold', fontSize: 12 }; break; case "14": textText = "COMPLETADO"; textStyle = { color: '#7cb6c3', fontWeight: 'bold', fontSize: 12 }; break; default: textText = "N/A"; textStyle = { color: '#7f8c8d', fontWeight: 'bold', fontSize: 12 }; break; } return (<View style={viewStyle}> <Text style={textStyle}>{textText}</Text> </View> ); }; enabledPrioridadComentario = (itemValue) => { if (itemValue !== util.returnBlankValue(this.state.CurrentPrioridadCodigo)) { this.setState((prevState) => { return { ...prevState, hasPrioridadChanged: true }; }); } else { this.setState((prevState) => { return { ...prevState, hasPrioridadChanged: false, solicitud: { ...prevState.solicitud, ComentarioPrioridad: '' } }; }); } }; async componentDidMount() { const { params } = this.props.navigation.state; if (params) { await this.fetchSolicitud(params.SolicitudId, params.TipoPrestamoCategoriaId, params.IsEnabledPriority, params); } } _renderForm = (solicitud, isVehiculo) => { return ( <View style={{ flex: 1 }}> <ScrollView keyboardShouldPersistTaps={'always'}> {/*****SOLICITANTE******/} <View> <View style={{ flexDirection: 'row' }}> <View style={styles.headerTitle}> <View style={{ flex: 1 }}> <Text style={styles.headerTitleText}>SOLICITANTE</Text> </View> </View> {(this.state.isNewSolicitud && this.state.IsNewRelacionado) && this._renderWorkflowEstadoView()} </View> <View> <View style={{ flexDirection: 'row' }}> <View style={{ flex: 1 }}> <FormLabel labelStyle={styles.labelStyle}>CEDULA</FormLabel> <FormInput value={this.state.solicitud.Cedula} editable={false} /> </View> {(this.state.isNewSolicitud && this.state.IsNewRelacionado) && <View style={{ flex: 1 }}> <FormLabel labelStyle={styles.labelStyle}># SOLICITUD</FormLabel> <FormInput value={`${this.state.solicitud.SolicitudId}`} keyboardType={'numeric'} editable={false} /> </View>} </View> {(this.state.isNewSolicitud && this.state.IsNewRelacionado) && <View> <FormLabel labelStyle={styles.labelStyle}>NOMBRE</FormLabel> <FormInput value={this.state.solicitud.NombreCompleto} editable={false} /> </View>} {(!this.state.isNewSolicitud && this.state.IsEnabledPriority) && <View> <View> <FormLabel labelStyle={styles.labelStyle}>PRIORIDAD</FormLabel> <Picker style={{ marginLeft: 10 }} selectedValue={this.state.solicitud.PrioridadCodigo} onValueChange={(itemValue) => { this.enabledPrioridadComentario(itemValue); this.setState(prevState => ({ solicitud: { ...prevState.solicitud, PrioridadCodigo: itemValue } })) }} editable={false}> <Picker.Item label='N/A' value='' /> {this.state.prioridades.map((item, index) => ( <Picker.Item label={item.DESCRIPCION} value={item.CODIGO} key={index} />) )} </Picker> </View> {this.state.hasPrioridadChanged && <View style={{ flex: 1 }}> <FormLabel labelStyle={{ color: '#e74c3c' }}>Motivo Cambio Prioridad (*)</FormLabel> <FormInput value={`${this.state.solicitud.ComentarioPrioridad}`} keyboardType={'default'} onChangeText={(text) => { this.setState(prevState => ({ solicitud: { ...prevState.solicitud, ComentarioPrioridad: text } })) }} /> </View> } </View> } <View style={{ flexDirection: 'row' }}> <View style={{ flex: 1 }}> <FormLabel labelStyle={styles.labelStyle}>SALARIO (*)</FormLabel> <FormInput value={`${this.state.solicitud.Salario}`} keyboardType={'numeric'} onChangeText={(text) => { this.setState(prevState => ({ solicitud: { ...prevState.solicitud, Salario: text } })) }} /> </View> <View style={{ flex: 1 }}> <FormLabel labelStyle={styles.labelStyle}>OTROS INGRESOS (*)</FormLabel> <FormInput value={`${this.state.solicitud.OtrosIngresos}`} keyboardType={'numeric'} onChangeText={(text) => { this.setState(prevState => ({ solicitud: { ...prevState.solicitud, OtrosIngresos: text } })) }} /> </View> </View> <View> <FormLabel labelStyle={styles.labelStyle}>DESCRIPCION INGRESOS (*)</FormLabel> <FormInput value={`${this.state.solicitud.DescripcionOtrosIngresos}`} keyboardType={'default'} onChangeText={(text) => { this.setState(prevState => ({ solicitud: { ...prevState.solicitud, DescripcionOtrosIngresos: text } })) }} /> </View> <View style={{ flexDirection: 'row' }}> <View style={{ flex: 1 }}> <FormLabel labelStyle={styles.labelStyle}>TIPO EMPLEO (*)</FormLabel> <Picker style={{ marginLeft: 10 }} selectedValue={this.state.solicitud.TipoEmpleoId} onValueChange={(itemValue) => this.setState(prevState => ({ solicitud: { ...prevState.solicitud, TipoEmpleoId: itemValue } }))}> <Picker.Item label='[ SELECCIONE ]' value='' /> {this.state.tiposEmpleo.map((item, index) => ( <Picker.Item label={item.Descripcion} value={item.IdEmpleo} key={index} />) )} </Picker> </View> <View style={{ flex: 1 }}> <FormLabel labelStyle={styles.labelStyle}>TIEMPO EMPLEADO (*)</FormLabel> <Picker style={{ marginLeft: 10 }} selectedValue={this.state.solicitud.TiempoEmpleandoId} onValueChange={(itemValue) => this.setState(prevState => ({ solicitud: { ...prevState.solicitud, TiempoEmpleandoId: itemValue } }))}> <Picker.Item label='[ SELECCIONE ]' value='' /> {this.state.tiemposEmpleado.map((item, index) => ( <Picker.Item label={item.Descripcion} value={item.IdTiempoLaborando} key={index} />) )} </Picker> </View> </View> <View> <FormLabel labelStyle={styles.labelStyle}>LUGAR DE TRABAJO</FormLabel> <FormInput value={`${this.state.solicitud.NombreEmpresa}`} keyboardType={'default'} onChangeText={(text) => { this.setState(prevState => ({ solicitud: { ...prevState.solicitud, NombreEmpresa: text } })) }} /> </View> <View style={{ flexDirection: 'row' }}> <View style={{ flex: 1 }}> <FormLabel labelStyle={styles.labelStyle}>TELEFONO CASA (*)</FormLabel> <FormInput value={`${this.state.solicitud.TelefonoCasa}`} keyboardType={'numeric'} onChangeText={(text) => { this.setState(prevState => ({ solicitud: { ...prevState.solicitud, TelefonoCasa: text } })) }} /> </View> <View style={{ flex: 1 }}> <FormLabel labelStyle={styles.labelStyle}>TELEFONO CELULAR (*)</FormLabel> <FormInput value={`${this.state.solicitud.TelefonoCelular}`} keyboardType={'numeric'} onChangeText={(text) => { this.setState(prevState => ({ solicitud: { ...prevState.solicitud, TelefonoCelular: text } })) }} /> </View> </View> </View> </View> {/*****VEHICULO******/} {isVehiculo && <View> <View> <View style={styles.headerTitle_2}> <Text style={styles.headerTitleText}>VEHICULO</Text> </View> <View> <FormLabel labelStyle={styles.labelStyle}>TIPO PRESTAMO</FormLabel> <FormInput value={this.state.solicitud.TipoPrestamo} editable={false} /> </View> <View> <FormLabel labelStyle={styles.labelStyle}>PRECIO VEHICULO (*)</FormLabel> <FormInput value={`${this.state.solicitud.PrecioVehiculo}`} keyboardType={'numeric'} onChangeText={(text) => { this.setState(prevState => ({ solicitud: { ...prevState.solicitud, PrecioVehiculo: text } })) }} editable={false} /> </View> <View> <FormLabel labelStyle={styles.labelStyle}>DEALER (*)</FormLabel> <TouchableOpacity onPress={this.onOpenSelectDealer} enabled={false}> <FormInput value={this.state.solicitud.DealerNombre} editable={false} /> </TouchableOpacity> </View> <View style={{ flexDirection: 'row' }}> <View style={{ flex: 1 }}> <FormLabel labelStyle={styles.labelStyle}>AÑO VEHICULO (*)</FormLabel> <Picker style={{ marginLeft: 10 }} selectedValue={this.state.solicitud.AnoVehiculoId} onValueChange={(itemValue) => this.setState(prevState => ({ solicitud: { ...prevState.solicitud, AnoVehiculoId: itemValue } })) } enabled={false}> <Picker.Item label='[ SELECCIONE ]' value='' /> {this.state.anosVehiculo.map((item, index) => ( <Picker.Item label={item.Descripcion} value={item.IdAnoVehiculo} key={index} />) )} </Picker> </View> </View> <View style={{ flexDirection: 'row' }}> <View style={{ flex: 1 }}> <FormLabel labelStyle={styles.labelStyle}>MARCA VEHICULO (*)</FormLabel> <Picker style={{ marginLeft: 10 }} selectedValue={this.state.solicitud.MarcaVehiculoId} onValueChange={(itemValue) => this.onMarcaValueChange(itemValue)} enabled={false}> <Picker.Item label='[ SELECCIONE ]' value='' /> {this.state.marcasVehiculo.map((item, index) => ( <Picker.Item label={item.Descripcion} value={item.IdMarcaVehiculo} key={index} />) )} </Picker> </View> <View style={{ flex: 1 }}> <FormLabel labelStyle={styles.labelStyle}>MODELO VEHICULO (*)</FormLabel> <Picker style={{ marginLeft: 10 }} selectedValue={this.state.solicitud.ModeloVehiculoId} onValueChange={(itemValue) => this.setState(prevState => ({ solicitud: { ...prevState.solicitud, ModeloVehiculoId: itemValue } })) } enabled={false}> <Picker.Item label='[ SELECCIONE ]' value='' /> {this.state.modelosVehiculo.map((item, index) => ( <Picker.Item label={item.Descripcion} value={item.IdModeloVehiculo} key={index} />) )} </Picker> </View> </View> </View> </View> } {/*****PESTAMO Y GARANTIA******/} <View> <View style={styles.headerTitle_2}> <Text style={styles.headerTitleText}>PESTAMO Y GARANTIA</Text> </View> <View> <FormLabel labelStyle={styles.labelStyle}>TIPO PRESTAMO</FormLabel> <FormInput value={this.state.solicitud.TipoPrestamo} editable={false} /> </View> <View> <FormLabel labelStyle={styles.labelStyle}>MONTO PRESTAMO (*)</FormLabel> <FormInput value={`${this.state.solicitud.MontoPrestamo}`} keyboardType={'numeric'} onChangeText={(text) => { this.setState(prevState => ({ solicitud: { ...prevState.solicitud, MontoPrestamo: text } })) }} editable={false} /> </View> <View style={{ flexDirection: 'row' }}> <View style={{ flex: 1 }}> <FormLabel labelStyle={styles.labelStyle}>MESES (*)</FormLabel> <FormInput value={`${this.state.solicitud.Meses}`} keyboardType={'numeric'} onChangeText={(text) => { this.setState(prevState => ({ solicitud: { ...prevState.solicitud, Meses: text } })) }} editable={false} /> </View> <View style={{ flex: 1 }}> <FormLabel labelStyle={styles.labelStyle}>TASA (*)</FormLabel> <FormInput value={`${this.state.solicitud.Tasa}`} keyboardType={'default'} onChangeText={(text) => { this.setState(prevState => ({ solicitud: { ...prevState.solicitud, Tasa: text } })) }} editable={false} /> </View> </View> <View> <FormLabel labelStyle={styles.labelStyle}>COMENTARIO</FormLabel> <FormInput value={`${this.state.solicitud.Comentario}`} keyboardType={'default'} onChangeText={(text) => { this.setState(prevState => ({ solicitud: { ...prevState.solicitud, Comentario: text } })) }} /> </View> </View> {/*****ACTION BUTTONS******/} <View style={{ flex: 1, justifyContent: 'flex-end' }}> <View style={{ flexDirection: 'row' }}> <View style={{ flex: 1 }}> <TouchableNativeFeedback onPress={() => this.cancelSolicitud()}> <View style={{ padding: 13, backgroundColor: '#999', elevation: 1, justifyContent: 'center', alignItems: 'center' }}> <Text style={{ color: '#fff', fontWeight: '500', fontSize: 14 }}>CANCELAR</Text> </View> </TouchableNativeFeedback> </View> <View style={{ flex: 1 }}> <TouchableNativeFeedback onPress={this.saveSolicitud}> <View style={{ padding: 13, backgroundColor: '#16a085', elevation: 1, justifyContent: 'center', alignItems: 'center' }}> <Text style={{ color: '#fff', fontWeight: '500', fontSize: 14 }}> GUARDAR CAMBIOS </Text> </View> </TouchableNativeFeedback> </View> </View> </View> </ScrollView> </View> ); }; render() { const { isLoading, solicitud = {}, isVehiculo } = this.state; return ( <View style={styles.container}> {isLoading ? (<LoadingIndicator />) : this._renderForm(solicitud, isVehiculo)} {/*Select Dealer Modal */} <ModalFilterPicker visible={this.state.showSelectedDealer} onSelect={this.onSelect} onCancel={this.onCancel} options={this.state.dealers} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: globalStyle.WhiteColor }, headerTitle: { backgroundColor: '#7f8c8d', padding: 10, justifyContent: 'center', flex: 2 }, headerTitle_2: { backgroundColor: '#7f8c8d', padding: 10, marginTop: 10, }, headerTitleText: { fontSize: 16, fontWeight: '400', color: '#ecf0f1' }, labelStyle: { color: '#5b6e7a' }, inputStyle: { borderColor: '#eee', borderWidth: 1 } }); export { DetailsRelation };
/*eslint-env node */ /* eslint quotes: [2, "single"], no-console: 0 */ var path = require('path'); var koa = require('koa'); var bodyParser = require('koa-bodyparser'); var serve = require('koa-static'); var render = require('koa-ejs'); var router = require('koa-router')(); var app = koa(); var items = []; render(app, { root: path.join(__dirname, 'templates'), viewExt: 'html', cache: false, debug: true }); router .get('/', function *() { yield this.render('app', { items: JSON.stringify(items), env: process.env.NODE_ENV }); }) .put('/api/state', function *() { items = this.request.body; this.status = 204; }); app .use(bodyParser()) .use(serve(path.join(__dirname, 'dist'))) .use(router.routes()) .use(router.allowedMethods()); console.log('Listening on 3000'); app.listen(3000);
import React from "react"; import Markdown from "markdown-to-jsx"; import moment from "moment"; import {PostDate} from "../"; import {AuthorAvatar, AuthorDetails, AuthorName} from "../Author"; import {CommentContainer} from "./"; import {HyperLink, CodeBlock} from "../../Markdown/Overrides"; export const Comment = ({comment}) => { return ( <CommentContainer> <AuthorDetails> <AuthorAvatar src={comment.author.avatarUrl} alt={comment.author.login} /> <div> <AuthorName>{comment.author.login}</AuthorName> <PostDate>{moment(comment.updatedAt).format("DD/MM/YYYY")}</PostDate> </div> </AuthorDetails> <Markdown options={{ overrides: { a: { component: HyperLink, }, pre: { component: CodeBlock, }, }, }} > {comment.body} </Markdown> </CommentContainer> ); };
export function configure(aurelia) { aurelia.use .standardConfiguration() .developmentLogging() // Install the plugin // .plugin('aurelia-bs-modal'); aurelia.start().then(a => a.setRoot()); }
const express = require("express"); const router = express.Router(); const { getCategories, getCategoryById, createCategory, updateCategory, deleteCategory, getProductsFromCategory } = require('./categoriesController'); router.get('/', async function(req, res, next) { try { const categories = await getCategories(); res.status(200).json([...categories]); } catch(e) { next(e); } }); router.get('/:id', async function(req, res, next) { try { const category = await getCategoryById(req); res.status(200).json({...category}); } catch(e) { next(e); } }); router.post('/', async function(req, res, next) { try { const category = await createCategory(req); res.status(201).json({_id: category,...req.body,}); } catch(e) { next(e); } }); router.put('/:id', async function(req, res, next) { try { const category = await updateCategory(req); res.status(200).json({...category}); } catch(e) { next(e); } }); router.delete('/:id', async function(req, res, next) { try { await deleteCategory(req); res.status(200).json(true); } catch(e) { next(e); } }); router.get('/:id/products', async function(req, res, next) { try { const products = await getProductsFromCategory(req); res.status(200).json([...products]); } catch(e) { next(e); } }); module.exports = router;
/** * Layout component that queries for data * with Gatsby's useStaticQuery component * * See: https://www.gatsbyjs.org/docs/use-static-query/ */ import React from "react" import PropTypes from "prop-types" import { useStaticQuery, graphql, Link } from "gatsby" import Header from "./header" import "./layout.css" const Layout = ({ children }) => { const data = useStaticQuery(graphql` query SiteTitleQuery { site { siteMetadata { title, description, author } } } `) return ( <> <Header siteTitle={data.site.siteMetadata.title} siteDescription={data.site.siteMetadata.author} about="About" contact="Contact" blog="Blog" /> <div style={{ margin: `0 auto`, maxWidth: 960, padding: `0px 1.0875rem 1.45rem`, paddingTop: 0, }} > <main style={{ minHeight: "100vh" }}>{children}</main> </div> <footer style={{ background: "rgba(50,50,50,0.5", textAlign: "center", minHeight: "3rem" }}> <h3>© {new Date().getFullYear()}, Built by <Link to="/" style={{textDecoration: "none"}}>{data.site.siteMetadata.author}</Link></h3> </footer> </> ) } Layout.propTypes = { children: PropTypes.node.isRequired, } export default Layout
const Joi = require('joi'); const id = Joi.number().integer(); const name = Joi.string(); const fecha = Joi.string(); const getGradeSchema = Joi.object({ id: id.required(), }); const createGradeSchema = Joi.object({ name: name.required(), fecha: fecha.required(), }); const updateGradeSchema = Joi.object({ name, fecha, }); module.exports = { getGradeSchema, createGradeSchema, updateGradeSchema };
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v0.8.3 */ goog.provide('ng.material.components.toolbar'); goog.require('ng.material.components.content'); goog.require('ng.material.core'); (function() { 'use strict'; /** * @ngdoc module * @name material.components.toolbar */ angular.module('material.components.toolbar', [ 'material.core', 'material.components.content' ]) .directive('mdToolbar', mdToolbarDirective); /** * @ngdoc directive * @name mdToolbar * @module material.components.toolbar * @restrict E * @description * `md-toolbar` is used to place a toolbar in your app. * * Toolbars are usually used above a content area to display the title of the * current page, and show relevant action buttons for that page. * * You can change the height of the toolbar by adding either the * `md-medium-tall` or `md-tall` class to the toolbar. * * @usage * <hljs lang="html"> * <div layout="column" layout-fill> * <md-toolbar> * * <div class="md-toolbar-tools"> * <span>My App's Title</span> * * <!-- fill up the space between left and right area --> * <span flex></span> * * <md-button> * Right Bar Button * </md-button> * </div> * * </md-toolbar> * <md-content> * Hello! * </md-content> * </div> * </hljs> * * @param {boolean=} md-scroll-shrink Whether the header should shrink away as * the user scrolls down, and reveal itself as the user scrolls up. * Note: for scrollShrink to work, the toolbar must be a sibling of a * `md-content` element, placed before it. See the scroll shrink demo. * * * @param {number=} md-shrink-speed-factor How much to change the speed of the toolbar's * shrinking by. For example, if 0.25 is given then the toolbar will shrink * at one fourth the rate at which the user scrolls down. Default 0.5. */ function mdToolbarDirective($$rAF, $mdConstant, $mdUtil, $mdTheming) { return { restrict: 'E', controller: angular.noop, link: function(scope, element, attr) { $mdTheming(element); if (angular.isDefined(attr.mdScrollShrink)) { setupScrollShrink(); } function setupScrollShrink() { // Current "y" position of scroll var y = 0; // Store the last scroll top position var prevScrollTop = 0; var shrinkSpeedFactor = attr.mdShrinkSpeedFactor || 0.5; var toolbarHeight; var contentElement; var debouncedContentScroll = $$rAF.throttle(onContentScroll); var debouncedUpdateHeight = $mdUtil.debounce(updateToolbarHeight, 5 * 1000); // Wait for $mdContentLoaded event from mdContent directive. // If the mdContent element is a sibling of our toolbar, hook it up // to scroll events. scope.$on('$mdContentLoaded', onMdContentLoad); function onMdContentLoad($event, newContentEl) { // Toolbar and content must be siblings if (element.parent()[0] === newContentEl.parent()[0]) { // unhook old content event listener if exists if (contentElement) { contentElement.off('scroll', debouncedContentScroll); } newContentEl.on('scroll', debouncedContentScroll); newContentEl.attr('scroll-shrink', 'true'); contentElement = newContentEl; $$rAF(updateToolbarHeight); } } function updateToolbarHeight() { toolbarHeight = element.prop('offsetHeight'); // Add a negative margin-top the size of the toolbar to the content el. // The content will start transformed down the toolbarHeight amount, // so everything looks normal. // // As the user scrolls down, the content will be transformed up slowly // to put the content underneath where the toolbar was. contentElement.css( 'margin-top', (-toolbarHeight * shrinkSpeedFactor) + 'px' ); onContentScroll(); } function onContentScroll(e) { var scrollTop = e ? e.target.scrollTop : prevScrollTop; debouncedUpdateHeight(); y = Math.min( toolbarHeight / shrinkSpeedFactor, Math.max(0, y + scrollTop - prevScrollTop) ); element.css( $mdConstant.CSS.TRANSFORM, 'translate3d(0,' + (-y * shrinkSpeedFactor) + 'px,0)' ); contentElement.css( $mdConstant.CSS.TRANSFORM, 'translate3d(0,' + ((toolbarHeight - y) * shrinkSpeedFactor) + 'px,0)' ); prevScrollTop = scrollTop; } } } }; } mdToolbarDirective.$inject = ["$$rAF", "$mdConstant", "$mdUtil", "$mdTheming"]; })();
/** Copyright 2018 Cisco and/or its affiliates 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. */ // SANDPlayer collection types enum const SANDPlayer_Collectors = { NEVER_COLLECT: 0, COLLECT_AT_INTERVAL: 1, COLLECT_ON_SEGMENT_DONE: 2, COLLECT_ON_STATS_CHANGE: 3, COLLECT_ON_STATS_CHANGE_THROTTLED: 4, COLLECT_ON_SEGMENT_DONE_THROTTLED: 5 }; // create a SANDPlayer using the given video tag, DASH URL and options var SANDPlayer = function (video_tag, video_url, userOption) { // defaults var options = { // ID for this player (component), generate new one if not given id: generateUUID(), // DMAppID, generate new if not given dmapp: generateUUID(), // monitor interval in ms monitor_interval: 1000, // history items to keep monitor_history: 30, // last interval monitored monitorLastInterval: 0, // URL of the collector (Bandwdith Orchestration Service) collectorUrl: null, // Collection type (choose from the enum above) collectorType: SANDPlayer_Collectors.NEVER_COLLECT, // data collection interval collectionInterval: 1000, }; //<editor-fold desc="Utilities"> // generate a UUID function generateUUID() { var d = new Date().getTime(); var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = (d + Math.random()*16)%16 | 0; d = Math.floor(d/16); return (c=='x' ? r : (r&0x3|0x8)).toString(16); }); return uuid; }; //</editor-fold> //<editor-fold desc="Bandwidth Monitor"> // collection interval object var reporter; // monitor background task var monitor; // stats update client callback var onStatsUpdateCallback; // an MPEG DASH SAND message template var sandMessage = { senderId: options.id, dmappId: options.dmapp }; // metric holder var metric = { averageThroughput: { avgVideoThroughput: 0, avgAudioThroughput: 0, avgThroughput: 0 }, bandwidth: { video: { current: 0, history: [], average: 0 }, audio: { current: 0, history: [], average: 0 }, current: 0, average: 0 }, bitrate: { playing: { video: 0, audio: 0 }, queued: { video: 0, audio: 0 } }, bitrates: { video: [], audio: [] }, status: "uninitialized" }; var prevMetric = $.extend(true, {}, metric); // bandwidth data var fragmentRequests = {}; var fragmentState = {}; var buildMessage = function() { return $.extend(true, {}, sandMessage, metric, {generationTime: Date.now()}); } // report metrics to collector var sendMetric = function() { // build message var message = buildMessage(); // send sand message to collector //console.log("Sending metrics: " + message); $.ajax({ method: "POST", url: options.collectorUrl, data: JSON.stringify(message), contentType: "application/json" }).done(function(data, status, q) { console.log("sent metrics"); }).fail(function(data, status, q) { console.log("failed to send metrics: " + status); }); setTimeout(function() {onStatsUpdateCallback(message)}, 0); }; // get the current average throughput and send to the collector var collectMetrics = function() { metric.averageThroughput.avgVideoThroughput = player.getAverageThroughput("video"); metric.averageThroughput.avgAudioThroughput = player.getAverageThroughput("audio"); metric.averageThroughput.avgThroughput = metric.averageThroughput.avgVideoThroughput + metric.averageThroughput.avgAudioThroughput; // we make a copy here because this changes while we work! // TODO: make sure we actually need to copy ... var videoMetrics = $.extend(true, {}, player.getMetricsFor("video")); var audioMetrics = $.extend(true, {}, player.getMetricsFor("audio")); var dashMetrics = $.extend(true, {}, player.getDashMetrics()); // current playing bitrate metric.bitrate.playing.video = metric.bitrates.video[player.getQualityFor('video')]; metric.bitrate.playing.audio = metric.bitrates.audio[player.getQualityFor('audio')]; // current scheduled bitrate var videoQuality = dashMetrics.getCurrentSchedulingInfo(videoMetrics).quality; metric.bitrate.queued.video = isNaN(videoQuality) ? prevMetric.bitrate.queued.video : metric.bitrates.video[videoQuality]; var audioQuality = dashMetrics.getCurrentSchedulingInfo(audioMetrics).quality; metric.bitrate.queued.audio = isNaN(audioQuality) ? prevMetric.bitrate.queued.audio : metric.bitrates.audio[audioQuality]; sendMetric(); }; // monitoring function var monitorPlayer = function() { // now? var intervalEnd = Date.now(); var intervalStart = options.monitorLastInterval; options.monitorLastInterval = intervalStart; var intervalSize = intervalEnd - intervalStart; /** bandwidth **/ // start by copying the data so it doesn't change anymore! var requests = $.extend(true, {}, fragmentRequests); var bandwidth = { video: 0, audio: 0 }; // go over the requests for (var url in requests) { var request = requests[url]; if (!request.firstByteDate) { continue; } // the request is done if (request.requestEndDate) { // thee request started and ended within the current interval if (request.requestStartDate >= intervalStart) { var duration = request.requestEndDate - request.requestStartDate; // console.log("case 1"); // console.log(request.requestEndDate - 0); // console.log(request.requestStartDate - 0); // console.log(duration); // console.log(request.bytesTotal); bandwidth[request.mediaType] += 1000.0 / duration * request.bytesTotal; delete fragmentRequests[url]; } // the request started before this interval start and ended within this interval else if (request.requestStartDate < intervalStart) { var duration = request.requestEndDate - intervalStart; var reduction = fragmentState[url] ? fragmentState[url] : 0; // console.log("case 2"); // console.log(duration); // console.log(request.bytesTotal - reduction); bandwidth[request.mediaType] += 1000.0 / duration * (request.bytesTotal - reduction); delete fragmentState[url] delete fragmentRequests[url]; } } else { // the request started within this interval and has not yet finished if (request.requestStartDate >= intervalStart) { var duration = intervalEnd - request.requestStartDate; // console.log("case 3"); // console.log(duration); // console.log(request.bytesLoaded); bandwidth[request.mediaType] += 1000.0 / duration * request.bytesLoaded; fragmentState[url] = request.bytesLoaded; } // this request started before this interval and has not yet ended else { var duration = intervalSize; var reduction = fragmentState[url] ? fragmentState[url] : 0; // console.log("case 4"); // console.log(duration); // console.log(request.bytesLoaded - reduction); bandwidth[request.mediaType] += 1000.0 / duration * (request.bytesLoaded - reduction); fragmentState[url] = request.bytesLoaded; } } } // hopefully, we should now have proper bandwidth measurements! metric.bandwidth.video.current = bandwidth.video; metric.bandwidth.audio.current = bandwidth.audio; metric.bandwidth.current = bandwidth.video + bandwidth.audio; metric.bandwidth.video.history.push(bandwidth.video); if (metric.bandwidth.video.history.length > options.monitor_history) { metric.bandwidth.video.history.shift(); } metric.bandwidth.video.average = metric.bandwidth.video.history.reduce(function(sum, value) {return sum + value;}, 0) / metric.bandwidth.video.history.length; metric.bandwidth.audio.history.push(bandwidth.audio); if (metric.bandwidth.audio.history.length > options.monitor_history) { metric.bandwidth.audio.history.shift(); } metric.bandwidth.audio.average = metric.bandwidth.audio.history.reduce(function(sum, value) {return sum + value;}, 0) / metric.bandwidth.audio.history.length; metric.bandwidth.average = metric.bandwidth.video.average + metric.bandwidth.audio.average; prevMetric = $.extend(true, {}, metric); }; //</editor-fold> // prep options options = $.extend(true, options, userOption); sandMessage.senderId = options.id; sandMessage.dmappId = options.dmapp; // create the dash player var player = dashjs.MediaPlayer().create(); // register a callback function to do client-side handling of stats updates var onStatsUpdate = function(callback) { onStatsUpdateCallback = callback; } // initialize the player var init = function(onCanPlay = function(){}) { // update network state player.on(dashjs.MediaPlayer.events.FRAGMENT_LOADING_STARTED, function(e) { metric.status = "downloading"; fragmentRequests[e.request.url] = e.request; }); player.on(dashjs.MediaPlayer.events.FRAGMENT_LOADING_COMPLETED, function() { metric.status = "idle"; }); player.on(dashjs.MediaPlayer.events.FRAGMENT_LOADING_ABANDONED, function() { metric.status = "idle"; }); // run user provided callback when ready to start playback player.on(dashjs.MediaPlayer.events.CAN_PLAY, function () { // get available bitrates player.getBitrateInfoListFor("video").forEach(function(item, index) { metric.bitrates.video[item.qualityIndex] = item.bitrate; }); player.getBitrateInfoListFor("audio").forEach(function(item, index) { metric.bitrates.audio[item.qualityIndex] = item.bitrate; }); onCanPlay(); }); // init player.initialize(video_tag, video_url, false); // start the monitor monitor = setInterval(monitorPlayer, options.monitor_interval); options.monitorLastInterval = Date.now(); // setup callbacks switch (options.collectorType) { case SANDPlayer_Collectors.COLLECT_ON_SEGMENT_DONE_THROTTLED: player.on(dashjs.MediaPlayer.events.FRAGMENT_LOADING_COMPLETED, $.throttle(options.collectionInterval, collectMetrics)); break; case SANDPlayer_Collectors.COLLECT_ON_STATS_CHANGE_THROTTLED: player.on(dashjs.MediaPlayer.events.METRIC_CHANGED, $.throttle(options.collectionInterval, collectMetrics)); break; case SANDPlayer_Collectors.COLLECT_AT_INTERVAL: reporter = setInterval(collectMetrics, options.collectionInterval); break; case SANDPlayer_Collectors.COLLECT_ON_SEGMENT_DONE: player.on(dashjs.MediaPlayer.events.FRAGMENT_LOADING_COMPLETED, collectMetrics); break; case SANDPlayer_Collectors.COLLECT_ON_STATS_CHANGE: player.on(dashjs.MediaPlayer.events.METRIC_CHANGED, collectMetrics); break; case SANDPlayer_Collectors.NEVER_COLLECT: break; default: console.log("No such collection policy, will NOT send statistics to collector!"); break; } } // start playback var play = function() { player.play(); }; // stop/pause playback var pause = function() { player.pause(); }; // destroy player var destroy = function() { player.pause(); if (reporter) { clearInterval(reporter); reporter = undefined; } if (monitor) { clearInterval(monitor); monitor = undefined; } player.reset(); }; // toggle (true/false) Adaptive BitRate var toggleABR = function(vaule) { player.setAutoSwitchQuality(value); }; // toggle (true/false) Adaptive BitRate for given type ("video" or "audio") var toggleABRForType = function(type, vaule) { player.setAutoSwitchQualityFor(type, value); }; // toggle (true/false) video Adaptive BitRate var toggleVideoABR = function(toggle) { player.setAutoSwitchQualityFor("video", value); }; // toggle (true/false) audio Adaptive BitRate var toggleAudioABR = function(toggle) { player.setAutoSwitchQualityFor("audio", value); }; // get the quality index of the given bitrate. // if this bitrate does not exist, returns 0. var getQualityForBitrate = function(type, bitrate) { for (var quality in metric.bitrates[type]) { if (metric.bitrates[type][quality] == bitrate) { return quality; } } return 0; } // set the bitrate for the given type ("video" or "audio"). selects first bitrate if doesn't exist. var setBitrate = function(type, bitrate) { player.setQualityFor(type, getQualityForBitrate(type, bitrate)); } // set the video bitrate. selects first bitrate if doesn't exist. var setVideoBitrate = function(bitrate) { player.setQualityFor("video", getQualityForBitrate("video", bitrate)); }; // set the audio bitrate. selects first bitrate if doesn't exist. var setAudioBitrate = function(bitrate) { player.setQualityFor("audio", getQualityForBitrate("audio", bitrate)); }; // limit the allowed bitrate for type ("video" or "audio"). use NaN to clear limit var limitBitrate = function(type, bitrate) { player.setMaxAllowedBitrateFor(type, bitrate); }; // limit the alowed video bitrate. use NaN to clear limit var limitVideoBitrate = function(bitrate) { player.setMaxAllowedBitrateFor("video", bitrate); }; // limit the allowed audio bitrate. use NaN to clear limit var limitAudioBitrate = function(bitrate) { player.setMaxAllowedBitrateFor("audio", bitrate); }; // return the list of available video and audio bitrates. valid only after player initialization var getAvailableBitrates = function() { return $.extend(true, [], metric.bitrates); }; return { /** DATA **/ // the DOM node of the video tag video_tag: video_tag, // video url video_url: video_url, // the dash.js player player: player, // options options: options, /** Metrics **/ // function run when sending stats (in case you want to do something with the stats client-side onStatsUpdate: onStatsUpdate, /** Playback Control **/ // initialize the player, can get a callback to run when ready init: init, play: play, pause: pause, // pause playback, clear reporter and clear monitor, reset the dash.js player destroy: destroy, /** Bitrate Control (valid only after initialization) **/ toggleABR: toggleABR, toggleABRForType: toggleABRForType, toggleVideoABR: toggleVideoABR, toggleAudioABR: toggleAudioABR, setBitrate: setBitrate, setVideoBitrate: setVideoBitrate, setAudioBitrate: setAudioBitrate, limitBitrate: limitBitrate, limitVideoBitrate: limitVideoBitrate, limitAudioBitrate: limitAudioBitrate, getAvailableBitrates: getAvailableBitrates }; };
// flow-typed signature: 5f1298f20d2329f008c4e3913692b542 // flow-typed version: <<STUB>>/babel-preset-flow_v^6.23.0/flow_v0.40.0 /** * This is an autogenerated libdef stub for: * * 'babel-preset-flow' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'babel-preset-flow' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'babel-preset-flow/lib/index' { declare module.exports: any; } // Filename aliases declare module 'babel-preset-flow/lib/index.js' { declare module.exports: $Exports<'babel-preset-flow/lib/index'>; }
var modal = document.querySelector('.modal'); var modalFrame = document.querySelector('.modal-frame'); var modalClose = document.querySelector('.modal-close'); var modalTitle = document.querySelector('.modal-title'); (function() { var counter = document.querySelector('.stargazers'); var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://api.github.com/repos/goldfire/howler.js', true); xhr.onload = function() { var res = xhr.response; var count = 0; try { count = JSON.parse(xhr.response).stargazers_count; } catch (e) {} counter.innerText = (count ? count.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') : '14,000+') + ' stars'; }; xhr.onerror = function() { counter.innerText = '15,000+ stars'; }; xhr.send(); })(); function showDemo(id) { if (id === 6) { window.location = 'https://github.com/yamoo9/howler.js/tree/master/examples'; return; } var uri = 'https://howlerjs.com/assets/howler.js/examples/'; if (id === 1) { uri += 'player/'; modalTitle.innerText = 'Music Player'; } else if (id === 2) { uri += 'radio/'; modalTitle.innerText = 'Live Radio'; } else if (id === 3) { uri += 'sprite/'; modalTitle.innerText = 'Audio Sprites'; } else if (id === 4) { uri += '3d/'; modalTitle.innerText = 'Spatial Audio'; } else if (id === 5) { uri = '/assets/howler.js/tests/'; modalTitle.innerText = 'Basic Functions'; } modal.className = 'modal fadein'; modal.style.display = '-webkit-box'; modal.style.display = '-webkit-flex'; modal.style.display = '-ms-flexbox'; modal.style.display = 'flex'; var iframe = document.createElement('iframe'); iframe.src = uri; modalFrame.appendChild(iframe); iframe.focus(); } (function() { var demos = [ 'player', 'radio', 'sprite', 'spatial', 'basic', 'code' ]; demos.forEach(function(selector, index) { var demo = document.querySelector('.' + selector); if (demo) { demo.addEventListener('click', function() { showDemo(index + 1); }); } }); if (modalClose) { modalClose.addEventListener('click', function() { modal.className = 'modal fadeout'; setTimeout(function() { var iframe = document.querySelector('.modal iframe'); modal.style.display = 'none'; iframe.src = 'about:blank'; modalFrame.removeChild(iframe); if ( window.location.hash && window.location.hash !== '' && window.history && window.history.pushState ) { window.history.pushState(null, null, '.'); } }, 500); }); } var hash = (window.location.hash + '').replace('#', ''); if (hash && hash.match(/player|radio|sprite|spatial|basic/)) { showDemo(demos.indexOf(hash) + 1); } })();
/** * ShapeInfo.js * @copyright 2002, 2017 Kevin Lindsey */ import {Point2D} from "kld-affine"; import {PathParser} from "kld-path-parser"; import PathHandler from "./PathHandler.js"; const degree90 = Math.PI * 0.5; const parser = new PathParser(); /** * getValues * * @param {Array} types * @param {Array} args * @returns {Array} */ export function getValues(types, args) { const result = []; for (const [names, type] of types) { let value = null; if (type === "Point2D") { value = parsePoint(names, args); } else if (type === "Number") { value = parseNumber(names, args); } else if (type === "Array<Point2D>" || type === "Point2D[]") { const values = []; while (args.length > 0) { values.push(parsePoint(names, args)); } if (values.length > 0) { value = values; } } else if (type === "Optional<Number>" || type === "Number?") { value = parseNumber(names, args); if (value === null) { value = undefined; } } else { throw new TypeError(`Unrecognized value type: ${type}`); } if (value !== null) { result.push(value); } else { throw new TypeError(`Unable to extract value for ${names}`); } } return result; } /** * parseNumber * * @param {Array} names * @param {Array} args * @returns {number} */ export function parseNumber(names, args) { let result = null; if (args.length > 0) { const item = args[0]; const itemType = typeof item; if (itemType === "number") { return args.shift(); } else if (itemType === "object") { for (const prop of names) { if (prop in item && typeof item[prop] === "number") { result = item[prop]; break; } } } } return result; } /** * parsePoint * * @param {Array} names * @param {Array} args * @returns {Array} */ export function parsePoint(names, args) { let result = null; if (args.length > 0) { const item = args[0]; const itemType = typeof item; if (itemType === "number") { if (args.length > 1) { const x = args.shift(); const y = args.shift(); result = new Point2D(x, y); } } else if (Array.isArray(item) && item.length > 1) { if (item.length === 2) { const [x, y] = args.shift(); result = new Point2D(x, y); } else { throw new TypeError(`Unhandled array of length ${item.length}`); } } else if (itemType === "object") { if ("x" in item && "y" in item) { result = new Point2D(item.x, item.y); // eslint-disable-next-line compat/compat if (Object.keys(item).length === 2) { args.shift(); } } else { for (const props of names) { if (Array.isArray(props)) { if (props.every(p => p in item)) { result = new Point2D(item[props[0]], item[props[1]]); break; } } else if (props in item) { result = parsePoint([], [item[props]]); break; } } } } } return result; } /** * ShapeInfo * @memberof module:kld-intersections */ export default class ShapeInfo { /** * @param {string} name * @param {Array} args * @returns {module:kld-intersections.ShapeInfo} */ constructor(name, args) { this.name = name; this.args = args; } static arc(...args) { const types = [ [["center", ["centerX", "centerY"], ["cx", "cy"]], "Point2D"], [["radiusX", "rx"], "Number"], [["radiusY", "ry"], "Number"], [["startRadians"], "Number"], [["endRadians"], "Number"] ]; const values = getValues(types, args); return new ShapeInfo(ShapeInfo.ARC, values); } static quadraticBezier(...args) { const types = [ [["p1", ["p1x", "p1y"]], "Point2D"], [["p2", ["p2x", "p2y"]], "Point2D"], [["p3", ["p3x", "p3y"]], "Point2D"] ]; const values = getValues(types, args); return new ShapeInfo(ShapeInfo.QUADRATIC_BEZIER, values); } static cubicBezier(...args) { const types = [ [["p1", ["p1x", "p1y"]], "Point2D"], [["p2", ["p2x", "p2y"]], "Point2D"], [["p3", ["p3x", "p3y"]], "Point2D"], [["p4", ["p4x", "p4y"]], "Point2D"] ]; const values = getValues(types, args); return new ShapeInfo(ShapeInfo.CUBIC_BEZIER, values); } static circle(...args) { const types = [ [["center", ["centerX", "centerY"], ["cx", "cy"]], "Point2D"], [["radius", "r"], "Number"] ]; const values = getValues(types, args); return new ShapeInfo(ShapeInfo.CIRCLE, values); } static ellipse(...args) { const types = [ [["center", ["centerX", "centerY"], ["cx", "cy"]], "Point2D"], [["radiusX", "rx"], "Number"], [["radiusY", "ry"], "Number"] ]; const values = getValues(types, args); return new ShapeInfo(ShapeInfo.ELLIPSE, values); } static line(...args) { const types = [ [["p1", ["p1x", "p1y"], ["x1", "y1"]], "Point2D"], [["p2", ["p2x", "p2y"], ["x2", "y2"]], "Point2D"] ]; const values = getValues(types, args); return new ShapeInfo(ShapeInfo.LINE, values); } static path(...args) { parser.parseData(args[0]); return new ShapeInfo(ShapeInfo.PATH, handler.shapes); } static polygon(...args) { const types = [ [[], "Array<Point2D>"] ]; const values = getValues( types, args.length === 1 && Array.isArray(args[0]) ? args[0] : args ); return new ShapeInfo(ShapeInfo.POLYGON, values); } static polyline(...args) { const types = [ [[], "Array<Point2D>"] ]; const values = getValues( types, args.length === 1 && Array.isArray(args[0]) ? args[0] : args ); return new ShapeInfo(ShapeInfo.POLYLINE, values); } static rectangle(...args) { const types = [ [["topLeft", ["x", "y"], ["left", "top"]], "Point2D"], [["size", ["width", "height"], ["w", "h"]], "Point2D"], [["radiusX", "rx"], "Optional<Number>"], [["radiusY", "ry"], "Optional<Number>"] ]; const values = getValues(types, args); // fix up bottom-right point const p1 = values[0]; const p2 = values[1]; values[1] = new Point2D(p1.x + p2.x, p1.y + p2.y); // create shape info const result = new ShapeInfo(ShapeInfo.RECTANGLE, values); // handle possible rounded rectangle values let ry = result.args.pop(); let rx = result.args.pop(); rx = rx === undefined ? 0 : rx; ry = ry === undefined ? 0 : ry; if (rx === 0 && ry === 0) { return result; } const {x: p1x, y: p1y} = result.args[0]; const {x: p2x, y: p2y} = result.args[1]; const width = p2x - p1x; const height = p2y - p1y; if (rx === 0) { rx = ry; } if (ry === 0) { ry = rx; } if (rx > width * 0.5) { rx = width * 0.5; } if (ry > height * 0.5) { ry = height * 0.5; } const x0 = p1x; const y0 = p1y; const x1 = p1x + rx; const y1 = p1y + ry; const x2 = p2x - rx; const y2 = p2y - ry; const x3 = p2x; const y3 = p2y; const segments = [ ShapeInfo.arc(x1, y1, rx, ry, 2 * degree90, 3 * degree90), ShapeInfo.line(x1, y0, x2, y0), ShapeInfo.arc(x2, y1, rx, ry, 3 * degree90, 4 * degree90), ShapeInfo.line(x3, y1, x3, y2), ShapeInfo.arc(x2, y2, rx, ry, 0, degree90), ShapeInfo.line(x2, y3, x1, y3), ShapeInfo.arc(x1, y2, rx, ry, degree90, 2 * degree90), ShapeInfo.line(x0, y2, x0, y1) ]; return new ShapeInfo(ShapeInfo.PATH, segments); } } // define shape name constants ShapeInfo.ARC = "Arc"; ShapeInfo.QUADRATIC_BEZIER = "Bezier2"; ShapeInfo.CUBIC_BEZIER = "Bezier3"; ShapeInfo.CIRCLE = "Circle"; ShapeInfo.ELLIPSE = "Ellipse"; ShapeInfo.LINE = "Line"; ShapeInfo.PATH = "Path"; ShapeInfo.POLYGON = "Polygon"; ShapeInfo.POLYLINE = "Polyline"; ShapeInfo.RECTANGLE = "Rectangle"; // setup path parser handler after ShapeInfo has been defined const handler = new PathHandler(ShapeInfo); parser.setHandler(handler);
var SimpleStorage = artifacts.require("./SimpleStorage.sol"); var Betme = artifacts.require("./Betme.sol"); module.exports = function (deployer) { deployer.deploy(SimpleStorage); deployer.deploy(Betme); };
const articledown = require('./index'); const BAD_ARG_ERROR = 'Bad argument sent, must be a non empty string'; const BAD_URL_ERROR = url => `Url ${url} is not found`; test('Send good url', async () => { const url = 'https://medium.com/@johndevore/i-am-fine-a19b36867a33'; return expect(await articledown(url)).toMatchObject({ link: 'https://medium.com/@johndevore/i-am-fine-a19b36867a33', title: 'I Am Fine', titleMarkdown: 'I Am Fine', }); }); test('Send bad url', async () => { const badurl = 'badurl'; return expect(articledown(badurl)).rejects.toThrowError(BAD_URL_ERROR(badurl)); }); test('Send null url', async () => { return expect(articledown(null)).rejects.toThrowError(BAD_ARG_ERROR); }); test('Send object as url', async () => { return expect(articledown({})).rejects.toThrowError(BAD_ARG_ERROR); }); test('Send empty url', async () => { return expect(articledown('')).rejects.toThrowError(BAD_ARG_ERROR); });
import React from 'react'; const Main = (props) => { return <main>{props.children}</main>; }; export { Main };
'use strict'; exports.register = function(socket) { socket.on('change:issue', function(issue) { socket.broadcast.emit('issue:changed', { issue: issue }); }); };
"use strict"; var Page = (function () { var Page = function (options) { var options = options || {}; this.Name = "Page"; this.Type = "dxDataGrid"; this.id = options.id || (this.Name + (new Date()).getTime()); this.Component = null; this.permit = getACL(this.Name) || { add: false, edit: false, delete: false, build: false }; this.Data = new NCStore({ url: 'api/core/page', key: "id" ,permit: this.permit}); this.Key = 0; this.Init = function () { var that = this; var $find = $(that.id); if(!$find.length){ var scriptTag = document.scripts[document.scripts.length - 1]; var parentTag = scriptTag.parentNode; $find = $("<div id='"+that.Id+"'>").appendTo(parentTag); } var appStore = new NCData({url:'api/core/app',key:'id',callback:function(a){ that.Component.columnOption('app_id', 'lookup.dataSource', a); }}); var layoutStore = new NCData({url:'api/core/layout',key:'id',callback:function(a){ that.Component.columnOption('layout_id', 'lookup.dataSource', a); }}); $find.dxDataGrid({ dataSource: that.Data.Store(), columns: [{ dataField: "id", allowEditing: false, formItem: { visible: false } }, { dataField: "page_name", caption: "Page Name", sortOrder: "asc", validationRules: [{ type: "required" }], }, { dataField: "page_title", caption: "Page Title", validationRules: [{type: "required"}], }, { dataField: "app_id", caption:"App", lookup: { dataSource: appStore.data, valueExpr: "id", displayExpr: "app_name" }, groupIndex:0, }, { dataField: "layout_id", caption:"Master layout", lookup: { dataSource: layoutStore.data, valueExpr: "id", displayExpr: "name" } }], editing: { mode: "form", allowUpdating: that.permit.edit || false, allowDeleting: that.permit.delete || false, allowAdding: that.permit.add || false, }, selection: { mode: "single" }, onSelectionChanged: function (selectedItems) { var data = selectedItems.selectedRowsData[0]; if (data) { that.Key = data.id; } }, onToolbarPreparing: function (e) { var dataGrid = e.component; e.toolbarOptions.items.unshift({ location: "after", widget: "dxButton", options: { icon: "toolbox", visible: that.permit.build || false, onClick: function () { if (that.Key) window.location = "/system/page/config/" + that.Key; } } }); }, onEditingStart: function (e) { that.Key = e.data.id; }, searchPanel: { visible: true, placeholder: "Search..." }, headerFilter: { visible: true }, showRowLines: true, showBorders: true, stateStoring: { enabled: true, type: "localStorage", storageKey: that.Name, }, paging: { pageSize: 50 }, pager: { showPageSizeSelector: true, allowedPageSizes: [10, 20, 50, 100, 200], showInfo: true }, grouping: { autoExpandAll: true, }, groupPanel: { visible: true }, }); that.Component = $find.dxDataGrid("instance"); }; this.Init(); } return Page; })(); if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') module.exports = Page; else window.Page = Page;
! function() { "use strict"; function e(e, t) { if (e) { if (t.element_.classList.contains(t.CssClasses_.MDL_JS_RIPPLE_EFFECT)) { var s = document.createElement("span"); s.classList.add(t.CssClasses_.MDL_RIPPLE_CONTAINER), s.classList.add(t.CssClasses_.MDL_JS_RIPPLE_EFFECT); var i = document.createElement("span"); i.classList.add(t.CssClasses_.MDL_RIPPLE), s.appendChild(i), e.appendChild(s) } e.addEventListener("click", function(s) { if ("#" === e.getAttribute("href").charAt(0)) { s.preventDefault(); var i = e.href.split("#")[1], n = t.element_.querySelector("#" + i); t.resetTabState_(), t.resetPanelState_(), e.classList.add(t.CssClasses_.ACTIVE_CLASS), n.classList.add(t.CssClasses_.ACTIVE_CLASS) } }) } } function t(e, t, s, i) { function n() { var n = e.href.split("#")[1], a = i.content_.querySelector("#" + n); i.resetTabState_(t), i.resetPanelState_(s), e.classList.add(i.CssClasses_.IS_ACTIVE), a.classList.add(i.CssClasses_.IS_ACTIVE) } if (i.tabBar_.classList.contains(i.CssClasses_.JS_RIPPLE_EFFECT)) { var a = document.createElement("span"); a.classList.add(i.CssClasses_.RIPPLE_CONTAINER), a.classList.add(i.CssClasses_.JS_RIPPLE_EFFECT); var l = document.createElement("span"); l.classList.add(i.CssClasses_.RIPPLE), a.appendChild(l), e.appendChild(a) } i.tabBar_.classList.contains(i.CssClasses_.TAB_MANUAL_SWITCH) || e.addEventListener("click", function(t) { "#" === e.getAttribute("href").charAt(0) && (t.preventDefault(), n()) }), e.show = n } var s = { upgradeDom: function(e, t) {}, upgradeElement: function(e, t) {}, upgradeElements: function(e) {}, upgradeAllRegistered: function() {}, registerUpgradedCallback: function(e, t) {}, register: function(e) {}, downgradeElements: function(e) {} }; s = function() { function e(e, t) { for (var s = 0; s < c.length; s++) if (c[s].className === e) return "undefined" != typeof t && (c[s] = t), c[s]; return !1 } function t(e) { var t = e.getAttribute("data-upgraded"); return null === t ? [""] : t.split(",") } function s(e, s) { var i = t(e); return i.indexOf(s) !== -1 } function i(e, t, s) { if ("CustomEvent" in window && "function" == typeof window.CustomEvent) return new CustomEvent(e, { bubbles: t, cancelable: s }); var i = document.createEvent("Events"); return i.initEvent(e, t, s), i } function n(t, s) { if ("undefined" == typeof t && "undefined" == typeof s) for (var i = 0; i < c.length; i++) n(c[i].className, c[i].cssClass); else { var l = t; if ("undefined" == typeof s) { var o = e(l); o && (s = o.cssClass) } for (var r = document.querySelectorAll("." + s), _ = 0; _ < r.length; _++) a(r[_], l) } } function a(n, a) { if (!("object" == typeof n && n instanceof Element)) throw new Error("Invalid argument provided to upgrade MDL element."); var l = i("mdl-componentupgrading", !0, !0); if (n.dispatchEvent(l), !l.defaultPrevented) { var o = t(n), r = []; if (a) s(n, a) || r.push(e(a)); else { var _ = n.classList; c.forEach(function(e) { _.contains(e.cssClass) && r.indexOf(e) === -1 && !s(n, e.className) && r.push(e) }) } for (var d, h = 0, u = r.length; h < u; h++) { if (d = r[h], !d) throw new Error("Unable to find a registered component for the given class."); o.push(d.className), n.setAttribute("data-upgraded", o.join(",")); var E = new d.classConstructor(n); E[C] = d, p.push(E); for (var m = 0, L = d.callbacks.length; m < L; m++) d.callbacks[m](n); d.widget && (n[d.className] = E); var I = i("mdl-componentupgraded", !0, !1); n.dispatchEvent(I) } } } function l(e) { Array.isArray(e) || (e = e instanceof Element ? [e] : Array.prototype.slice.call(e)); for (var t, s = 0, i = e.length; s < i; s++) t = e[s], t instanceof HTMLElement && (a(t), t.children.length > 0 && l(t.children)) } function o(t) { var s = "undefined" == typeof t.widget && "undefined" == typeof t.widget, i = !0; s || (i = t.widget || t.widget); var n = { classConstructor: t.constructor || t.constructor, className: t.classAsString || t.classAsString, cssClass: t.cssClass || t.cssClass, widget: i, callbacks: [] }; if (c.forEach(function(e) { if (e.cssClass === n.cssClass) throw new Error("The provided cssClass has already been registered: " + e.cssClass); if (e.className === n.className) throw new Error("The provided className has already been registered") }), t.constructor.prototype.hasOwnProperty(C)) throw new Error("MDL component classes must not have " + C + " defined as a property."); var a = e(t.classAsString, n); a || c.push(n) } function r(t, s) { var i = e(t); i && i.callbacks.push(s) } function _() { for (var e = 0; e < c.length; e++) n(c[e].className) } function d(e) { if (e) { var t = p.indexOf(e); p.splice(t, 1); var s = e.element_.getAttribute("data-upgraded").split(","), n = s.indexOf(e[C].classAsString); s.splice(n, 1), e.element_.setAttribute("data-upgraded", s.join(",")); var a = i("mdl-componentdowngraded", !0, !1); e.element_.dispatchEvent(a) } } function h(e) { var t = function(e) { p.filter(function(t) { return t.element_ === e }).forEach(d) }; if (e instanceof Array || e instanceof NodeList) for (var s = 0; s < e.length; s++) t(e[s]); else { if (!(e instanceof Node)) throw new Error("Invalid argument provided to downgrade MDL nodes."); t(e) } } var c = [], p = [], C = "mdlComponentConfigInternal_"; return { upgradeDom: n, upgradeElement: a, upgradeElements: l, upgradeAllRegistered: _, registerUpgradedCallback: r, register: o, downgradeElements: h } }(), s.ComponentConfigPublic, s.ComponentConfig, s.Component, s.upgradeDom = s.upgradeDom, s.upgradeElement = s.upgradeElement, s.upgradeElements = s.upgradeElements, s.upgradeAllRegistered = s.upgradeAllRegistered, s.registerUpgradedCallback = s.registerUpgradedCallback, s.register = s.register, s.downgradeElements = s.downgradeElements, window.componentHandler = s, window.componentHandler = s, window.addEventListener("load", function() { "classList" in document.createElement("div") && "querySelector" in document && "addEventListener" in window && Array.prototype.forEach ? (document.documentElement.classList.add("mdl-js"), s.upgradeAllRegistered()) : (s.upgradeElement = function() {}, s.register = function() {}) }), Date.now || (Date.now = function() { return (new Date).getTime() }, Date.now = Date.now); for (var i = ["webkit", "moz"], n = 0; n < i.length && !window.requestAnimationFrame; ++n) { var a = i[n]; window.requestAnimationFrame = window[a + "RequestAnimationFrame"], window.cancelAnimationFrame = window[a + "CancelAnimationFrame"] || window[a + "CancelRequestAnimationFrame"], window.requestAnimationFrame = window.requestAnimationFrame, window.cancelAnimationFrame = window.cancelAnimationFrame } if (/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent) || !window.requestAnimationFrame || !window.cancelAnimationFrame) { var l = 0; window.requestAnimationFrame = function(e) { var t = Date.now(), s = Math.max(l + 16, t); return setTimeout(function() { e(l = s) }, s - t) }, window.cancelAnimationFrame = clearTimeout, window.requestAnimationFrame = window.requestAnimationFrame, window.cancelAnimationFrame = window.cancelAnimationFrame } var o = function(e) { this.element_ = e, this.init() }; window.MaterialButton = o, o.prototype.Constant_ = {}, o.prototype.CssClasses_ = { RIPPLE_EFFECT: "mdl-js-ripple-effect", RIPPLE_CONTAINER: "mdl-button__ripple-container", RIPPLE: "mdl-ripple" }, o.prototype.blurHandler_ = function(e) { e && this.element_.blur() }, o.prototype.disable = function() { this.element_.disabled = !0 }, o.prototype.disable = o.prototype.disable, o.prototype.enable = function() { this.element_.disabled = !1 }, o.prototype.enable = o.prototype.enable, o.prototype.init = function() { if (this.element_) { if (this.element_.classList.contains(this.CssClasses_.RIPPLE_EFFECT)) { var e = document.createElement("span"); e.classList.add(this.CssClasses_.RIPPLE_CONTAINER), this.rippleElement_ = document.createElement("span"), this.rippleElement_.classList.add(this.CssClasses_.RIPPLE), e.appendChild(this.rippleElement_), this.boundRippleBlurHandler = this.blurHandler_.bind(this), this.rippleElement_.addEventListener("mouseup", this.boundRippleBlurHandler), this.element_.appendChild(e) } this.boundButtonBlurHandler = this.blurHandler_.bind(this), this.element_.addEventListener("mouseup", this.boundButtonBlurHandler), this.element_.addEventListener("mouseleave", this.boundButtonBlurHandler) } }, s.register({ constructor: o, classAsString: "MaterialButton", cssClass: "mdl-js-button", widget: !0 }); var r = function(e) { this.element_ = e, this.init() }; window.MaterialCheckbox = r, r.prototype.Constant_ = { TINY_TIMEOUT: .001 }, r.prototype.CssClasses_ = { INPUT: "mdl-checkbox__input", BOX_OUTLINE: "mdl-checkbox__box-outline", FOCUS_HELPER: "mdl-checkbox__focus-helper", TICK_OUTLINE: "mdl-checkbox__tick-outline", RIPPLE_EFFECT: "mdl-js-ripple-effect", RIPPLE_IGNORE_EVENTS: "mdl-js-ripple-effect--ignore-events", RIPPLE_CONTAINER: "mdl-checkbox__ripple-container", RIPPLE_CENTER: "mdl-ripple--center", RIPPLE: "mdl-ripple", IS_FOCUSED: "is-focused", IS_DISABLED: "is-disabled", IS_CHECKED: "is-checked", IS_UPGRADED: "is-upgraded" }, r.prototype.onChange_ = function(e) { this.updateClasses_() }, r.prototype.onFocus_ = function(e) { this.element_.classList.add(this.CssClasses_.IS_FOCUSED) }, r.prototype.onBlur_ = function(e) { this.element_.classList.remove(this.CssClasses_.IS_FOCUSED) }, r.prototype.onMouseUp_ = function(e) { this.blur_() }, r.prototype.updateClasses_ = function() { this.checkDisabled(), this.checkToggleState() }, r.prototype.blur_ = function() { window.setTimeout(function() { this.inputElement_.blur() }.bind(this), this.Constant_.TINY_TIMEOUT) }, r.prototype.checkToggleState = function() { this.inputElement_.checked ? this.element_.classList.add(this.CssClasses_.IS_CHECKED) : this.element_.classList.remove(this.CssClasses_.IS_CHECKED) }, r.prototype.checkToggleState = r.prototype.checkToggleState, r.prototype.checkDisabled = function() { this.inputElement_.disabled ? this.element_.classList.add(this.CssClasses_.IS_DISABLED) : this.element_.classList.remove(this.CssClasses_.IS_DISABLED) }, r.prototype.checkDisabled = r.prototype.checkDisabled, r.prototype.disable = function() { this.inputElement_.disabled = !0, this.updateClasses_() }, r.prototype.disable = r.prototype.disable, r.prototype.enable = function() { this.inputElement_.disabled = !1, this.updateClasses_() }, r.prototype.enable = r.prototype.enable, r.prototype.check = function() { this.inputElement_.checked = !0, this.updateClasses_() }, r.prototype.check = r.prototype.check, r.prototype.uncheck = function() { this.inputElement_.checked = !1, this.updateClasses_() }, r.prototype.uncheck = r.prototype.uncheck, r.prototype.init = function() { if (this.element_) { this.inputElement_ = this.element_.querySelector("." + this.CssClasses_.INPUT); var e = document.createElement("span"); e.classList.add(this.CssClasses_.BOX_OUTLINE); var t = document.createElement("span"); t.classList.add(this.CssClasses_.FOCUS_HELPER); var s = document.createElement("span"); if (s.classList.add(this.CssClasses_.TICK_OUTLINE), e.appendChild(s), this.element_.appendChild(t), this.element_.appendChild(e), this.element_.classList.contains(this.CssClasses_.RIPPLE_EFFECT)) { this.element_.classList.add(this.CssClasses_.RIPPLE_IGNORE_EVENTS), this.rippleContainerElement_ = document.createElement("span"), this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_CONTAINER), this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_EFFECT), this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_CENTER), this.boundRippleMouseUp = this.onMouseUp_.bind(this), this.rippleContainerElement_.addEventListener("mouseup", this.boundRippleMouseUp); var i = document.createElement("span"); i.classList.add(this.CssClasses_.RIPPLE), this.rippleContainerElement_.appendChild(i), this.element_.appendChild(this.rippleContainerElement_) } this.boundInputOnChange = this.onChange_.bind(this), this.boundInputOnFocus = this.onFocus_.bind(this), this.boundInputOnBlur = this.onBlur_.bind(this), this.boundElementMouseUp = this.onMouseUp_.bind(this), this.inputElement_.addEventListener("change", this.boundInputOnChange), this.inputElement_.addEventListener("focus", this.boundInputOnFocus), this.inputElement_.addEventListener("blur", this.boundInputOnBlur), this.element_.addEventListener("mouseup", this.boundElementMouseUp), this.updateClasses_(), this.element_.classList.add(this.CssClasses_.IS_UPGRADED) } }, s.register({ constructor: r, classAsString: "MaterialCheckbox", cssClass: "mdl-js-checkbox", widget: !0 }); var _ = function(e) { this.element_ = e, this.init() }; window.MaterialIconToggle = _, _.prototype.Constant_ = { TINY_TIMEOUT: .001 }, _.prototype.CssClasses_ = { INPUT: "mdl-icon-toggle__input", JS_RIPPLE_EFFECT: "mdl-js-ripple-effect", RIPPLE_IGNORE_EVENTS: "mdl-js-ripple-effect--ignore-events", RIPPLE_CONTAINER: "mdl-icon-toggle__ripple-container", RIPPLE_CENTER: "mdl-ripple--center", RIPPLE: "mdl-ripple", IS_FOCUSED: "is-focused", IS_DISABLED: "is-disabled", IS_CHECKED: "is-checked" }, _.prototype.onChange_ = function(e) { this.updateClasses_() }, _.prototype.onFocus_ = function(e) { this.element_.classList.add(this.CssClasses_.IS_FOCUSED) }, _.prototype.onBlur_ = function(e) { this.element_.classList.remove(this.CssClasses_.IS_FOCUSED) }, _.prototype.onMouseUp_ = function(e) { this.blur_() }, _.prototype.updateClasses_ = function() { this.checkDisabled(), this.checkToggleState() }, _.prototype.blur_ = function() { window.setTimeout(function() { this.inputElement_.blur() }.bind(this), this.Constant_.TINY_TIMEOUT) }, _.prototype.checkToggleState = function() { this.inputElement_.checked ? this.element_.classList.add(this.CssClasses_.IS_CHECKED) : this.element_.classList.remove(this.CssClasses_.IS_CHECKED) }, _.prototype.checkToggleState = _.prototype.checkToggleState, _.prototype.checkDisabled = function() { this.inputElement_.disabled ? this.element_.classList.add(this.CssClasses_.IS_DISABLED) : this.element_.classList.remove(this.CssClasses_.IS_DISABLED) }, _.prototype.checkDisabled = _.prototype.checkDisabled, _.prototype.disable = function() { this.inputElement_.disabled = !0, this.updateClasses_() }, _.prototype.disable = _.prototype.disable, _.prototype.enable = function() { this.inputElement_.disabled = !1, this.updateClasses_() }, _.prototype.enable = _.prototype.enable, _.prototype.check = function() { this.inputElement_.checked = !0, this.updateClasses_() }, _.prototype.check = _.prototype.check, _.prototype.uncheck = function() { this.inputElement_.checked = !1, this.updateClasses_() }, _.prototype.uncheck = _.prototype.uncheck, _.prototype.init = function() { if (this.element_) { if (this.inputElement_ = this.element_.querySelector("." + this.CssClasses_.INPUT), this.element_.classList.contains(this.CssClasses_.JS_RIPPLE_EFFECT)) { this.element_.classList.add(this.CssClasses_.RIPPLE_IGNORE_EVENTS), this.rippleContainerElement_ = document.createElement("span"), this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_CONTAINER), this.rippleContainerElement_.classList.add(this.CssClasses_.JS_RIPPLE_EFFECT), this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_CENTER), this.boundRippleMouseUp = this.onMouseUp_.bind(this), this.rippleContainerElement_.addEventListener("mouseup", this.boundRippleMouseUp); var e = document.createElement("span"); e.classList.add(this.CssClasses_.RIPPLE), this.rippleContainerElement_.appendChild(e), this.element_.appendChild(this.rippleContainerElement_) } this.boundInputOnChange = this.onChange_.bind(this), this.boundInputOnFocus = this.onFocus_.bind(this), this.boundInputOnBlur = this.onBlur_.bind(this), this.boundElementOnMouseUp = this.onMouseUp_.bind(this), this.inputElement_.addEventListener("change", this.boundInputOnChange), this.inputElement_.addEventListener("focus", this.boundInputOnFocus), this.inputElement_.addEventListener("blur", this.boundInputOnBlur), this.element_.addEventListener("mouseup", this.boundElementOnMouseUp), this.updateClasses_(), this.element_.classList.add("is-upgraded") } }, s.register({ constructor: _, classAsString: "MaterialIconToggle", cssClass: "mdl-js-icon-toggle", widget: !0 }); var d = function(e) { this.element_ = e, this.init() }; window.MaterialMenu = d, d.prototype.Constant_ = { TRANSITION_DURATION_SECONDS: .3, TRANSITION_DURATION_FRACTION: .8, CLOSE_TIMEOUT: 150 }, d.prototype.Keycodes_ = { ENTER: 13, ESCAPE: 27, SPACE: 32, UP_ARROW: 38, DOWN_ARROW: 40 }, d.prototype.CssClasses_ = { CONTAINER: "mdl-menu__container", OUTLINE: "mdl-menu__outline", ITEM: "mdl-menu__item", ITEM_RIPPLE_CONTAINER: "mdl-menu__item-ripple-container", RIPPLE_EFFECT: "mdl-js-ripple-effect", RIPPLE_IGNORE_EVENTS: "mdl-js-ripple-effect--ignore-events", RIPPLE: "mdl-ripple", IS_UPGRADED: "is-upgraded", IS_VISIBLE: "is-visible", IS_ANIMATING: "is-animating", BOTTOM_LEFT: "mdl-menu--bottom-left", BOTTOM_RIGHT: "mdl-menu--bottom-right", TOP_LEFT: "mdl-menu--top-left", TOP_RIGHT: "mdl-menu--top-right", UNALIGNED: "mdl-menu--unaligned" }, d.prototype.init = function() { if (this.element_) { var e = document.createElement("div"); e.classList.add(this.CssClasses_.CONTAINER), this.element_.parentElement.insertBefore(e, this.element_), this.element_.parentElement.removeChild(this.element_), e.appendChild(this.element_), this.container_ = e; var t = document.createElement("div"); t.classList.add(this.CssClasses_.OUTLINE), this.outline_ = t, e.insertBefore(t, this.element_); var s = this.element_.getAttribute("for") || this.element_.getAttribute("data-mdl-for"), i = null; s && (i = document.getElementById(s), i && (this.forElement_ = i, i.addEventListener("click", this.handleForClick_.bind(this)), i.addEventListener("keydown", this.handleForKeyboardEvent_.bind(this)))); var n = this.element_.querySelectorAll("." + this.CssClasses_.ITEM); this.boundItemKeydown_ = this.handleItemKeyboardEvent_.bind(this), this.boundItemClick_ = this.handleItemClick_.bind(this); for (var a = 0; a < n.length; a++) n[a].addEventListener("click", this.boundItemClick_), n[a].tabIndex = "-1", n[a].addEventListener("keydown", this.boundItemKeydown_); if (this.element_.classList.contains(this.CssClasses_.RIPPLE_EFFECT)) for (this.element_.classList.add(this.CssClasses_.RIPPLE_IGNORE_EVENTS), a = 0; a < n.length; a++) { var l = n[a], o = document.createElement("span"); o.classList.add(this.CssClasses_.ITEM_RIPPLE_CONTAINER); var r = document.createElement("span"); r.classList.add(this.CssClasses_.RIPPLE), o.appendChild(r), l.appendChild(o), l.classList.add(this.CssClasses_.RIPPLE_EFFECT) } this.element_.classList.contains(this.CssClasses_.BOTTOM_LEFT) && this.outline_.classList.add(this.CssClasses_.BOTTOM_LEFT), this.element_.classList.contains(this.CssClasses_.BOTTOM_RIGHT) && this.outline_.classList.add(this.CssClasses_.BOTTOM_RIGHT), this.element_.classList.contains(this.CssClasses_.TOP_LEFT) && this.outline_.classList.add(this.CssClasses_.TOP_LEFT), this.element_.classList.contains(this.CssClasses_.TOP_RIGHT) && this.outline_.classList.add(this.CssClasses_.TOP_RIGHT), this.element_.classList.contains(this.CssClasses_.UNALIGNED) && this.outline_.classList.add(this.CssClasses_.UNALIGNED), e.classList.add(this.CssClasses_.IS_UPGRADED) } }, d.prototype.handleForClick_ = function(e) { if (this.element_ && this.forElement_) { var t = this.forElement_.getBoundingClientRect(), s = this.forElement_.parentElement.getBoundingClientRect(); this.element_.classList.contains(this.CssClasses_.UNALIGNED) || (this.element_.classList.contains(this.CssClasses_.BOTTOM_RIGHT) ? (this.container_.style.right = s.right - t.right + "px", this.container_.style.top = this.forElement_.offsetTop + this.forElement_.offsetHeight + "px") : this.element_.classList.contains(this.CssClasses_.TOP_LEFT) ? (this.container_.style.left = this.forElement_.offsetLeft + "px", this.container_.style.bottom = s.bottom - t.top + "px") : this.element_.classList.contains(this.CssClasses_.TOP_RIGHT) ? (this.container_.style.right = s.right - t.right + "px", this.container_.style.bottom = s.bottom - t.top + "px") : (this.container_.style.left = this.forElement_.offsetLeft + "px", this.container_.style.top = this.forElement_.offsetTop + this.forElement_.offsetHeight + "px")) } this.toggle(e) }, d.prototype.handleForKeyboardEvent_ = function(e) { if (this.element_ && this.container_ && this.forElement_) { var t = this.element_.querySelectorAll("." + this.CssClasses_.ITEM + ":not([disabled])"); t && t.length > 0 && this.container_.classList.contains(this.CssClasses_.IS_VISIBLE) && (e.keyCode === this.Keycodes_.UP_ARROW ? (e.preventDefault(), t[t.length - 1].focus()) : e.keyCode === this.Keycodes_.DOWN_ARROW && (e.preventDefault(), t[0].focus())) } }, d.prototype.handleItemKeyboardEvent_ = function(e) { if (this.element_ && this.container_) { var t = this.element_.querySelectorAll("." + this.CssClasses_.ITEM + ":not([disabled])"); if (t && t.length > 0 && this.container_.classList.contains(this.CssClasses_.IS_VISIBLE)) { var s = Array.prototype.slice.call(t).indexOf(e.target); if (e.keyCode === this.Keycodes_.UP_ARROW) e.preventDefault(), s > 0 ? t[s - 1].focus() : t[t.length - 1].focus(); else if (e.keyCode === this.Keycodes_.DOWN_ARROW) e.preventDefault(), t.length > s + 1 ? t[s + 1].focus() : t[0].focus(); else if (e.keyCode === this.Keycodes_.SPACE || e.keyCode === this.Keycodes_.ENTER) { e.preventDefault(); var i = new MouseEvent("mousedown"); e.target.dispatchEvent(i), i = new MouseEvent("mouseup"), e.target.dispatchEvent(i), e.target.click() } else e.keyCode === this.Keycodes_.ESCAPE && (e.preventDefault(), this.hide()) } } }, d.prototype.handleItemClick_ = function(e) { e.target.hasAttribute("disabled") ? e.stopPropagation() : (this.closing_ = !0, window.setTimeout(function(e) { this.hide(), this.closing_ = !1 }.bind(this), this.Constant_.CLOSE_TIMEOUT)) }, d.prototype.applyClip_ = function(e, t) { this.element_.classList.contains(this.CssClasses_.UNALIGNED) ? this.element_.style.clip = "" : this.element_.classList.contains(this.CssClasses_.BOTTOM_RIGHT) ? this.element_.style.clip = "rect(0 " + t + "px 0 " + t + "px)" : this.element_.classList.contains(this.CssClasses_.TOP_LEFT) ? this.element_.style.clip = "rect(" + e + "px 0 " + e + "px 0)" : this.element_.classList.contains(this.CssClasses_.TOP_RIGHT) ? this.element_.style.clip = "rect(" + e + "px " + t + "px " + e + "px " + t + "px)" : this.element_.style.clip = "" }, d.prototype.removeAnimationEndListener_ = function(e) { e.target.classList.remove(d.prototype.CssClasses_.IS_ANIMATING) }, d.prototype.addAnimationEndListener_ = function() { this.element_.addEventListener("transitionend", this.removeAnimationEndListener_), this.element_.addEventListener("webkitTransitionEnd", this.removeAnimationEndListener_) }, d.prototype.show = function(e) { if (this.element_ && this.container_ && this.outline_) { var t = this.element_.getBoundingClientRect().height, s = this.element_.getBoundingClientRect().width; this.container_.style.width = s + "px", this.container_.style.height = t + "px", this.outline_.style.width = s + "px", this.outline_.style.height = t + "px"; for (var i = this.Constant_.TRANSITION_DURATION_SECONDS * this.Constant_.TRANSITION_DURATION_FRACTION, n = this.element_.querySelectorAll("." + this.CssClasses_.ITEM), a = 0; a < n.length; a++) { var l = null; l = this.element_.classList.contains(this.CssClasses_.TOP_LEFT) || this.element_.classList.contains(this.CssClasses_.TOP_RIGHT) ? (t - n[a].offsetTop - n[a].offsetHeight) / t * i + "s" : n[a].offsetTop / t * i + "s", n[a].style.transitionDelay = l } this.applyClip_(t, s), window.requestAnimationFrame(function() { this.element_.classList.add(this.CssClasses_.IS_ANIMATING), this.element_.style.clip = "rect(0 " + s + "px " + t + "px 0)", this.container_.classList.add(this.CssClasses_.IS_VISIBLE) }.bind(this)), this.addAnimationEndListener_(); var o = function(t) { t === e || this.closing_ || t.target.parentNode === this.element_ || (document.removeEventListener("click", o), this.hide()) }.bind(this); document.addEventListener("click", o) } }, d.prototype.show = d.prototype.show, d.prototype.hide = function() { if (this.element_ && this.container_ && this.outline_) { for (var e = this.element_.querySelectorAll("." + this.CssClasses_.ITEM), t = 0; t < e.length; t++) e[t].style.removeProperty("transition-delay"); var s = this.element_.getBoundingClientRect(), i = s.height, n = s.width; this.element_.classList.add(this.CssClasses_.IS_ANIMATING), this.applyClip_(i, n), this.container_.classList.remove(this.CssClasses_.IS_VISIBLE), this.addAnimationEndListener_() } }, d.prototype.hide = d.prototype.hide, d.prototype.toggle = function(e) { this.container_.classList.contains(this.CssClasses_.IS_VISIBLE) ? this.hide() : this.show(e) }, d.prototype.toggle = d.prototype.toggle, s.register({ constructor: d, classAsString: "MaterialMenu", cssClass: "mdl-js-menu", widget: !0 }); var h = function(e) { this.element_ = e, this.init() }; window.MaterialProgress = h, h.prototype.Constant_ = {}, h.prototype.CssClasses_ = { INDETERMINATE_CLASS: "mdl-progress__indeterminate" }, h.prototype.setProgress = function(e) { this.element_.classList.contains(this.CssClasses_.INDETERMINATE_CLASS) || (this.progressbar_.style.width = e + "%") }, h.prototype.setProgress = h.prototype.setProgress, h.prototype.setBuffer = function(e) { this.bufferbar_.style.width = e + "%", this.auxbar_.style.width = 100 - e + "%" }, h.prototype.setBuffer = h.prototype.setBuffer, h.prototype.init = function() { if (this.element_) { var e = document.createElement("div"); e.className = "progressbar bar bar1", this.element_.appendChild(e), this.progressbar_ = e, e = document.createElement("div"), e.className = "bufferbar bar bar2", this.element_.appendChild(e), this.bufferbar_ = e, e = document.createElement("div"), e.className = "auxbar bar bar3", this.element_.appendChild(e), this.auxbar_ = e, this.progressbar_.style.width = "0%", this.bufferbar_.style.width = "100%", this.auxbar_.style.width = "0%", this.element_.classList.add("is-upgraded") } }, s.register({ constructor: h, classAsString: "MaterialProgress", cssClass: "mdl-js-progress", widget: !0 }); var c = function(e) { this.element_ = e, this.init() }; window.MaterialRadio = c, c.prototype.Constant_ = { TINY_TIMEOUT: .001 }, c.prototype.CssClasses_ = { IS_FOCUSED: "is-focused", IS_DISABLED: "is-disabled", IS_CHECKED: "is-checked", IS_UPGRADED: "is-upgraded", JS_RADIO: "mdl-js-radio", RADIO_BTN: "mdl-radio__button", RADIO_OUTER_CIRCLE: "mdl-radio__outer-circle", RADIO_INNER_CIRCLE: "mdl-radio__inner-circle", RIPPLE_EFFECT: "mdl-js-ripple-effect", RIPPLE_IGNORE_EVENTS: "mdl-js-ripple-effect--ignore-events", RIPPLE_CONTAINER: "mdl-radio__ripple-container", RIPPLE_CENTER: "mdl-ripple--center", RIPPLE: "mdl-ripple" }, c.prototype.onChange_ = function(e) { for (var t = document.getElementsByClassName(this.CssClasses_.JS_RADIO), s = 0; s < t.length; s++) { var i = t[s].querySelector("." + this.CssClasses_.RADIO_BTN); i.getAttribute("name") === this.btnElement_.getAttribute("name") && "undefined" != typeof t[s].MaterialRadio && t[s].MaterialRadio.updateClasses_() } }, c.prototype.onFocus_ = function(e) { this.element_.classList.add(this.CssClasses_.IS_FOCUSED) }, c.prototype.onBlur_ = function(e) { this.element_.classList.remove(this.CssClasses_.IS_FOCUSED) }, c.prototype.onMouseup_ = function(e) { this.blur_() }, c.prototype.updateClasses_ = function() { this.checkDisabled(), this.checkToggleState() }, c.prototype.blur_ = function() { window.setTimeout(function() { this.btnElement_.blur() }.bind(this), this.Constant_.TINY_TIMEOUT) }, c.prototype.checkDisabled = function() { this.btnElement_.disabled ? this.element_.classList.add(this.CssClasses_.IS_DISABLED) : this.element_.classList.remove(this.CssClasses_.IS_DISABLED) }, c.prototype.checkDisabled = c.prototype.checkDisabled, c.prototype.checkToggleState = function() { this.btnElement_.checked ? this.element_.classList.add(this.CssClasses_.IS_CHECKED) : this.element_.classList.remove(this.CssClasses_.IS_CHECKED) }, c.prototype.checkToggleState = c.prototype.checkToggleState, c.prototype.disable = function() { this.btnElement_.disabled = !0, this.updateClasses_() }, c.prototype.disable = c.prototype.disable, c.prototype.enable = function() { this.btnElement_.disabled = !1, this.updateClasses_() }, c.prototype.enable = c.prototype.enable, c.prototype.check = function() { this.btnElement_.checked = !0, this.onChange_(null) }, c.prototype.check = c.prototype.check, c.prototype.uncheck = function() { this.btnElement_.checked = !1, this.onChange_(null) }, c.prototype.uncheck = c.prototype.uncheck, c.prototype.init = function() { if (this.element_) { this.btnElement_ = this.element_.querySelector("." + this.CssClasses_.RADIO_BTN), this.boundChangeHandler_ = this.onChange_.bind(this), this.boundFocusHandler_ = this.onChange_.bind(this), this.boundBlurHandler_ = this.onBlur_.bind(this), this.boundMouseUpHandler_ = this.onMouseup_.bind(this); var e = document.createElement("span"); e.classList.add(this.CssClasses_.RADIO_OUTER_CIRCLE); var t = document.createElement("span"); t.classList.add(this.CssClasses_.RADIO_INNER_CIRCLE), this.element_.appendChild(e), this.element_.appendChild(t); var s; if (this.element_.classList.contains(this.CssClasses_.RIPPLE_EFFECT)) { this.element_.classList.add(this.CssClasses_.RIPPLE_IGNORE_EVENTS), s = document.createElement("span"), s.classList.add(this.CssClasses_.RIPPLE_CONTAINER), s.classList.add(this.CssClasses_.RIPPLE_EFFECT), s.classList.add(this.CssClasses_.RIPPLE_CENTER), s.addEventListener("mouseup", this.boundMouseUpHandler_); var i = document.createElement("span"); i.classList.add(this.CssClasses_.RIPPLE), s.appendChild(i), this.element_.appendChild(s) } this.btnElement_.addEventListener("change", this.boundChangeHandler_), this.btnElement_.addEventListener("focus", this.boundFocusHandler_), this.btnElement_.addEventListener("blur", this.boundBlurHandler_), this.element_.addEventListener("mouseup", this.boundMouseUpHandler_), this.updateClasses_(), this.element_.classList.add(this.CssClasses_.IS_UPGRADED) } }, s.register({ constructor: c, classAsString: "MaterialRadio", cssClass: "mdl-js-radio", widget: !0 }); var p = function(e) { this.element_ = e, this.isIE_ = window.navigator.msPointerEnabled, this.init() }; window.MaterialSlider = p, p.prototype.Constant_ = {}, p.prototype.CssClasses_ = { IE_CONTAINER: "mdl-slider__ie-container", SLIDER_CONTAINER: "mdl-slider__container", BACKGROUND_FLEX: "mdl-slider__background-flex", BACKGROUND_LOWER: "mdl-slider__background-lower", BACKGROUND_UPPER: "mdl-slider__background-upper", IS_LOWEST_VALUE: "is-lowest-value", IS_UPGRADED: "is-upgraded" }, p.prototype.onInput_ = function(e) { this.updateValueStyles_() }, p.prototype.onChange_ = function(e) { this.updateValueStyles_() }, p.prototype.onMouseUp_ = function(e) { e.target.blur() }, p.prototype.onContainerMouseDown_ = function(e) { if (e.target === this.element_.parentElement) { e.preventDefault(); var t = new MouseEvent("mousedown", { target: e.target, buttons: e.buttons, clientX: e.clientX, clientY: this.element_.getBoundingClientRect().y }); this.element_.dispatchEvent(t) } }, p.prototype.updateValueStyles_ = function() { var e = (this.element_.value - this.element_.min) / (this.element_.max - this.element_.min); 0 === e ? this.element_.classList.add(this.CssClasses_.IS_LOWEST_VALUE) : this.element_.classList.remove(this.CssClasses_.IS_LOWEST_VALUE), this.isIE_ || (this.backgroundLower_.style.flex = e, this.backgroundLower_.style.webkitFlex = e, this.backgroundUpper_.style.flex = 1 - e, this.backgroundUpper_.style.webkitFlex = 1 - e) }, p.prototype.disable = function() { this.element_.disabled = !0 }, p.prototype.disable = p.prototype.disable, p.prototype.enable = function() { this.element_.disabled = !1 }, p.prototype.enable = p.prototype.enable, p.prototype.change = function(e) { "undefined" != typeof e && (this.element_.value = e), this.updateValueStyles_() }, p.prototype.change = p.prototype.change, p.prototype.init = function() { if (this.element_) { if (this.isIE_) { var e = document.createElement("div"); e.classList.add(this.CssClasses_.IE_CONTAINER), this.element_.parentElement.insertBefore(e, this.element_), this.element_.parentElement.removeChild(this.element_), e.appendChild(this.element_) } else { var t = document.createElement("div"); t.classList.add(this.CssClasses_.SLIDER_CONTAINER), this.element_.parentElement.insertBefore(t, this.element_), this.element_.parentElement.removeChild(this.element_), t.appendChild(this.element_); var s = document.createElement("div"); s.classList.add(this.CssClasses_.BACKGROUND_FLEX), t.appendChild(s), this.backgroundLower_ = document.createElement("div"), this.backgroundLower_.classList.add(this.CssClasses_.BACKGROUND_LOWER), s.appendChild(this.backgroundLower_), this.backgroundUpper_ = document.createElement("div"), this.backgroundUpper_.classList.add(this.CssClasses_.BACKGROUND_UPPER), s.appendChild(this.backgroundUpper_) } this.boundInputHandler = this.onInput_.bind(this), this.boundChangeHandler = this.onChange_.bind(this), this.boundMouseUpHandler = this.onMouseUp_.bind(this), this.boundContainerMouseDownHandler = this.onContainerMouseDown_.bind(this), this.element_.addEventListener("input", this.boundInputHandler), this.element_.addEventListener("change", this.boundChangeHandler), this.element_.addEventListener("mouseup", this.boundMouseUpHandler), this.element_.parentElement.addEventListener("mousedown", this.boundContainerMouseDownHandler), this.updateValueStyles_(), this.element_.classList.add(this.CssClasses_.IS_UPGRADED) } }, s.register({ constructor: p, classAsString: "MaterialSlider", cssClass: "mdl-js-slider", widget: !0 }); var C = function(e) { if (this.element_ = e, this.textElement_ = this.element_.querySelector("." + this.cssClasses_.MESSAGE), this.actionElement_ = this.element_.querySelector("." + this.cssClasses_.ACTION), !this.textElement_) throw new Error("There must be a message element for a snackbar."); if (!this.actionElement_) throw new Error("There must be an action element for a snackbar."); this.active = !1, this.actionHandler_ = void 0, this.message_ = void 0, this.actionText_ = void 0, this.queuedNotifications_ = [], this.setActionHidden_(!0) }; window.MaterialSnackbar = C, C.prototype.Constant_ = { ANIMATION_LENGTH: 250 }, C.prototype.cssClasses_ = { SNACKBAR: "mdl-snackbar", MESSAGE: "mdl-snackbar__text", ACTION: "mdl-snackbar__action", ACTIVE: "mdl-snackbar--active" }, C.prototype.displaySnackbar_ = function() { this.element_.setAttribute("aria-hidden", "true"),
//>>built define("dojox/gfx/svg", ["dojo/_base/lang", "dojo/_base/window", "dojo/dom","dojo/_base/declare", "dojo/_base/array", "dojo/dom-geometry", "dojo/_base/Color", "./_base", "./shape", "./path"], function(lang, win, dom, declare, arr, domGeom, Color, g, gs, pathLib){ /*===== dojox.gfx.svg = { // module: // dojox/gfx/svg // summary: // This the graphics rendering bridge for browsers compliant with W3C SVG1.0. // This is the preferred renderer to use for interactive and accessible graphics. }; pathLib.Path = dojox.gfx.path.Path; pathLib.TextPath = dojox.gfx.path.TextPath; svg.Shape = dojox.gfx.canvas.Shape; gs.Shape = dojox.gfx.shape.Shape; gs.Rect = dojox.gfx.shape.Rect; gs.Ellipse = dojox.gfx.shape.Ellipse; gs.Circle = dojox.gfx.shape.Circle; gs.Line = dojox.gfx.shape.Line; gs.PolyLine = dojox.gfx.shape.PolyLine; gs.Image = dojox.gfx.shape.Image; gs.Text = dojox.gfx.shape.Text; gs.Surface = dojox.gfx.shape.Surface; =====*/ var svg = g.svg = {}; svg.useSvgWeb = (typeof window.svgweb != "undefined"); // Need to detect iOS in order to workaround bug when // touching nodes with text var uagent = navigator.userAgent.toLowerCase(), safMobile = uagent.search('iphone') > -1 || uagent.search('ipad') > -1 || uagent.search('ipod') > -1; function _createElementNS(ns, nodeType){ // summary: // Internal helper to deal with creating elements that // are namespaced. Mainly to get SVG markup output // working on IE. if(win.doc.createElementNS){ return win.doc.createElementNS(ns,nodeType); }else{ return win.doc.createElement(nodeType); } } function _createTextNode(text){ if(svg.useSvgWeb){ return win.doc.createTextNode(text, true); }else{ return win.doc.createTextNode(text); } } function _createFragment(){ if(svg.useSvgWeb){ return win.doc.createDocumentFragment(true); }else{ return win.doc.createDocumentFragment(); } } svg.xmlns = { xlink: "http://www.w3.org/1999/xlink", svg: "http://www.w3.org/2000/svg" }; svg.getRef = function(name){ // summary: returns a DOM Node specified by the name argument or null // name: String: an SVG external reference if(!name || name == "none") return null; if(name.match(/^url\(#.+\)$/)){ return dom.byId(name.slice(5, -1)); // Node } // alternative representation of a reference if(name.match(/^#dojoUnique\d+$/)){ // we assume here that a reference was generated by dojox.gfx return dom.byId(name.slice(1)); // Node } return null; // Node }; svg.dasharray = { solid: "none", shortdash: [4, 1], shortdot: [1, 1], shortdashdot: [4, 1, 1, 1], shortdashdotdot: [4, 1, 1, 1, 1, 1], dot: [1, 3], dash: [4, 3], longdash: [8, 3], dashdot: [4, 3, 1, 3], longdashdot: [8, 3, 1, 3], longdashdotdot: [8, 3, 1, 3, 1, 3] }; declare("dojox.gfx.svg.Shape", gs.Shape, { // summary: SVG-specific implementation of dojox.gfx.Shape methods setFill: function(fill){ // summary: sets a fill object (SVG) // fill: Object: a fill object // (see dojox.gfx.defaultLinearGradient, // dojox.gfx.defaultRadialGradient, // dojox.gfx.defaultPattern, // or dojo.Color) if(!fill){ // don't fill this.fillStyle = null; this.rawNode.setAttribute("fill", "none"); this.rawNode.setAttribute("fill-opacity", 0); return this; } var f; // FIXME: slightly magical. We're using the outer scope's "f", but setting it later var setter = function(x){ // we assume that we're executing in the scope of the node to mutate this.setAttribute(x, f[x].toFixed(8)); }; if(typeof(fill) == "object" && "type" in fill){ // gradient switch(fill.type){ case "linear": f = g.makeParameters(g.defaultLinearGradient, fill); var gradient = this._setFillObject(f, "linearGradient"); arr.forEach(["x1", "y1", "x2", "y2"], setter, gradient); break; case "radial": f = g.makeParameters(g.defaultRadialGradient, fill); var grad = this._setFillObject(f, "radialGradient"); arr.forEach(["cx", "cy", "r"], setter, grad); break; case "pattern": f = g.makeParameters(g.defaultPattern, fill); var pattern = this._setFillObject(f, "pattern"); arr.forEach(["x", "y", "width", "height"], setter, pattern); break; } this.fillStyle = f; return this; } // color object f = g.normalizeColor(fill); this.fillStyle = f; this.rawNode.setAttribute("fill", f.toCss()); this.rawNode.setAttribute("fill-opacity", f.a); this.rawNode.setAttribute("fill-rule", "evenodd"); return this; // self }, setStroke: function(stroke){ // summary: // sets a stroke object (SVG) // stroke: Object // a stroke object (see dojox.gfx.defaultStroke) var rn = this.rawNode; if(!stroke){ // don't stroke this.strokeStyle = null; rn.setAttribute("stroke", "none"); rn.setAttribute("stroke-opacity", 0); return this; } // normalize the stroke if(typeof stroke == "string" || lang.isArray(stroke) || stroke instanceof Color){ stroke = { color: stroke }; } var s = this.strokeStyle = g.makeParameters(g.defaultStroke, stroke); s.color = g.normalizeColor(s.color); // generate attributes if(s){ rn.setAttribute("stroke", s.color.toCss()); rn.setAttribute("stroke-opacity", s.color.a); rn.setAttribute("stroke-width", s.width); rn.setAttribute("stroke-linecap", s.cap); if(typeof s.join == "number"){ rn.setAttribute("stroke-linejoin", "miter"); rn.setAttribute("stroke-miterlimit", s.join); }else{ rn.setAttribute("stroke-linejoin", s.join); } var da = s.style.toLowerCase(); if(da in svg.dasharray){ da = svg.dasharray[da]; } if(da instanceof Array){ da = lang._toArray(da); for(var i = 0; i < da.length; ++i){ da[i] *= s.width; } if(s.cap != "butt"){ for(var i = 0; i < da.length; i += 2){ da[i] -= s.width; if(da[i] < 1){ da[i] = 1; } } for(var i = 1; i < da.length; i += 2){ da[i] += s.width; } } da = da.join(","); } rn.setAttribute("stroke-dasharray", da); rn.setAttribute("dojoGfxStrokeStyle", s.style); } return this; // self }, _getParentSurface: function(){ var surface = this.parent; for(; surface && !(surface instanceof g.Surface); surface = surface.parent); return surface; }, _setFillObject: function(f, nodeType){ var svgns = svg.xmlns.svg; this.fillStyle = f; var surface = this._getParentSurface(), defs = surface.defNode, fill = this.rawNode.getAttribute("fill"), ref = svg.getRef(fill); if(ref){ fill = ref; if(fill.tagName.toLowerCase() != nodeType.toLowerCase()){ var id = fill.id; fill.parentNode.removeChild(fill); fill = _createElementNS(svgns, nodeType); fill.setAttribute("id", id); defs.appendChild(fill); }else{ while(fill.childNodes.length){ fill.removeChild(fill.lastChild); } } }else{ fill = _createElementNS(svgns, nodeType); fill.setAttribute("id", g._base._getUniqueId()); defs.appendChild(fill); } if(nodeType == "pattern"){ fill.setAttribute("patternUnits", "userSpaceOnUse"); var img = _createElementNS(svgns, "image"); img.setAttribute("x", 0); img.setAttribute("y", 0); img.setAttribute("width", f.width .toFixed(8)); img.setAttribute("height", f.height.toFixed(8)); img.setAttributeNS(svg.xmlns.xlink, "xlink:href", f.src); fill.appendChild(img); }else{ fill.setAttribute("gradientUnits", "userSpaceOnUse"); for(var i = 0; i < f.colors.length; ++i){ var c = f.colors[i], t = _createElementNS(svgns, "stop"), cc = c.color = g.normalizeColor(c.color); t.setAttribute("offset", c.offset.toFixed(8)); t.setAttribute("stop-color", cc.toCss()); t.setAttribute("stop-opacity", cc.a); fill.appendChild(t); } } this.rawNode.setAttribute("fill", "url(#" + fill.getAttribute("id") +")"); this.rawNode.removeAttribute("fill-opacity"); this.rawNode.setAttribute("fill-rule", "evenodd"); return fill; }, _applyTransform: function() { var matrix = this.matrix; if(matrix){ var tm = this.matrix; this.rawNode.setAttribute("transform", "matrix(" + tm.xx.toFixed(8) + "," + tm.yx.toFixed(8) + "," + tm.xy.toFixed(8) + "," + tm.yy.toFixed(8) + "," + tm.dx.toFixed(8) + "," + tm.dy.toFixed(8) + ")"); }else{ this.rawNode.removeAttribute("transform"); } return this; }, setRawNode: function(rawNode){ // summary: // assigns and clears the underlying node that will represent this // shape. Once set, transforms, gradients, etc, can be applied. // (no fill & stroke by default) var r = this.rawNode = rawNode; if(this.shape.type!="image"){ r.setAttribute("fill", "none"); } r.setAttribute("fill-opacity", 0); r.setAttribute("stroke", "none"); r.setAttribute("stroke-opacity", 0); r.setAttribute("stroke-width", 1); r.setAttribute("stroke-linecap", "butt"); r.setAttribute("stroke-linejoin", "miter"); r.setAttribute("stroke-miterlimit", 4); // Bind GFX object with SVG node for ease of retrieval - that is to // save code/performance to keep this association elsewhere r.__gfxObject__ = this.getUID(); }, setShape: function(newShape){ // summary: sets a shape object (SVG) // newShape: Object: a shape object // (see dojox.gfx.defaultPath, // dojox.gfx.defaultPolyline, // dojox.gfx.defaultRect, // dojox.gfx.defaultEllipse, // dojox.gfx.defaultCircle, // dojox.gfx.defaultLine, // or dojox.gfx.defaultImage) this.shape = g.makeParameters(this.shape, newShape); for(var i in this.shape){ if(i != "type"){ this.rawNode.setAttribute(i, this.shape[i]); } } this.bbox = null; return this; // self }, // move family _moveToFront: function(){ // summary: moves a shape to front of its parent's list of shapes (SVG) this.rawNode.parentNode.appendChild(this.rawNode); return this; // self }, _moveToBack: function(){ // summary: moves a shape to back of its parent's list of shapes (SVG) this.rawNode.parentNode.insertBefore(this.rawNode, this.rawNode.parentNode.firstChild); return this; // self } }); declare("dojox.gfx.svg.Group", svg.Shape, { // summary: a group shape (SVG), which can be used // to logically group shapes (e.g, to propagate matricies) constructor: function(){ gs.Container._init.call(this); }, setRawNode: function(rawNode){ // summary: sets a raw SVG node to be used by this shape // rawNode: Node: an SVG node this.rawNode = rawNode; // Bind GFX object with SVG node for ease of retrieval - that is to // save code/performance to keep this association elsewhere this.rawNode.__gfxObject__ = this.getUID(); } }); svg.Group.nodeType = "g"; declare("dojox.gfx.svg.Rect", [svg.Shape, gs.Rect], { // summary: a rectangle shape (SVG) setShape: function(newShape){ // summary: sets a rectangle shape object (SVG) // newShape: Object: a rectangle shape object this.shape = g.makeParameters(this.shape, newShape); this.bbox = null; for(var i in this.shape){ if(i != "type" && i != "r"){ this.rawNode.setAttribute(i, this.shape[i]); } } if(this.shape.r != null){ this.rawNode.setAttribute("ry", this.shape.r); this.rawNode.setAttribute("rx", this.shape.r); } return this; // self } }); svg.Rect.nodeType = "rect"; declare("dojox.gfx.svg.Ellipse", [svg.Shape, gs.Ellipse], {}); svg.Ellipse.nodeType = "ellipse"; declare("dojox.gfx.svg.Circle", [svg.Shape, gs.Circle], {}); svg.Circle.nodeType = "circle"; declare("dojox.gfx.svg.Line", [svg.Shape, gs.Line], {}); svg.Line.nodeType = "line"; declare("dojox.gfx.svg.Polyline", [svg.Shape, gs.Polyline], { // summary: a polyline/polygon shape (SVG) setShape: function(points, closed){ // summary: sets a polyline/polygon shape object (SVG) // points: Object: a polyline/polygon shape object if(points && points instanceof Array){ // branch // points: Array: an array of points this.shape = g.makeParameters(this.shape, { points: points }); if(closed && this.shape.points.length){ this.shape.points.push(this.shape.points[0]); } }else{ this.shape = g.makeParameters(this.shape, points); } this.bbox = null; this._normalizePoints(); var attr = [], p = this.shape.points; for(var i = 0; i < p.length; ++i){ attr.push(p[i].x.toFixed(8), p[i].y.toFixed(8)); } this.rawNode.setAttribute("points", attr.join(" ")); return this; // self } }); svg.Polyline.nodeType = "polyline"; declare("dojox.gfx.svg.Image", [svg.Shape, gs.Image], { // summary: an image (SVG) setShape: function(newShape){ // summary: sets an image shape object (SVG) // newShape: Object: an image shape object this.shape = g.makeParameters(this.shape, newShape); this.bbox = null; var rawNode = this.rawNode; for(var i in this.shape){ if(i != "type" && i != "src"){ rawNode.setAttribute(i, this.shape[i]); } } rawNode.setAttribute("preserveAspectRatio", "none"); rawNode.setAttributeNS(svg.xmlns.xlink, "xlink:href", this.shape.src); // Bind GFX object with SVG node for ease of retrieval - that is to // save code/performance to keep this association elsewhere rawNode.__gfxObject__ = this.getUID(); return this; // self } }); svg.Image.nodeType = "image"; declare("dojox.gfx.svg.Text", [svg.Shape, gs.Text], { // summary: an anchored text (SVG) setShape: function(newShape){ // summary: sets a text shape object (SVG) // newShape: Object: a text shape object this.shape = g.makeParameters(this.shape, newShape); this.bbox = null; var r = this.rawNode, s = this.shape; r.setAttribute("x", s.x); r.setAttribute("y", s.y); r.setAttribute("text-anchor", s.align); r.setAttribute("text-decoration", s.decoration); r.setAttribute("rotate", s.rotated ? 90 : 0); r.setAttribute("kerning", s.kerning ? "auto" : 0); r.setAttribute("text-rendering", "optimizeLegibility"); // update the text content if(r.firstChild){ r.firstChild.nodeValue = s.text; }else{ r.appendChild(_createTextNode(s.text)); } return this; // self }, getTextWidth: function(){ // summary: get the text width in pixels var rawNode = this.rawNode, oldParent = rawNode.parentNode, _measurementNode = rawNode.cloneNode(true); _measurementNode.style.visibility = "hidden"; // solution to the "orphan issue" in FF var _width = 0, _text = _measurementNode.firstChild.nodeValue; oldParent.appendChild(_measurementNode); // solution to the "orphan issue" in Opera // (nodeValue == "" hangs firefox) if(_text!=""){ while(!_width){ //Yang: work around svgweb bug 417 -- http://code.google.com/p/svgweb/issues/detail?id=417 if (_measurementNode.getBBox) _width = parseInt(_measurementNode.getBBox().width); else _width = 68; } } oldParent.removeChild(_measurementNode); return _width; } }); svg.Text.nodeType = "text"; declare("dojox.gfx.svg.Path", [svg.Shape, pathLib.Path], { // summary: a path shape (SVG) _updateWithSegment: function(segment){ // summary: updates the bounding box of path with new segment // segment: Object: a segment this.inherited(arguments); if(typeof(this.shape.path) == "string"){ this.rawNode.setAttribute("d", this.shape.path); } }, setShape: function(newShape){ // summary: forms a path using a shape (SVG) // newShape: Object: an SVG path string or a path object (see dojox.gfx.defaultPath) this.inherited(arguments); if(this.shape.path){ this.rawNode.setAttribute("d", this.shape.path); }else{ this.rawNode.removeAttribute("d"); } return this; // self } }); svg.Path.nodeType = "path"; declare("dojox.gfx.svg.TextPath", [svg.Shape, pathLib.TextPath], { // summary: a textpath shape (SVG) _updateWithSegment: function(segment){ // summary: updates the bounding box of path with new segment // segment: Object: a segment this.inherited(arguments); this._setTextPath(); }, setShape: function(newShape){ // summary: forms a path using a shape (SVG) // newShape: Object: an SVG path string or a path object (see dojox.gfx.defaultPath) this.inherited(arguments); this._setTextPath(); return this; // self }, _setTextPath: function(){ if(typeof this.shape.path != "string"){ return; } var r = this.rawNode; if(!r.firstChild){ var tp = _createElementNS(svg.xmlns.svg, "textPath"), tx = _createTextNode(""); tp.appendChild(tx); r.appendChild(tp); } var ref = r.firstChild.getAttributeNS(svg.xmlns.xlink, "href"), path = ref && svg.getRef(ref); if(!path){ var surface = this._getParentSurface(); if(surface){ var defs = surface.defNode; path = _createElementNS(svg.xmlns.svg, "path"); var id = g._base._getUniqueId(); path.setAttribute("id", id); defs.appendChild(path); r.firstChild.setAttributeNS(svg.xmlns.xlink, "xlink:href", "#" + id); } } if(path){ path.setAttribute("d", this.shape.path); } }, _setText: function(){ var r = this.rawNode; if(!r.firstChild){ var tp = _createElementNS(svg.xmlns.svg, "textPath"), tx = _createTextNode(""); tp.appendChild(tx); r.appendChild(tp); } r = r.firstChild; var t = this.text; r.setAttribute("alignment-baseline", "middle"); switch(t.align){ case "middle": r.setAttribute("text-anchor", "middle"); r.setAttribute("startOffset", "50%"); break; case "end": r.setAttribute("text-anchor", "end"); r.setAttribute("startOffset", "100%"); break; default: r.setAttribute("text-anchor", "start"); r.setAttribute("startOffset", "0%"); break; } //r.parentNode.setAttribute("alignment-baseline", "central"); //r.setAttribute("dominant-baseline", "central"); r.setAttribute("baseline-shift", "0.5ex"); r.setAttribute("text-decoration", t.decoration); r.setAttribute("rotate", t.rotated ? 90 : 0); r.setAttribute("kerning", t.kerning ? "auto" : 0); r.firstChild.data = t.text; } }); svg.TextPath.nodeType = "text"; declare("dojox.gfx.svg.Surface", gs.Surface, { // summary: a surface object to be used for drawings (SVG) constructor: function(){ gs.Container._init.call(this); }, destroy: function(){ this.defNode = null; // release the external reference this.inherited(arguments); }, setDimensions: function(width, height){ // summary: sets the width and height of the rawNode // width: String: width of surface, e.g., "100px" // height: String: height of surface, e.g., "100px" if(!this.rawNode){ return this; } this.rawNode.setAttribute("width", width); this.rawNode.setAttribute("height", height); return this; // self }, getDimensions: function(){ // summary: returns an object with properties "width" and "height" var t = this.rawNode ? { width: g.normalizedLength(this.rawNode.getAttribute("width")), height: g.normalizedLength(this.rawNode.getAttribute("height"))} : null; return t; // Object } }); svg.createSurface = function(parentNode, width, height){ // summary: creates a surface (SVG) // parentNode: Node: a parent node // width: String: width of surface, e.g., "100px" // height: String: height of surface, e.g., "100px" var s = new svg.Surface(); s.rawNode = _createElementNS(svg.xmlns.svg, "svg"); s.rawNode.setAttribute("overflow", "hidden"); if(width){ s.rawNode.setAttribute("width", width); } if(height){ s.rawNode.setAttribute("height", height); } var defNode = _createElementNS(svg.xmlns.svg, "defs"); s.rawNode.appendChild(defNode); s.defNode = defNode; s._parent = dom.byId(parentNode); s._parent.appendChild(s.rawNode); return s; // dojox.gfx.Surface }; // Extenders var Font = { _setFont: function(){ // summary: sets a font object (SVG) var f = this.fontStyle; // next line doesn't work in Firefox 2 or Opera 9 //this.rawNode.setAttribute("font", dojox.gfx.makeFontString(this.fontStyle)); this.rawNode.setAttribute("font-style", f.style); this.rawNode.setAttribute("font-variant", f.variant); this.rawNode.setAttribute("font-weight", f.weight); this.rawNode.setAttribute("font-size", f.size); this.rawNode.setAttribute("font-family", f.family); } }; var C = gs.Container, Container = { openBatch: function() { // summary: starts a new batch, subsequent new child shapes will be held in // the batch instead of appending to the container directly this.fragment = _createFragment(); }, closeBatch: function() { // summary: submits the current batch, append all pending child shapes to DOM if (this.fragment) { this.rawNode.appendChild(this.fragment); delete this.fragment; } }, add: function(shape){ // summary: adds a shape to a group/surface // shape: dojox.gfx.Shape: an VML shape object if(this != shape.getParent()){ if (this.fragment) { this.fragment.appendChild(shape.rawNode); } else { this.rawNode.appendChild(shape.rawNode); } C.add.apply(this, arguments); } return this; // self }, remove: function(shape, silently){ // summary: remove a shape from a group/surface // shape: dojox.gfx.Shape: an VML shape object // silently: Boolean?: if true, regenerate a picture if(this == shape.getParent()){ if(this.rawNode == shape.rawNode.parentNode){ this.rawNode.removeChild(shape.rawNode); } if(this.fragment && this.fragment == shape.rawNode.parentNode){ this.fragment.removeChild(shape.rawNode); } C.remove.apply(this, arguments); } return this; // self }, clear: function(){ // summary: removes all shapes from a group/surface var r = this.rawNode; while(r.lastChild){ r.removeChild(r.lastChild); } var defNode = this.defNode; if(defNode){ while(defNode.lastChild){ defNode.removeChild(defNode.lastChild); } r.appendChild(defNode); } return C.clear.apply(this, arguments); }, _moveChildToFront: C._moveChildToFront, _moveChildToBack: C._moveChildToBack }; var Creator = { // summary: SVG shape creators createObject: function(shapeType, rawShape){ // summary: creates an instance of the passed shapeType class // shapeType: Function: a class constructor to create an instance of // rawShape: Object: properties to be passed in to the classes "setShape" method if(!this.rawNode){ return null; } var shape = new shapeType(), node = _createElementNS(svg.xmlns.svg, shapeType.nodeType); shape.setRawNode(node); shape.setShape(rawShape); // rawNode.appendChild() will be done inside this.add(shape) below this.add(shape); return shape; // dojox.gfx.Shape } }; lang.extend(svg.Text, Font); lang.extend(svg.TextPath, Font); lang.extend(svg.Group, Container); lang.extend(svg.Group, gs.Creator); lang.extend(svg.Group, Creator); lang.extend(svg.Surface, Container); lang.extend(svg.Surface, gs.Creator); lang.extend(svg.Surface, Creator); // Mouse/Touch event svg.fixTarget = function(event, gfxElement) { // summary: // Adds the gfxElement to event.gfxTarget if none exists. This new // property will carry the GFX element associated with this event. // event: Object // The current input event (MouseEvent or TouchEvent) // gfxElement: Object // The GFX target element if (!event.gfxTarget) { if (safMobile && event.target.wholeText) { // Workaround iOS bug when touching text nodes event.gfxTarget = gs.byId(event.target.parentElement.__gfxObject__); } else { event.gfxTarget = gs.byId(event.target.__gfxObject__); } } return true; }; // some specific override for svgweb + flash if(svg.useSvgWeb){ // override createSurface() svg.createSurface = function(parentNode, width, height){ var s = new svg.Surface(); // ensure width / height if(!width || !height){ var pos = domGeom.position(parentNode); width = width || pos.w; height = height || pos.h; } // ensure id parentNode = dom.byId(parentNode); var id = parentNode.id ? parentNode.id+'_svgweb' : g._base._getUniqueId(); // create dynamic svg root var mockSvg = _createElementNS(svg.xmlns.svg, 'svg'); mockSvg.id = id; mockSvg.setAttribute('width', width); mockSvg.setAttribute('height', height); svgweb.appendChild(mockSvg, parentNode); // notice: any call to the raw node before flash init will fail. mockSvg.addEventListener('SVGLoad', function(){ // become loaded s.rawNode = this; s.isLoaded = true; // init defs var defNode = _createElementNS(svg.xmlns.svg, "defs"); s.rawNode.appendChild(defNode); s.defNode = defNode; // notify application if (s.onLoad) s.onLoad(s); }, false); // flash not loaded yet s.isLoaded = false; return s; }; // override Surface.destroy() svg.Surface.extend({ destroy: function(){ var mockSvg = this.rawNode; svgweb.removeChild(mockSvg, mockSvg.parentNode); } }); // override connect() & disconnect() for Shape & Surface event processing var _eventsProcessing = { connect: function(name, object, method){ // connect events using the mock addEventListener() provided by svgweb if (name.substring(0, 2)==='on') { name = name.substring(2); } if (arguments.length == 2) { method = object; } else { method = lang.hitch(object, method); } this.getEventSource().addEventListener(name, method, false); return [this, name, method]; }, disconnect: function(token){ // disconnect events using the mock removeEventListener() provided by svgweb this.getEventSource().removeEventListener(token[1], token[2], false); delete token[0]; } }; lang.extend(svg.Shape, _eventsProcessing); lang.extend(svg.Surface, _eventsProcessing); } return svg; });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Types considered simple: * * - primitive types * - literal types * - mixed and any types * - generic types (such as Date, Promise<string>, $Keys<T>, etc.) * - array type written in shorthand notation * * Types not considered simple: * * - maybe type * - function type * - object type * - tuple type * - union and intersection types * * Reminder: if you change these semantics, don't forget to modify documentation of `array-style-...` rules */ var simpleTypePatterns = [/^(?:Any|Array|Boolean|Generic|Mixed|Number|String|Void)TypeAnnotation$/, /.+LiteralTypeAnnotation$/]; exports.default = function (node) { return simpleTypePatterns.some(function (pattern) { return pattern.test(node.type); }); }; module.exports = exports.default;
describe('The ch.Validation', function () { var Validation = ch.Validation, form = '<form id="form{ID}" action="./" class="ch-form"><div class="ch-form-row"><label>Test {ID}</label><input id="validation{ID}" type="text"></div><div class="ch-form-actions"><input type="submit" class="ch-btn"></div></form>', idGenerator = (function(){ var count = 0; return function(){ return count++; } }()), email = { // hacer array con la condition condition: { name: "email", message: 'Message' } }, string = { condition: { name: "string", message: 'Message' } }, required = { condition: { name: "required", message: 'Message' } }; describe('constructor', function () { var n = idGenerator(); var f = $(form.replace(/{ID}/g, n)); var input = f.find('#validation' + n); var validation = new Validation(input, email); $('body').prepend(f); it('should be a function.', function () { expect(typeof Validation).toEqual('function'); }); describe('returns an object', function () { it('so it should be an object', function () { expect(typeof validation).toEqual('object'); }); describe('with property', function () { it('"element" that it should be a instanceof a HTMLElement.', function () { expect(validation.element).toBeDefined(); expect(validation.element instanceof HTMLElement).toBeTruthy(); }); it('"float" that it should be an object', function () { expect(validation['float']).toBeDefined(); expect(typeof validation['float']).toEqual('object'); }); it('"form" that it should be an object', function () { expect(validation.form).toBeDefined(); expect(typeof validation.form).toEqual('object'); }); it('"helper" that it should be an object', function () { expect(validation.helper).toBeDefined(); expect(typeof validation.helper).toEqual('object'); }); it('"type" that it should be a string', function () { expect(validation.type).toBeDefined(); expect(typeof validation.type).toEqual('string'); expect(validation.type).toEqual('validation'); }); it('"validator" that it should be an object', function () { expect(validation.validator).toBeDefined(); expect(typeof validation.validator).toEqual('object'); }); it('"uid" that it should be a number', function () { expect(validation.uid).toBeDefined(); expect(typeof validation.uid).toEqual('number'); }); }); describe('with method', function () { it('"and" that it should return an object', function () { expect(validation.and).toBeDefined(); expect(typeof validation.and).toEqual('function'); expect(typeof validation.and()).toEqual('object'); }); it('"clear" that it should return an object', function () { expect(validation.clear).toBeDefined(); expect(typeof validation.clear).toEqual('function'); expect(typeof validation.clear()).toEqual('object'); // === validation }); it('"disable" that it should return an object', function () { expect(validation.disable).toBeDefined(); expect(typeof validation.disable).toEqual('function'); expect(typeof validation.disable()).toEqual('object'); }); it('"enable" that it should return an object', function () { expect(validation.enable).toBeDefined(); expect(typeof validation.enable).toEqual('function'); expect(typeof validation.enable()).toEqual('object'); }); it('"hasError" that it should return a boolean value', function () { expect(validation.hasError).toBeDefined(); expect(typeof validation.hasError).toEqual('function'); expect(typeof validation.hasError()).toEqual('boolean'); }); it('"isActive" that it should return a boolean value', function () { expect(validation.isActive).toBeDefined(); expect(typeof validation.isActive).toEqual('function'); expect(typeof validation.isActive()).toEqual('boolean'); }); it('"message"', function () { expect(validation.message).toBeDefined(); expect(typeof validation.message).toEqual('function'); }); it('"off" that it should return an object', function () { expect(validation.off).toBeDefined(); expect(typeof validation.off).toEqual('function'); expect(typeof validation.off('show', function(){})).toEqual('object'); }); it('"on" that it should return an object', function () { expect(validation.on).toBeDefined(); expect(typeof validation.on).toEqual('function'); expect(typeof validation.on('show', function(){})).toEqual('object'); }); it('"once" that it should return an object', function () { expect(validation.once).toBeDefined(); expect(typeof validation.once).toEqual('function'); expect(typeof validation.once('show', function(){})).toEqual('object'); }); it('"position"', function () { expect(validation.position).toBeDefined(); expect(typeof validation.position).toEqual('function'); }); it('"toggleEnable" that it should return an object', function () { expect(validation.toggleEnable).toBeDefined(); expect(typeof validation.toggleEnable).toEqual('function'); expect(typeof validation.toggleEnable()).toEqual('object'); }); it('"trigger"', function () { expect(validation.trigger).toBeDefined(); expect(typeof validation.trigger).toEqual('function'); }); it('"validate" that it should return an object', function () { expect(validation.validate).toBeDefined(); expect(typeof validation.validate).toEqual('function'); expect(typeof validation.validate()).toEqual('object'); }); }); }); }); describe('method', function () { var input; beforeEach(function() { var n = idGenerator(); var f = $(form.replace(/{ID}/g, n)); input = f.find('#validation' + n); f.insertAfter('#form' + (n-1)); }); afterEach(function() { input.removeAttr('value'); }); describe('message', function () { it('should return the original sent message by parameter', function () { var validation = input.email('Message'); expect(validation.message('email')).toEqual('Message'); }); it('should change the message', function () { var validation = input.email('Message'); expect(validation.message('email', 'New Message').message('email')).toEqual('New Message'); }); }); describe('hasError', function () { it('should return an error', function () { var validation = input.email('Message'); input.attr('value','1234'); expect(validation.hasError()).toBeTruthy(); }); it('should be valid', function () { var validation = input.email('Message'); input.attr('value','foo@bar.foo'); expect(validation.hasError()).toBeFalsy(); }); }); describe('disable', function () { it('should off the engine and it should not to return an error when the input has a valid value', function () { var validation = input.required(); input.attr('value','12345'); validation.disable(); expect(validation.hasError()).toBeFalsy(); }); it('should off the engine and it should not to return an error when the input has an invalid value', function () { var validation = input.required(); validation.disable(); expect(validation.hasError()).toBeFalsy(); }); }); describe('enable', function () { // review those tests, it are test in that way because we hadn't a way to test enable disable methods // those tests could be for hasError method it('should on the engine and it should not return an error when the input has a valid value', function () { var validation = input.required(); input.attr('value','12345'); validation.disable(); validation.enable(); expect(validation.hasError()).toBeFalsy(); }); it('should on the engine and it should return an error when the input has a invalid value', function () { var validation = input.required(); validation.disable(); validation.enable(); expect(validation.hasError()).toBeTruthy(); }); }); describe('toggleEnable', function () { it('should off the engine when it is on, and it should not return an error when the input is a invalid value', function () { var validation = input.required(); validation.toggleEnable(); expect(validation.hasError()).toBeFalsy(); }); it('should on the engine when it is off, and it should return an error when the input is a invalid value', function () { var validation = input.required(); validation.disable(); validation.toggleEnable(); expect(validation.hasError()).toBeTruthy(); }); }); describe('isActive', function () { it('should return false when the validation message is not visible', function () { var validation = input.required(); expect(validation.isActive()).toBeFalsy(); }); it('should return true when the validation message is not visible', function () { var validation = input.required(); validation.validate(); expect(validation.isActive()).toBeTruthy(); }); it('should return false when the validation message is not visible after it was showed because it had an error', function () { var validation = input.required(); validation.validate(); input.attr('value','12345'); validation.validate(); expect(validation.isActive()).toBeFalsy(); }); }); describe('and', function () { it('should return the same jQuery object that was used to instantiate the component', function () { var validation = input.required(); var uid = validation.uid; var jQueryObject = validation.and(); expect(jQueryObject.data().validation.uid).toEqual(uid); }); }); }); describe('condition', function () { var n = idGenerator(); var f = $(form.replace(/{ID}/g, n)); var input = f.find('#validation' + n); var validation = input.required('Required').and().email('Message'); f.insertAfter('#form' + (n-1)); it('should be defined', function () { expect(validation.validator.conditions.required).toBeDefined('object'); expect(typeof validation.validator.conditions.required).toEqual('object'); expect(validation.validator.conditions.email).toBeDefined('object'); expect(typeof validation.validator.conditions.email).toEqual('object'); }); it('should show the correct message to each condition', function () { expect(validation.validator.conditions.required.message).toEqual('Required'); expect(validation.validator.conditions.email.message).toEqual('Message'); }); }); describe('classes.', function () { var n = idGenerator(); var f = $(form.replace(/{ID}/g, n)); var input = f.find('#validation' + n); var validation = input.required('Required').and().email('Message'); f.insertAfter('#form' + (n-1)); it('"ch-points-ltrt" should be added to the input element', function () { expect( input.hasClass('ch-points-ltrt') ).toBeTruthy(); }); it('"ch-points-ltrt" and "ch-form-error" should be added to the input element', function () { validation.validate(); expect( input.hasClass('ch-points-ltrt') && input.hasClass('ch-form-error') ).toBeTruthy(); }); it('"ch-points-ltrt", "ch-validation", "ch-box-error" and "ch-cone" classes should be added to the message element', function () { var message = $('#' + input.attr('aria-label')); expect(message.hasClass('ch-points-ltrt') && message.hasClass('ch-validation') && message.hasClass('ch-box-error') && message.hasClass('ch-cone')).toBeTruthy(); }); }); describe('event', function () { var n = idGenerator(); var f = $(form.replace(/{ID}/g, n)); var input = f.find('#validation' + n); var validation = input.required(); $('body').prepend(f); var readyCallback, beforeValidateCallback, afterValidateCallback, clearCallback, errorCallback; validation.on('ready', function(){ readyEvent(); }); validation.on('beforeValidate', function(){ beforeValidateEvent(); }); validation.on('afterValidate', function(){ afterValidateEvent(); }); validation.on('clear', function(){ clearEvent(); }); validation.on('error', function(){ errorEvent(); }); beforeEach(function () { readyEvent = jasmine.createSpy('readyEvent'); beforeValidateEvent = jasmine.createSpy('beforeValidateEvent'); afterValidateEvent = jasmine.createSpy('afterValidateEvent'); clearEvent = jasmine.createSpy('clearEvent'); errorEvent = jasmine.createSpy('errorEvent'); }); it('ready', function () { waits(75); runs(function () { expect(readyEvent).toHaveBeenCalled(); }); }); it('beforeValidate', function () { input.attr('value', 'foo'); validation.validate(); expect(beforeValidateEvent.callCount).toEqual(1); expect(beforeValidateEvent).toHaveBeenCalled(); }); it('afterValidate', function () { validation.validate(); expect(afterValidateEvent.callCount).toEqual(1); expect(afterValidateEvent).toHaveBeenCalled(); }); it('clear', function () { validation.clear(); expect(clearEvent.callCount).toEqual(1); expect(clearEvent).toHaveBeenCalled(); }); it('error', function () { input.attr('value', ''); validation.validate(); expect(errorEvent.callCount).toEqual(1); expect(errorEvent).toHaveBeenCalled(); }); }); describe('callback', function () { var n = idGenerator(); var f = $(form.replace(/{ID}/g, n)); var input = f.find('#validation' + n); var beforeValidateCallback, afterValidateCallback, clearCallback, errorCallback; var validation = input.required({ 'beforeValidate': function(){ beforeValidateCallback(); }, 'afterValidate': function(){ afterValidateCallback(); }, 'onClear': function(){ clearCallback(); }, 'onError': function(){ errorCallback(); } }); $('body').prepend(f); beforeEach(function () { beforeValidateCallback = jasmine.createSpy('beforeValidateCallback'); afterValidateCallback = jasmine.createSpy('afterValidateCallback'); clearCallback = jasmine.createSpy('clearCallback'); errorCallback = jasmine.createSpy('errorCallback'); }); it('beforeValidate', function () { input.attr('value', 'foo'); validation.validate(); expect(beforeValidateCallback.callCount).toEqual(1); expect(beforeValidateCallback).toHaveBeenCalled(); }); it('afterValidate', function () { validation.validate(); expect(afterValidateCallback.callCount).toEqual(1); expect(afterValidateCallback).toHaveBeenCalled(); }); it('clear', function () { validation.clear(); expect(clearCallback.callCount).toEqual(1); expect(clearCallback).toHaveBeenCalled(); }); it('error', function () { input.attr('value', ''); validation.validate(); expect(errorCallback.callCount).toEqual(1); expect(errorCallback).toHaveBeenCalled(); }); }); });
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M18.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM5 10v4c0 .55.45 1 1 1h3l3.29 3.29c.63.63 1.71.18 1.71-.71V6.41c0-.89-1.08-1.34-1.71-.71L9 9H6c-.55 0-1 .45-1 1z" /></React.Fragment> , 'VolumeDownRounded');
import moment from "moment" import React from "react" import PanelLoader from "misago/components/panel-loader" import PanelMessage from "misago/components/panel-message" import misago from "misago/index" import polls from "misago/services/polls" import title from "misago/services/page-title" export default class extends React.Component { constructor(props) { super(props) if (misago.has("PROFILE_BAN")) { this.initWithPreloadedData(misago.pop("PROFILE_BAN")) } else { this.initWithoutPreloadedData() } this.startPolling(props.profile.api.ban) } initWithPreloadedData(ban) { if (ban.expires_on) { ban.expires_on = moment(ban.expires_on) } this.state = { isLoaded: true, ban } } initWithoutPreloadedData() { this.state = { isLoaded: false } } startPolling(api) { polls.start({ poll: "ban-details", url: api, frequency: 90 * 1000, update: this.update, error: this.error }) } update = ban => { if (ban.expires_on) { ban.expires_on = moment(ban.expires_on) } this.setState({ isLoaded: true, error: null, ban }) } error = error => { this.setState({ isLoaded: true, error: error.detail, ban: null }) } componentDidMount() { title.set({ title: gettext("Ban details"), parent: this.props.profile.username }) } componentWillUnmount() { polls.stop("ban-details") } getUserMessage() { if (this.state.ban.user_message) { return ( <div className="panel-body ban-message ban-user-message"> <h4>{gettext("User-shown ban message")}</h4> <div className="lead" dangerouslySetInnerHTML={{ __html: this.state.ban.user_message.html }} /> </div> ) } else { return null } } getStaffMessage() { if (this.state.ban.staff_message) { return ( <div className="panel-body ban-message ban-staff-message"> <h4>{gettext("Team-shown ban message")}</h4> <div className="lead" dangerouslySetInnerHTML={{ __html: this.state.ban.staff_message.html }} /> </div> ) } else { return null } } getExpirationMessage() { if (this.state.ban.expires_on) { if (this.state.ban.expires_on.isAfter(moment())) { let title = interpolate( gettext("This ban expires on %(expires_on)s."), { expires_on: this.state.ban.expires_on.format("LL, LT") }, true ) let message = interpolate( gettext("This ban expires %(expires_on)s."), { expires_on: this.state.ban.expires_on.fromNow() }, true ) return <abbr title={title}>{message}</abbr> } else { return gettext("This ban has expired.") } } else { return interpolate( gettext("%(username)s's ban is permanent."), { username: this.props.profile.username }, true ) } } getPanelBody() { if (this.state.ban) { if (Object.keys(this.state.ban).length) { return ( <div> {this.getUserMessage()} {this.getStaffMessage()} <div className="panel-body ban-expires"> <h4>{gettext("Ban expiration")}</h4> <p className="lead">{this.getExpirationMessage()}</p> </div> </div> ) } else { return ( <div> <PanelMessage message={gettext("No ban is active at the moment.")} /> </div> ) } } else if (this.state.error) { return ( <div> <PanelMessage icon="error_outline" message={this.state.error} /> </div> ) } else { return ( <div> <PanelLoader /> </div> ) } } render() { return ( <div className="profile-ban-details"> <div className="panel panel-default"> <div className="panel-heading"> <h3 className="panel-title">{gettext("Ban details")}</h3> </div> {this.getPanelBody()} </div> </div> ) } }
/* * Tambahin nama author lah * Author nya Radya and Nazwa * Tambahin ya zhayank * Jan numpang nama doank * Baca readme nya biar gk tanya tanya */ const { WAConnection, MessageType, Presence, Mimetype, GroupSettingChange } = require('@adiwajshing/baileys') /******BEGIN OF FILE INPUT******/ const { color, bgcolor } = require('./lib/color') const { bahasa } = require('./src/bahasa') const { negara } = require('./src/kodenegara') const { virtex } = require('./src/virtex') const { wait, simih, getBuffer, h2k, generateMessageID, getGroupAdmins, getRandom, banner, start, info, success, close } = require('./lib/functions') const { fetchJson } = require('./lib/fetcher') const { recognize } = require('./lib/ocr') /******END OF FILE INPUT******/ /******BEGIN OF NPM PACKAGE INPUT******/ const fs = require('fs') const moment = require('moment-timezone') const { exec } = require('child_process') const kagApi = require('@kagchi/kag-api') const fetch = require('node-fetch') const tiktod = require('tiktok-scraper') const ffmpeg = require('fluent-ffmpeg') const { removeBackgroundFromImageFile } = require('remove.bg') const imgbb = require('imgbb-uploader') const lolis = require('lolis.life') const loli = new lolis() const speed = require('performance-now') /******END OF NPM PACKAGE INPUT******/ /******BEGIN OF JSON INPUT******/ const welkom = JSON.parse(fs.readFileSync('./src/welkom.json')) const nsfw = JSON.parse(fs.readFileSync('./src/nsfw.json')) const samih = JSON.parse(fs.readFileSync('./src/simi.json')) const _leveling = JSON.parse(fs.readFileSync('./src/leveling.json')) const _level = JSON.parse(fs.readFileSync('./src/level.json')) /******END OF JSON INPUT******/ /******LOAD OF MENU INPUT******/ const { help } = require('./src/help') const { menuadmin } = require('./src/menuadmin') const { nsfwmenu } = require('./src/nsfwmenu') const { toinmenu } = require('./src/toinmenu') //const { makermenu } = require('./database/menu/makermenu') //const { mediamenu } = require('./database/menu/mediamenu') //const { educationmenu } = require('./database/menu/educationmenu') //const { downloadermenu } = require('./database/menu/downloadermenu') //const { mememenu } = require('./database/menu/mememenu') //const { kerangmenu } = require('./database/menu/kerangmenu') //const { groupmenu } = require('./database/menu/groupmenu') //const { soundmenu } = require('./database/menu/soundmenu') //const { musicmenu } = require('./database/menu/musicmenu') //const { islammenu } = require('./database/menu/islammenu') //const { stalkmenu } = require('./database/menu/stalkmenu') //const { wibumenu } = require('./database/menu/wibumenu') //const { funmenu } = require('./database/menu/funmenu') //const { informationmenu } = require('./database/menu/informationmenu') //const { 18+menu } require('./database/menu/18+menu') //const { ownermenu } require('./database/menu/ownermenu') //const { othermenu } require('./database/menu/othermenu') /******END OF MENU INPUT******/ //const daftar = JSON.parse(fs.readFileSync('./src/daftar.json')) const vcard = 'BEGIN:VCARD\n' // metadata of the contact card + 'VERSION:3.0\n' + 'FN:Toin\n' // full name + 'ORG:Owner Bot;\n' // the organization of the contact + 'TEL;type=CELL;type=VOICE;waid=12542123926:+55 (62) 99663-8900\n' // WhatsApp ID + phone number + 'END:VCARD' prefix = '*' blocked = [] /******BEGIN OF FUNCTIONS INPUT******/ const getLevelingXp = (userId) => { let position = false Object.keys(_level).forEach((i) => { if (_level[i].jid === userId) { position = i } }) if (position !== false) { return _level[position].xp } } const getLevelingLevel = (userId) => { let position = false Object.keys(_level).forEach((i) => { if (_level[i].jid === userId) { position = i } }) if (position !== false) { return _level[position].level } } const getLevelingId = (userId) => { let position = false Object.keys(_level).forEach((i) => { if (_level[i].jid === userId) { position = i } }) if (position !== false) { return _level[position].jid } } const addLevelingXp = (userId, amount) => { let position = false Object.keys(_level).forEach((i) => { if (_level[i].jid === userId) { position = i } }) if (position !== false) { _level[position].xp += amount fs.writeFileSync('./src/level.json', JSON.stringify(_level)) } } const addLevelingLevel = (userId, amount) => { let position = false Object.keys(_level).forEach((i) => { if (_level[i].jid === userId) { position = i } }) if (position !== false) { _level[position].level += amount fs.writeFileSync('./src/level.json', JSON.stringify(_level)) } } const addLevelingId = (userId) => { const obj = {jid: userId, xp: 1, level: 1} _level.push(obj) fs.writeFileSync('./src/level.json', JSON.stringify(_level)) } function kyun(seconds){ function pad(s){ return (s < 10 ? '0' : '') + s; } var hours = Math.floor(seconds / (60*60)); var minutes = Math.floor(seconds % (60*60) / 60); var seconds = Math.floor(seconds % 60); //return pad(hours) + ':' + pad(minutes) + ':' + pad(seconds) return `${pad(hours)} Jam ${pad(minutes)} Menit ${pad(seconds)} Detik` } async function starts() { const client = new WAConnection() client.logger.level = 'warn' console.log(banner.string) client.on('qr', () => { console.log(color('[','white'), color('!','red'), color(']','white'), color(' Scan the qr code above')) }) fs.existsSync('./Nazwa.json') && client.loadAuthInfo('./Nazwa.json') client.on('connecting', () => { start('2', 'Connecting...') }) client.on('open', () => { success('2', 'Connected') }) await client.connect({timeoutMs: 30*1000}) fs.writeFileSync('./Nazwa.json', JSON.stringify(client.base64EncodedAuthInfo(), null, '\t')) client.on('group-participants-update', async (anu) => { if (!welkom.includes(anu.jid)) return try { const mdata = await client.groupMetadata(anu.jid) console.log(anu) if (anu.action == 'add') { num = anu.participants[0] try { ppimg = await client.getProfilePicture(`${anu.participants[0].split('@')[0]}@c.us`) } catch { ppimg = 'https://i0.wp.com/www.gambarunik.id/wp-content/uploads/2019/06/Top-Gambar-Foto-Profil-Kosong-Lucu-Tergokil-.jpg' } teks = `Oiin @${num.split('@')[0]}\nBem vindor ao *${mdata.subject}*` let buff = await getBuffer(ppimg) client.sendMessage(mdata.id, buff, MessageType.image, {caption: teks, contextInfo: {"mentionedJid": [num]}}) } else if (anu.action == 'remove') { num = anu.participants[0] try { ppimg = await client.getProfilePicture(`${num.split('@')[0]}@c.us`) } catch { ppimg = 'https://i0.wp.com/www.gambarunik.id/wp-content/uploads/2019/06/Top-Gambar-Foto-Profil-Kosong-Lucu-Tergokil-.jpg' } teks = `ja foi tarde @${num.split('@')[0]}👋` let buff = await getBuffer(ppimg) client.sendMessage(mdata.id, buff, MessageType.image, {caption: teks, contextInfo: {"mentionedJid": [num]}}) } } catch (e) { console.log('Error : %s', color(e, 'red')) } }) client.on('CB:Blocklist', json => { if (blocked.length > 2) return for (let i of json[1].blocklist) { blocked.push(i.replace('c.us','s.whatsapp.net')) } }) client.on('chat-update', async (mek) => { try { if (!mek.hasNewMessage) return mek = JSON.parse(JSON.stringify(mek)).messages[0] if (!mek.message) return if (mek.key && mek.key.remoteJid == 'status@broadcast') return if (mek.key.fromMe) return global.prefix global.blocked const content = JSON.stringify(mek.message) const from = mek.key.remoteJid const type = Object.keys(mek.message)[0] const { text, extendedText, contact, location, liveLocation, image, video, sticker, document, audio, product } = MessageType const time = moment.tz('Asia/Jakarta').format('DD/MM HH:mm:ss') const date = moment.tz('Asia/Jakarta').format('DD,MM,YY') body = (type === 'conversation' && mek.message.conversation.startsWith(prefix)) ? mek.message.conversation : (type == 'imageMessage') && mek.message.imageMessage.caption.startsWith(prefix) ? mek.message.imageMessage.caption : (type == 'videoMessage') && mek.message.videoMessage.caption.startsWith(prefix) ? mek.message.videoMessage.caption : (type == 'extendedTextMessage') && mek.message.extendedTextMessage.text.startsWith(prefix) ? mek.message.extendedTextMessage.text : '' budy = (type === 'conversation') ? mek.message.conversation : (type === 'extendedTextMessage') ? mek.message.extendedTextMessage.text : '' const command = body.slice(1).trim().split(/ +/).shift().toLowerCase() const args = body.trim().split(/ +/).slice(1) const isCmd = body.startsWith(prefix) mess = { wait: '⌛ Calmaer mano to fazendo ⌛', success: '✔️ Sucesso ✔️', levelon: '❬ ✔ ❭ *Ativado leveling*', leveloff: ' ❬ X ❭ *Desativado leveling*', levelnoton: '❬ X ❭ *Leveling naum ativado*', levelnol: '*Kskskst opohar Level* 0 ', error: { stick: '[❗] Falha, ocorreu um erro ao converter a imagem em um adesivo ❌', Iv: '❌ Link inválido ❌' }, only: { group: '[❗] Este comando só pode ser usado em grupos! ❌', ownerG: '[❗] Este comando so pode ser usado pelo dono do grupo! ❌', ownerB: '[❗] Este comando só pode ser usado pelo Vitinn! ❌', admin: '[❗] Este comando só pode ser usado por administradores de grupo,Seu membro comum 😂! ❌', Badmin: '[❗] Este comando só pode ser usado quando o bot se torna administrador! ❌', daftarB: `──「 DAFTAR 」──\nHalo kak !\nKamu belum Terdaftar didalam database, \n\nCommand : ${prefix}daftar nama|umur\nContoh : ${prefix}daftar Ryz|17`, } } const apakah = ['Ya','Tidak'] const bisakah = ['Bisa','Tidak Bisa'] const kapankah = ['Hari Lagi','Minggu Lagi','Bulan Lagi','Tahun Lagi'] const botNumber = client.user.jid const ownerNumber = ["5598989016015@s.whatsapp.net"] // replace this with your number const nomorOwner = [ownerNumber] const isGroup = from.endsWith('@g.us') const totalchat = await client.chats.all() const sender = isGroup ? mek.participant : mek.key.remoteJid const groupMetadata = isGroup ? await client.groupMetadata(from) : '' const groupName = isGroup ? groupMetadata.subject : '' const groupId = isGroup ? groupMetadata.jid : '' let { pushname, verifiedName } = sender pushname = pushname || verifiedName // verifiedName is the name of someone who uses a business account const groupMembers = isGroup ? groupMetadata.participants : '' const groupAdmins = isGroup ? getGroupAdmins(groupMembers) : '' const isBotGroupAdmins = groupAdmins.includes(botNumber) || false const isGroupAdmins = groupAdmins.includes(sender) || false const isWelkom = isGroup ? welkom.includes(from) : false const isNsfw = isGroup ? nsfw.includes(from) : false const isSimi = isGroup ? samih.includes(from) : false const isOwner = ownerNumber.includes(sender) const isLevelingOn = isGroup ? _leveling.includes(groupId) : false const NomerOwner = '5598988636013@s.whatsapp.net' //const isDaftar = daftar.includes(sender) const isUrl = (url) => { return url.match(new RegExp(/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)/, 'gi')) } const reply = (teks) => { client.sendMessage(from, teks, text, {quoted:mek}) } const sendMess = (hehe, teks) => { client.sendMessage(hehe, teks, text) } const mentions = (teks, memberr, id) => { (id == null || id == undefined || id == false) ? client.sendMessage(from, teks.trim(), extendedText, {contextInfo: {"mentionedJid": memberr}}) : client.sendMessage(from, teks.trim(), extendedText, {quoted: mek, contextInfo: {"mentionedJid": memberr}}) } //function leveling if (isGroup && isLevelingOn) { const currentLevel = getLevelingLevel(sender) const checkId = getLevelingId(sender) try { if (currentLevel === undefined && checkId === undefined) addLevelingId(sender) const amountXp = Math.floor(Math.random() * 10) + 500 const requiredXp = 5000 * (Math.pow(2, currentLevel) - 1) const getLevel = getLevelingLevel(sender) addLevelingXp(sender, amountXp) if (requiredXp <= getLevelingXp(sender)) { addLevelingLevel(sender, 1) await reply(`*「 LEVEL UP 」*\n\n➸ *Nome*: ${sender}\n➸ *XP*: ${getLevelingXp(sender)}\n➸ *Level*: ${getLevel} -> ${getLevelingLevel(sender)}\n\nCongrats!! 🎉🎉`) } } catch (err) { console.error(err) } } colors = ['red','white','black','blue','yellow','green'] const isMedia = (type === 'imageMessage' || type === 'videoMessage') const isQuotedImage = type === 'extendedTextMessage' && content.includes('imageMessage') const isQuotedVideo = type === 'extendedTextMessage' && content.includes('videoMessage') const isQuotedSticker = type === 'extendedTextMessage' && content.includes('stickerMessage') if (!isGroup && isCmd) console.log('\x1b[1;31m~\x1b[1;37m>', '[\x1b[1;32mEXEC\x1b[1;37m]', time, color(command), 'from', color(sender.split('@')[0]), 'args :', color(args.length)) if (!isGroup && !isCmd) console.log('\x1b[1;31m~\x1b[1;37m>', '[\x1b[1;31mRECV\x1b[1;37m]', time, color('Message'), 'from', color(sender.split('@')[0]), 'args :', color(args.length)) if (isCmd && isGroup) console.log('\x1b[1;31m~\x1b[1;37m>', '[\x1b[1;32mEXEC\x1b[1;37m]', time, color(command), 'from', color(sender.split('@')[0]), 'in', color(groupName), 'args :', color(args.length)) if (!isCmd && isGroup) console.log('\x1b[1;31m~\x1b[1;37m>', '[\x1b[1;31mRECV\x1b[1;37m]', time, color('Message'), 'from', color(sender.split('@')[0]), 'in', color(groupName), 'args :', color(args.length)) /******END OF FUNCTIONS INPUT******/ switch(command) { case '.': case '.': hisil = fs.readFileSync('./assets/menuimg.jpg') client.sendMessage(from, hisil, image, {quoted: mek, caption: (prefix), text}) break case 'help': case 'menu': client.sendMessage(from, help(prefix, sender), text, {quoted: mek}) break case 'bahasa': client.sendMessage(from, bahasa(prefix, sender), text, {quoted: mek}) break case 'virtex': client.sendMessage(from, virtex(prefix, sender), text, {quoted: mek}) break case 'kodenegara': client.sendMessage(from, negara(prefix, sender), text, {quoted: mek}) break case 'vitinnmenu': client.sendMessage(from, vitinnmenu(prefix, sender), text, {quoted: mek}) break case 'menuadmin': client.sendMessage(from, menuadmin(prefix, sender), text, {quoted: mek}) break case 'nsfwmenu': client.sendMessage(from, nsfwmenu(prefix, sender), text, {quoted: mek}) break case 'demote': if (!isGroup) return reply(mess.only.group) if (!isGroupAdmins) return reply(mess.only.admin) if (!isBotGroupAdmins) return reply(mess.only.Badmin) if (mek.message.extendedTextMessage === undefined || mek.message.extendedTextMessage === null) return reply('𝐓𝐚𝐠 𝐭𝐚𝐫𝐠𝐞𝐭 𝐲𝐚𝐧𝐠 𝐦𝐚𝐮 𝐝𝐢 𝐭𝐮𝐫𝐮𝐧𝐤𝐚𝐧 𝐚𝐝𝐦𝐢𝐧') mentioned = mek.message.extendedTextMessage.contextInfo.mentionedJid if (mentioned.length > 1) { teks = '' for (let _ of mentioned) { teks += `𝐏𝐞𝐫𝐢𝐧𝐭𝐚𝐡 𝐝𝐢𝐭𝐞𝐫𝐢𝐦𝐚, 𝐦𝐞𝐧𝐮𝐫𝐮𝐧𝐤𝐚𝐧 𝐣𝐚𝐝𝐢 𝐚𝐝𝐦𝐢𝐧 𝐠𝐫𝐨𝐮𝐩 :\n` teks += `@_.split('@')[0]` } mentions(teks, mentioned, true) client.groupDemoteAdmin(from, mentioned) } else { mentions(`Agora ele @${mentioned[0].split('@')[0]}\n é um membro comum kkkk _*${groupMetadata.subject}*_`, mentioned, true) client.groupDemoteAdmin(from, mentioned) } break case 'toin': gatauda = body.slice(6) /*if (!isDaftar) return reply(mess.only.daftarB)*/ reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/hentai?apikey=BotWeA`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek}) break case 'loli': gatauda = body.slice(6) /*if (!isDaftar) return reply(mess.only.daftarB)*/ reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/randomloli?apikey=BotWeA`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek}) break case 'nsfwlolinaumfunfa': if (!isNsfw) return reply('❌ *NSFW Desativado* ❌') loli.getNSFWLoli(async (err, res) => { if (err) return reply('❄1�7 *ERRO* ❄1�7') buffer = await getBuffer(res.url) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Jangan jadiin bahan buat comli om'}) }) break case 'promote': client.updatePresence(from, Presence.composing) /*if (!isDaftar) return reply(mess.only.daftarB)*/ if (!isGroup) return reply(mess.only.group) if (!isGroupAdmins) return reply(mess.only.admin) if (!isBotGroupAdmins) return reply(mess.only.Badmin) if (mek.message.extendedTextMessage === undefined || mek.message.extendedTextMessage === null) return reply('Tag target yang ingin di promote!') mentioned = mek.message.extendedTextMessage.contextInfo.mentionedJid if (mentioned.length > 1) { teks = 'Perintah di terima, menambah jabatan sebagai admin :\n' for (let _ of mentioned) { teks += `@${_.split('@')[0]}\n` } mentions(teks, mentioned, true) client.groupMakeAdmin(from, mentioned) } else { mentions(`Agora ele : @${mentioned[0].split('@')[0]}é um Adm,respeitem ele 😳`, mentioned, true) client.groupMakeAdmin(from, mentioned) } break case 'randomhentaio': try { if (!isNsfw) return reply('❌ *NSFW Desativado* ❌') res = await fetchJson(`https://tobz-api.herokuapp.com/api/hentai?apikey=BotWeA`, {method: 'get'}) buffer = await getBuffer(res.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'hentai teros'}) } catch (e) { console.log(`Error :`, color(e,'red')) reply('❌ *ERROR* ❌') } break case 'nsfwloli': try { if (!isNsfw) return reply('❌ *NSFW Desativado* ❌') res = await fetchJson(`https://api.lolis.life/random?nsfw=true`, {method: 'get'}) buffer = await getBuffer(res.url) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Jangan jadiin bahan buat comli om'}) } catch (e) { console.log(`Error :`, color(e,'red')) reply('❌ *ERROR* ❌') } break case 'nsfwbobs': try { if (!isNsfw) return reply('❌ *NSFW Desativado* ❌') res = await fetchJson(`https://meme-api.herokuapp.com/gimme/biganimetiddies`, {method: 'get'}) buffer = await getBuffer(res.url) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Tai os peitos que vc queria\npunhetero de merda'}) } catch (e) { console.log(`Error :`, color(e,'red')) reply('❌ *ERROR* ❌') } break case 'nsfwblowjob': try { if (!isNsfw) return reply('❌ *NSFW Desativado* ❌') res = await fetchJson(`https://tobz-api.herokuapp.com/api/nsfwblowjob`, {method: 'get'}) buffer = await getBuffer(res.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Jangan jadiin bahan buat comli om'}) } catch (e) { console.log(`Error :`, color(e,'red')) reply('❌ *ERROR* ❌') } break case 'nsfwneko': try { if (!isNsfw) return reply('❌ *NSFW Desativado* ❌') res = await fetchJson(`https://api.computerfreaker.cf/v1/neko`, {method: 'get'}) buffer = await getBuffer(res.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'ni anjim'}) } catch (e) { console.log(`Error :`, color(e,'red')) reply('❌ *ERROR* ❌') } break case 'trap': try { if (!isNsfw) return reply('❌ *NSFW Desativado* ❌') res = await fetchJson(`https://api.computerfreaker.cf/v1/trap`, {method: 'get'}) buffer = await getBuffer(res.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'ni anjim'}) } catch (e) { console.log(`Error :`, color(e,'red')) reply('❌ *ERROR* ❌') } break case 'nsfwass': try { if (!isNsfw) return reply('❌ *NSFW Desativado* ❌') res = await fetchJson(`'https://meme-api.herokuapp.com/gimme/animebooty`, {method: 'get'}) buffer = await getBuffer(res.url) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Tai a bunda que vc queria'}) } catch (e) { console.log(`Error :`, color(e,'red')) reply('❌ *ERROR* ❌') } break case 'nsfwsidebobs': try { if (!isNsfw) return reply('❌ *NSFW Desativado* ❌') res = await fetchJson(`https://meme-api.herokuapp.com/gimme/sideoppai`, {method: 'get'}) buffer = await getBuffer(res.url) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'aaaah'}) } catch (e) { console.log(`Error :`, color(e,'red')) reply('❌ *ERROR* ❌') } break case 'nsfwahegao': try { if (!isNsfw) return reply('❌ *NSFW Desativado* ❌') res = await fetchJson(`https://meme-api.herokuapp.com/gimme/ahegao`, {method: 'get'}) buffer = await getBuffer(res.url) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'fodar'}) } catch (e) { console.log(`Error :`, color(e,'red')) reply('❌ *ERROR* ❌') } break case 'nsfwthighs': try { if (!isNsfw) return reply('❌ *NSFW Desativado* ❌') res = await fetchJson(`https://meme-api.herokuapp.com/gimme/animethighss`, {method: 'get'}) buffer = await getBuffer(res.url) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'aaah q bosta'}) } catch (e) { console.log(`Error :`, color(e,'red')) reply('❌ *ERROR* ❌') } break case 'nsfwfeets': try { if (!isNsfw) return reply('❌ *NSFW Desativado* ❌') res = await fetchJson(`https://meme-api.herokuapp.com/gimme/animefeets`, {method: 'get'}) buffer = await getBuffer(res.url) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Tai mais fia sapoha no cu'}) } catch (e) { console.log(`Error :`, color(e,'red')) reply('❌ *ERROR* ❌') } break case 'nsfwarmpits': try { if (!isNsfw) return reply('❌ *NSFW Desativado* ❌') res = await fetchJson(`https://meme-api.herokuapp.com/gimme/animearmpits`, {method: 'get'}) buffer = await getBuffer(res.url) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Tai'}) } catch (e) { console.log(`Error :`, color(e,'red')) reply('❌ *ERROR* ❌') } break case 'nsfwtrap': try { if (!isNsfw) return reply('❌ *NSFW Desativado* ❌') res = await fetchJson(`https://tobz-api.herokuapp.com/nsfwtrap?apikey=BotWeA`, {method: 'get'}) buffer = await getBuffer(res.url) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Tai os peitos que vc queria\npunhetero de merda'}) } catch (e) { console.log(`Error :`, color(e,'red')) reply('❌ *ERROR* ❌') } break case 'wa.me': case 'wame': client.updatePresence(from, Presence.composing) options = { text: `「 *SELF WHATSAPP* 」\n\n_Request by_ : *@${sender.split("@s.whatsapp.net")[0]}\n\nYour link WhatsApp : *https://wa.me/${sender.split("@s.whatsapp.net")[0]}*\n*Or ( / )*\n*https://api.whatsapp.com/send?phone=${sender.split("@")[0]}*`, contextInfo: { mentionedJid: [sender] } } client.sendMessage(from, options, text, { quoted: mek } ) break if (data.error) return reply(data.error) reply(data.result) break case 'quotes': client.updatePresence(from, Presence.composing) /*if (!isDaftar) return reply(mess.only.daftarB)*/ data = await fetchJson(`http://mhankbarbars.herokuapp.com/api/randomquotes`) ez = `*➸ Author :* ${data.author}\n*➸ Quotes :* ${data.quotes}` reply(ez) break case '3dtext': data = await await getBuffer(`https://docs-jojo.herokuapp.com/api/text3d?text=${body.slice(8)}`) /*if (!isDaftar) return reply(mess.only.daftarB)*/ client.sendMessage(from, data, image, {quoted: mek, caption: body.slice(8)}) break case 'fml': data = await fetchJson(`https://docs-jojo.herokuapp.com/api/fml`) /*if (!isDaftar) return reply(mess.only.daftarB)*/ hasil = data.result.fml reply(hasil) break case 'owner': case 'creator': client.sendMessage(from, {displayname: "Vitinn", vcard: vcard}, MessageType.contact, { quoted: mek}) client.sendMessage(from, 'Nih nomor ownerku kak, save ya kak nanti di save balik',MessageType.text, { quoted: mek} ) break case 'hidetag': client.updatePresence(from, Presence.composing) /*if (!isDaftar) return reply(mess.only.daftarB)*/ if (!isGroup) return reply(mess.only.group) teks = body.slice(9) group = await client.groupMetadata(from); member = group['participants'] jids = []; member.map( async adm => { jids.push(adm.id.replace('c.us', 's.whatsapp.net')); }) options = { text: teks, contextInfo: {mentionedJid: jids}, quoted: mek } break case "randomtag": const getRandomUser = await client.getGroupParticipantIDs() const randomizeIt = getRandomUser[Math.floor(Math.random() * getRandomUser.length)] await client.sendTextWithMentions(from, `@${randomizeIt.replace('@c.us', '')}`) break case 'nsfw': if (!isGroup) return reply(mess.only.group) if (!isGroupAdmins) return reply(mess.only.admin) if (args.length < 1) return reply('Hmmmm 1 para ativar 0 para desativar') if (Number(args[0]) === 1) { if (isNsfw) return reply('NSFW ja esta ativado') nsfw.push(from) fs.writeFileSync('./src/nsfw.json', JSON.stringify(nsfw)) reply('NSFW Ativado ✔️') } else if (Number(args[0]) === 0) { nsfw.splice(from, 1) fs.writeFileSync('./src/nsfw.json', JSON.stringify(nsfw)) reply('NSFW Desativado ✔️') } else { reply('1 para ativar 2 para desativar') } await client.sendMessage(from, options, text) break case 'tiktokstalk': try { if (args.length < 1) return client.sendMessage(from, 'Usernamenya mana kak? ', text, {quoted: mek}) /*if (!isDaftar) return reply(mess.only.daftarB)*/ let { user, stats } = await tiktod.getUserProfileInfo(args[0]) reply(mess.wait) teks = `*ID* : ${user.id}\n*Username* : ${user.uniqueId}\n*Nickname* : ${user.nickname}\n*Followers* : ${stats.followerCount}\n*Followings* : ${stats.followingCount}\n*Posts* : ${stats.videoCount}\n*Luv* : ${stats.heart}\n` buffer = await getBuffer(user.avatarLarger) client.sendMessage(from, buffer, image, {quoted: mek, caption: teks}) } catch (e) { console.log(`Error :`, color(e,'red')) reply('username tidak valid') } break case 'snowwrite': var gh = body.slice(11) var gbl7 = gh.split("|")[0]; var gbl8 = gh.split("|")[1]; if (args.length < 1) return reply(`Kirim perintah ${prefix}snowwrite teks1|teks2, contoh ${prefix}snowwrite aqulzz|galuh`) /*if (!isDaftar) return reply(mess.only.daftarB)*/ reply(mess.wait) anu = await fetchJson(`https://zeksapi.herokuapp.com/api/snowwrite?text1=${gbl7}&text2=${gbl8}&apikey=apivinz`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek}) break case 'marvellogo': var gh = body.slice(12) var gbl5 = gh.split("|")[0]; var gbl6 = gh.split("|")[1]; if (args.length < 1) return reply(`Kirim perintah ${prefix}marvellogo teks1|teks2, contoh ${prefix}marvellogo aqulzz|galuh`) /*if (!isDaftar) return reply(mess.only.daftarB)*/ reply(mess.wait) anu = await fetchJson(`https://zeksapi.herokuapp.com/api/marvellogo?text1=${gbl5}&text2=${gbl6}&apikey=apivinz`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek}) break case 'yuugo': anu = await fetchJson(`https://api.vhtear.com/pinterest?query=yuugoneverland&apikey=ANTIGRATISNIHANJENKKK`, {method: 'get'}) var eln = JSON.parse(JSON.stringify(anu.result)); var elnn = eln[Math.floor(Math.random() * eln.length)]; nye = await getBuffer(elnn) client.sendMessage(from, nye, image, { caption: 'elang!!', quoted: mek }) break case 'artinama': client.updatePresence(from, Presence.composing) /*if (!isDaftar) return reply(mess.only.daftarB)*/ data = await fetchJson(`https://arugaz.herokuapp.com/api/artinama?nama=${body.slice(10)}`) reply(data.result) break case 'infonomor': client.updatePresence(from, Presence.composing) /*if (!isDaftar) return reply(mess.only.daftarB)*/ if (args.length < 1) return reply(`Masukan Nomor\nContoh : ${prefix}infonomor 0812345678`) data = await fetchJson(`https://docs-jojo.herokuapp.com/api/infonomor?no=${body.slice(11)}`) if (data.error) return reply(data.error) if (data.result) return reply(data.result) hasil = `╠➥ internasional : ${data.international}\n╠➥ nomor : ${data.nomor}\n╠➥ operator : ${data.op}` reply(hasil) break case 'spamcall': client.updatePresence(from, Presence.composing) /*if (!isDaftar) return reply(mess.only.daftarB)*/ if (args.length < 1) return reply(`Masukan Nomor\nContoh : ${prefix}spamcall 812345678`) data = await fetchJson(`https://arugaz.herokuapp.com/api/spamcall?no=${body.slice(10)}`) if (data.msg) return reply(data.msg) hasil = data.logs reply(hasil) break case 'map': data = await fetchJson(`https://mnazria.herokuapp.com/api/maps?search=${body.slice(5)}`) /*if (!isDaftar) return reply(mess.only.daftarB)*/ hasil = await getBuffer(data.gambar) client.sendMessage(from, hasil, image, {quoted: mek, caption: `Hasil Dari *${body.slice(5)}*`}) break case 'covid': client.updatePresence(from, Presence.composing) /*if (!isDaftar) return reply(mess.only.daftarB)*/ data = await fetchJson(`https://arugaz.herokuapp.com/api/corona?country=${body.slice(7)}`) if (data.result) reply(data.result) hasil = `Negara : ${data.result.country}\n\nActive : ${data.result.active}\ncasesPerOneMillion : ${data.result.casesPerOneMillion}\ncritical : ${data.result.critical}\ndeathsPerOneMillion : ${data.result.deathsPerOneMillion}\nrecovered : ${data.result.recovered}\ntestPerOneMillion : ${data.result.testPerOneMillion}\ntodayCases : ${data.result.todayCases}\ntodayDeath : ${data.result.todayDeath}\ntotalCases : ${data.result.totalCases}\ntotalTest : ${data.result.totalTest}` reply(hasil) break case 'wiki': if (args.length < 1) return reply('masukan kata kunci') tels = body.slice(6) /*if (!isDaftar) return reply(mess.only.daftarB)*/ anu = await fetchJson(`https://tobz-api.herokuapp.com/api/wiki?q=${tels}&apikey=BotWeA`, {method: 'get'}) reply(anu.result) break case 'wikien': if (args.length < 1) return reply('masukan kata kunci') tels = body.slice(8) /*if (!isDaftar) return reply(mess.only.daftarB)*/ anu = await fetchJson(`https://arugaz.herokuapp.com/api/wikien?q=${tels}`, {method: 'get'}) reply(anu.result) break case 'ytmp3': if (args.length < 1) return reply('Urlnya mana um?') if(!isUrl(args[0]) && !args[0].includes('youtu')) return reply(mess.error.Iv) /*if (!isDaftar) return reply(mess.only.daftarB)*/ anu = await fetchJson(`https://tobz-api.herokuapp.com/api/yta?url=${args[0]}&apiKey=BotWeA`, {method: 'get'}) if (anu.error) return reply(anu.error) teks = `*Title* : ${anu.title}\n*Filesize* : ${anu.filesize}` thumb = await getBuffer(anu.thumb) client.sendMessage(from, thumb, image, {quoted: mek, caption: teks}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, audio, {mimetype: 'audio/mp4', filename: `${anu.title}.mp3`, quoted: mek}) break case 'ytmp4': if (args.length < 1) return reply('link YouTube nya mana?') tels = body.slice(7) reply(mess.wait) buffer = await getBuffer(anu.thumb) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/ytv?url=${tels}&apikey=BotWeA`, {method: 'get'}) /*if (!isDaftar) return reply(mess.only.daftarB)*/ hasil = `*❏ Judul* : ${anu.title}\n*❏ Filesize* : ${anu.filesize}\n*❏ resolution* : ${anu.resolution}\n*❏ Tipe* : ${anu.ext}\n*❏ Link* : ${anu.result}` client.sendMessage(from, buffer, image, {quoted: mek, caption: hasil}) break case 'trendtwit': client.updatePresence(from, Presence.composing) /*if (!isDaftar) return reply(mess.only.daftarB)*/ data = await fetchJson(`https://docs-jojo.herokuapp.com/api/trendingtwitter`, {method: 'get'}) teks = '=================\n' for (let i of data.result) { teks += `*Hastag* : ${i.hastag}\n*link* : ${i.link}\n*rank* : ${i.rank}\n*Tweet* : ${i.tweet}\n=================\n` } reply(teks.trim()) break case 'testime': setTimeout( () => { client.sendMessage(from, 'Waktu habis:v', text) // ur cods }, 10000) // 1000 = 1s, setTimeout( () => { client.sendMessage(from, '5 Detik lagi', text) // ur cods }, 5000) // 1000 = 1s, setTimeout( () => { client.sendMessage(from, '10 Detik lagi', text) // ur cods }, 0) // 1000 = 1s, break case 'semoji': if (args.length < 1) return reply('emojinya mana um?') /*if (!isDaftar) return reply(mess.only.daftarB)*/ ranp = getRandom('.png') rano = getRandom('.webp') teks = body.slice(8).trim() anu = await fetchJson(`https://mhankbarbars.herokuapp.com/api/emoji2png?emoji=${teks}`, {method: 'get'}) if (anu.error) return reply(anu.error) exec(`wget ${anu.result} -O ${ranp} && ffmpeg -i ${ranp} -vcodec libwebp -filter:v fps=fps=20 -lossless 1 -loop 0 -preset default -an -vsync 0 -s 512:512 ${rano}`, (err) => { fs.unlinkSync(ranp) if (err) return reply(mess.error.stick) buffer = fs.readFileSync(rano) client.sendMessage(from, buffer, sticker) fs.unlinkSync(rano) }) break case 'nulis': case 'tulis': ini if (args.length < 1) return reply('aku suruh nulis apa kak?') /*if (!isDaftar) return reply(mess.only.daftarB)*/ teks = body.slice(7) reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/nulis?text=halo&apikey=BotWeA`, {method: 'get'}) if (anu.error) return reply(anu.error) buff = await getBuffer(anu.result) client.sendMessage(from, buff, image, {quoted: mek, caption: mess.success}) break case 'kbbi': client.updatePresence(from, Presence.composing) if (args.length < 1) return reply(`Masukan Pertanyaan\nContoh : ${prefix}kbbi asu`) tels = body.slice(6) data = await fetchJson(`https://tobz-api.herokuapp.com/api/kbbi?kata=${tels}&apikey=BotWeA`) if (data.error) return reply(data.error) hasil = `${data.result}` reply(hasil) break case 'joox': tels = body.slice(6) data = await fetchJson(`https://tobz-api.herokuapp.com/api/joox?q=${tels}`, {method: 'get'}) /*if (!isDaftar) return reply(mess.only.daftarB)*/ if (data.error) return reply(data.error) infomp3 = `*Lagu Ditemukan!!!*\nJudul : ${data.result.judul}\nAlbum : ${data.result.album}\nDipublikasi : ${data.result.dipublikasi}` buffer = await getBuffer(data.result.thumb) lagu = await getBuffer(data.result.mp3) client.sendMessage(from, buffer, image, {quoted: mek, caption: infomp3}) client.sendMessage(from, lagu, audio, {mimetype: 'audio/mp4', filename: `${data.result.title}.mp3`, quoted: mek}) break case 'info': me = client.user uptime = process.uptime() teks = `*Nama bot* : ${me.name}\n*Nomor Bot* : @${me.jid.split('@')[0]}\n*Prefix* : ${prefix}\n*Total Block Contact* : ${blocked.length}\n*The bot is active on* : ${kyun(uptime)}\n*Total Chat* : ${totalchat.length}` buffer = await getBuffer(me.imgUrl) client.sendMessage(from, buffer, image, {caption: teks, contextInfo:{mentionedJid: [me.jid]}}) break case 'blocklist': teks = 'This is list of blocked number :\n' for (let block of blocked) { teks += `~> @${block.split('@')[0]}\n` } teks += `Total : ${blocked.length}` client.sendMessage(from, teks.trim(), extendedText, {quoted: mek, contextInfo: {"mentionedJid": blocked}}) break case 'chatlist': client.updatePresence(from, Presence.composing) teks = 'This is list of chat number :\n' for (let all of totalchat) { teks += `~> @${all}\n` } teks += `Total : ${totalchat.length}` client.sendMessage(from, teks.trim(), extendedText, {quoted: mek, contextInfo: {"mentionedJid": totalchat}}) break case 'animecry': ranp = getRandom('.gif') rano = getRandom('.webp') anu = await fetchJson('https://tobz-api.herokuapp.com/api/cry', {method: 'get'}) /*if (!isDaftar) return reply(mess.only.daftarB)*/ if (anu.error) return reply(anu.error) exec(`wget ${anu.result} -O ${ranp} && ffmpeg -i ${ranp} -vcodec libwebp -filter:v fps=fps=15 -lossless 1 -loop 0 -preset default -an -vsync 0 -s 512:512 ${rano}`, (err) => { fs.unlinkSync(ranp) if (err) return reply(mess.error.stick) buffer = fs.readFileSync(rano) client.sendMessage(from, buffer, sticker, {quoted: mek}) fs.unlinkSync(rano) }) break case 'neonime': client.updatePresence(from, Presence.composing) data = await fetchJson(`https://docs-jojo.herokuapp.com/api/neonime_lastest`, {method: 'get'}) /*if (!isDaftar) return reply(mess.only.daftarB)*/ teks = '################\n' for (let i of data.result) { teks += `*Title* : ${i.judul}\n*link* : ${i.link}\n*rilis* : ${i.rilis}\n###############\n` } reply(teks.trim()) break case 'bpink': if (args.length < 1) return reply(`Masukan Teks\nContoh : ${prefix}Caliph Bot`) data = await getBuffer(`https://docs-jojo.herokuapp.com/api/blackpink?text=${body.slice(7)}`) /*if (!isDaftar) return reply(mess.only.daftarB)*/ client.sendMessage(from, data, image, {quoted: mek, caption: body.slice(7)}) break case 'tts': client.updatePresence(from, Presence.recording) if (args.length < 1) return client.sendMessage(from, 'Kode bahasanya mana om?', text, {quoted: mek}) /*if (!isDaftar) return reply(mess.only.daftarB)*/ const gtts = require('./lib/gtts')(args[0]) if (args.length < 2) return client.sendMessage(from, 'Textnya mana om', text, {quoted: mek}) dtt = body.slice(8) ranm = getRandom('.mp3') rano = getRandom('.ogg') dtt.length > 600 ? reply('Textnya kebanyakan om') : gtts.save(ranm, dtt, function() { exec(`ffmpeg -i ${ranm} -ar 48000 -vn -c:a libopus ${rano}`, (err) => { fs.unlinkSync(ranm) buff = fs.readFileSync(rano) if (err) return reply('Gagal om:(') client.sendMessage(from, buff, audio, {quoted: mek, ptt:true}) fs.unlinkSync(rano) }) }) break case 'listadmins': case 'adminlist': client.updatePresence(from, Presence.composing) /*if (!isDaftar) return reply(mess.only.daftarB)*/ if (!isGroup) return reply(mess.only.group) teks = `List admin of group *${groupMetadata.subject}*\nTotal : ${groupAdmins.length}\n\n` no = 0 for (let admon of groupAdmins) { no += 1 teks += `[${no.toString()}] @${admon.split('@')[0]}\n` } mentions(teks, groupAdmins, true) break case 'pokemon': client.updatePresence(from, Presence.composing) data = await fetchJson(`https://api.fdci.se/rep.php?gambar=pokemon`, {method: 'get'}) /*if (!isDaftar) return reply(mess.only.daftarB)*/ reply(mess.wait) n = JSON.parse(JSON.stringify(data)); nimek = n[Math.floor(Math.random() * n.length)]; pok = await getBuffer(nimek) client.sendMessage(from, pok, image, { quoted: mek }) break case 'imagens': client.updatePresence(from, Presence.composing) data = await fetchJson( `https://api.fdci.se/rep.php?gambar=${search}`, {method: 'get'}) /*if (!isDaftar) return reply(mess.only.daftarB)*/ reply(mess.wait) n = JSON.parse(JSON.stringify(data)); nimek = n[Math.floor(Math.random() * n.length)]; pok = await getBuffer(nimek) client.sendMessage(from, pok, image, { quoted: mek, caption: `𝐏𝐈𝐍𝐓𝐄𝐑𝐄𝐒𝐓\n\*Hasil Pencarian* : *${body.slice(11)}*`}) break case 'images': client.updatePresence(from, Presence.composing) data = await fetchJson(`https://api.fdci.se/rep.php?gambar=${body.slice(11)}`, {method: 'get'}) /*if (!isDaftar) return reply(mess.only.daftarB)*/ reply(mess.wait) n = JSON.parse(JSON.stringify(data)); nimek = n[Math.floor(Math.random() * n.length)]; pok = await getBuffer(nimek) client.sendMessage(from, pok, image, { quoted: mek, caption: `Era sapoha q tu qria?\n\*Soq tae* : *${body.slice(11)}*`}) break case 'pinterest': client.updatePresence(from, Presence.composing) data = await fetchJson(`https://api.fdci.se/rep.php?gambar=${body.slice(11)}`, {method: 'get'}) if (!isUser) return reply(mess.only.daftarB) reply(mess.wait) n = JSON.parse(JSON.stringify(data)); nimek = n[Math.floor(Math.random() * n.length)]; pok = await getBuffer(nimek) client.sendMessage(from, pok, image, { quoted: mek, caption: `𝐏𝐈𝐍𝐓𝐄𝐑𝐄𝐒𝐓\n\*Era isso?* : *${body.slice(11)}*`}) break case 'animet': client.updatePresence(from, Presence.composing) data = await fetchJson(`https://arugaz.herokuapp.com/api/kuso?q=${body.slice(11)}`, {method: 'get'}) /*if (!isDaftar) return reply(mess.only.daftarB)*/ reply(mess.wait) n = JSON.parse(JSON.stringify(data)); nimek = n[Math.floor(Math.random() * n.length)]; pok = await getBuffer(nimek) client.sendMessage(from, pok, image, { quoted: mek, caption: `Era sapoha q tu qria?\n\*Soq tae* : *${body.slice(11)}*`}) break case 'randomanime': gatauda = body.slice(13) reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/randomanime`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: `Diria q uma imagem random de Anime`}) break case 'waifu': gatauda = body.slice(7) reply(mess.wait) anu = await fetchJson(`https://arugaz.herokuapp.com/api/nekonime`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image,{quoted: mek, caption: `Casar com 2d e fodar mais okei`}) break case 'walpaper': client.updatePresence(from, Presence.composing) data = await fetchJson(`https://api.fdci.se/rep.php?gambar=wallpaper`, {method: 'get'}) /*if (!isDaftar) return reply(mess.only.daftarB)*/ reply(mess.wait) n = JSON.parse(JSON.stringify(data)); nimek = n[Math.floor(Math.random() * n.length)]; pok = await getBuffer(nimek) client.sendMessage(from, pok, image, { quoted: mek }) break case 'twit': client.updatePresence(from, Presence.composing) data = await fetchJson(`https://api.fdci.se/rep.php?gambar=`, {method: 'get'}) /*if (!isDaftar) return reply(mess.only.daftarB)*/ reply(mess.wait) n = JSON.parse(JSON.stringify(data)); nimek = n[Math.floor(Math.random() * n.length)]; pok = await getBuffer(nimek) client.sendMessage(from, pok, image, { quoted: mek, caption: `Seu post random do tt`}) break case 'setprefix': client.updatePresence(from, Presence.composing) if (args.length < 1) return if (!isOwner) return reply(mess.only.ownerB) prefix = args[0] reply(`Prefix berhasil di ubah menjadi : ${prefix}`) break case 'meme': meme = await kagApi.memes() buffer = await getBuffer(`https://imgur.com/${meme.hash}.jpg`) client.sendMessage(from, buffer, image, {quoted: mek, caption: '.......'}) break case 'memeindo': memein = await kagApi.memeindo() buffer = await getBuffer(`https://imgur.com/${memein.hash}.jpg`) client.sendMessage(from, buffer, image, {quoted: mek, caption: '.......'}) break case 'block': client.updatePresence(from, Presence.composing) if (!isGroup) return reply(mess.only.group) if (!isOwner) return reply(mess.only.ownerB) client.blockUser (`${body.slice(8)}@c.us`, "add") client.sendMessage(from, `Membro bloqueado ${body.slice(8)}@c.us`, text) break case 'delete': case 'del': if (!isGroup)return reply(mess.only.group) if (!isGroupAdmins)return reply(mess.only.admin) client.deleteMessage(from, { id: mek.message.extendedTextMessage.contextInfo.stanzaId, remoteJid: from, fromMe: true }) break case 'hilih': client.updatePresence(from, Presence.composing) anu = await fetchJson(`https://mhankbarbars.herokuapp.com/api/hilih?teks=${body.slice(7)}`, {method: 'get'}) reply(anu.result) break case 'tagall': client.updatePresence(from, Presence.composing) if (!isGroup) return reply(mess.only.group) /*if (!isDaftar) return reply(mess.only.daftarB)*/ if (!isGroupAdmins) return reply(mess.only.admin) members_id = [] teks = (args.length > 1) ? body.slice(8).trim() : '' teks += ` Total : ${groupMembers.length}\n` for (let mem of groupMembers) { teks += `╠➥ @${mem.jid.split('@')[0]}\n` members_id.push(mem.jid) } if (text.includes('random')){ conn.sendMessage(id, 'Silakan ulangi command dengan huruf kecil',MessageType.text, { quoted: m } ); } if (text.includes("random")) { var items = ["ullzang girl", "cewe cantik", "cewe hijab", "remaja cantik", "cewek jepang"]; var cewe = items[Math.floor(Math.random() * items.length)]; var url = "https://api.fdci.se/rep.php?gambar=" + cewe; axios.get(url) .then((result) => { var b = JSON.parse(JSON.stringify(result.data)); var cewek = b[Math.floor(Math.random() * b.length)]; imageToBase64(cewek) // Path to the image .then( (response) => { conn.sendMessage(id, 'Jaja eu mando sabosta espera', MessageType.text, { quoted: m } ) var buf = Buffer.from(response, 'base64'); // Ta-da conn.sendMessage(id, buf ,MessageType.image, { caption: `nih gan`, quoted: m } ) } ) .catch( (error) => { console.log(error); // Logs an error if there was one } ) }); } if (text.includes('Bot')){ conn.sendMessage(id, 'Silakan ulangi command dengan huruf kecil\n_contoh : .bot apa kabar_',MessageType.text, { quoted: m } ); } if (text.includes("bot")){ const teks = text.replace(/.bot /, "") axios.get(`https://st4rz.herokuapp.com/api/simsimi?kata=${teks}`).then((res) => { let hasil = `${res.data.result}\n\n*Simsimi chat*`; conn.sendMessage(id, hasil ,MessageType.text, {quoted: m}); }) } mentions('╔══✪〘 Mencionando Todo Mundo! 〙✪══\n╠➥'+teks+'╚═〘 Vitinn Bot 〙', members_id, true) break case 'tagall2': client.updatePresence(from, Presence.composing) if (!isGroup) return reply(mess.only.group) if (!isGroupAdmins) return reply(mess.only.admin) members_id = [] teks = (args.length > 1) ? body.slice(8).trim() : '' teks += ` Total : ${groupMembers.length}\n` for (let mem of groupMembers) { teks += `╠➥ ${mem.jid.split('@')[0]}\n` members_id.push(mem.jid) } client.sendMessage(from, '╔══✪〘 Mencionando Todo Mundo! 〙✪══\n╠➥'+teks+'╚═〘 Vitinn Bot 〙', text, {quoted: mek}) break case 'tagall3': client.updatePresence(from, Presence.composing) if (!isGroup) return reply(mess.only.group) if (!isGroupAdmins) return reply(mess.only.admin) members_id = [] teks = (args.length > 1) ? body.slice(8).trim() : '' teks += ` Total : ${groupMembers.length}\n` for (let mem of groupMembers) { teks += `╠➥ https://wa.me/${mem.jid.split('@')[0]}\n` members_id.push(mem.jid) } client.sendMessage(from, '╔══✪〘 Mencionando Todo Mundo! 〙✪══\n╠➥'+teks+'╚═〘 Vitinn BOT 〙', text, {detectLinks: false, quoted: mek}) break case 'tagall4': client.updatePresence(from, Presence.composing) if (!isGroup) return reply(mess.only.group) if (!isGroupAdmins) return reply(mess.only.admin) members_id = [] teks = (args.length > 1) ? body.slice(8).trim() : '' teks += ` Total : ${groupMembers.length}\n` for (let mem of groupMembers) { teks += `╠➥ ${mem.jid.split('@')[0]}@c.us\n` members_id.push(mem.jid) } client.sendMessage(from, '╔══✪〘 Mencionando Todo Mundo! 〙✪══\n╠➥'+teks+'╚═〘 Vitinn BOT 〙', text, {quoted: mek}) break case 'tagall5': client.updatePresence(from, Presence.composing) if (!isGroup) return reply(mess.only.group) if (!isGroupAdmins) return reply(mess.only.admin) members_id = [] teks = (args.length > 1) ? body.slice(8).trim() : '' teks += ` Total : ${groupMembers.length}\n` for (let mem of groupMembers) { teks += `╠➥ ${mem.jid.split('@')[0]}@s.whatsapp.net\n` members_id.push(mem.jid) } reply('╔══✪〘 Mencionando Todo Mundo 〙✪══\n╠➥'+teks+'╚═〘 Vitinn BOT 〙') break case 'send': var pc = body.slice(6) var nomor = pc.split("|")[0]; var pesan = pc.split("|")[1]; client.sendMessage(nomor+'@s.whatsapp.net', pesan, text) break case 'quotesnime': nimek = await fetchJson('https://animechanapi.xyz/api/quotes/random') hasil = `anime : ${nimek.data.anime}\nCharacter : ${nimek.data.character}\n${nimek.data.quote}` reply(hasil) break case 'setppbot': client.updatePresence(from, Presence.composing) if (!isQuotedImage) return reply(`Kirim gambar dengan caption ${prefix}setbotpp atau tag gambar yang sudah dikirim`) if (!isOwner) return reply(mess.only.ownerB) enmedia = JSON.parse(JSON.stringify(mek).replace('quotedM','m')).message.extendedTextMessage.contextInfo media = await client.downloadAndSaveMediaMessage(enmedia) await client.updateProfilePicture(botNumber, media) reply('Makasih profil barunya😗') break case 'bc': client.updatePresence(from, Presence.composing) if (!isOwner) return reply(mess.only.ownerB) if (args.length < 1) return reply('.......') anu = await client.chats.all() if (isMedia && !mek.message.videoMessage || isQuotedImage) { const encmedia = isQuotedImage ? JSON.parse(JSON.stringify(mek).replace('quotedM','m')).message.extendedTextMessage.contextInfo : mek buff = await client.downloadMediaMessage(encmedia) for (let _ of anu) { client.sendMessage(_.jid, buff, image, {caption: `*「 BROADCAST 」*\n\n${body.slice(4)}`}) } reply('') } else { for (let _ of anu) { sendMess(_.jid, `*「 BROADCAST 」*\n\n${body.slice(4)}`) } reply('Sucesso Enviado Para Todos') } break case 'bcgc': client.updatePresence(from, Presence.composing) if (!isOwner) return reply(mess.only.ownerB) if (args.length < 1) return reply('.......') if (isMedia && !mek.message.videoMessage || isQuotedImage) { const encmedia = isQuotedImage ? JSON.parse(JSON.stringify(mek).replace('quotedM','m')).message.extendedTextMessage.contextInfo : mek buff = await client.downloadMediaMessage(encmedia) for (let _ of groupMembers) { client.sendMessage(_.jid, buff, image, {caption: `*「 BC GROUP 」*\n*Group* : ${groupName}\n\n${body.slice(6)}`}) } reply('') } else { for (let _ of groupMembers) { sendMess(_.jid, `*「 BC GROUP 」*\n*Group* : ${groupName}\n\n${body.slice(6)}`) } reply('Suksess broadcast group') } break case 'simi': if (args.length < 1) return reply('Textnya mana um?') teks = body.slice(5) anu = await simih(teks) //fetchJson(`https://mhankbarbars.herokuapp.com/api/samisami?text=${teks}`, {method: 'get'}) //if (anu.error) return reply('Simi ga tau kak') reply(anu) break case 'simih': if (!isGroup) return reply(mess.only.group) if (!isGroupAdmins) return reply(mess.only.admin) if (args.length < 1) return reply('Hmmmm') if (Number(args[0]) === 1) { if (isSimi) return reply('Simi Ativado') samih.push(from) fs.writeFileSync('./src/simi.json', JSON.stringify(samih)) reply('Simi Ativado Neste Grupo ✔️') } else if (Number(args[0]) === 0) { samih.splice(from, 1) fs.writeFileSync('./src/simi.json', JSON.stringify(samih)) reply('Simi Desativado Neste Grupo ✔️') } else { reply('1 para ativar, 0 para desativar') } break case 'alay': client.updatePresence(from, Presence.composing) /*if (!isDaftar) return reply(mess.only.daftarB)*/ data = await fetchJson(`https://arugaz.herokuapp.com/api/bapakfont?kata=${body.slice(6)}`) reply(data.result) break case 'quotemaker': gh = body.slice(12) /*if (!isDaftar) return reply(mess.only.daftarB)*/ teks1 = gh.split("|")[0]; teks2 = gh.split("|")[1]; teks3 = gh.split("|")[2] data = await fetchJson(`https://terhambar.com/aw/qts/?kata=${teks1}&author=${teks2}&tipe=${teks3}`) hasil = await getBuffer(data.result) client.sendMessage(from, hasil, image, {quoted: mek, caption: 'neh...'}) break case 'glitch': gh = body.slice(8) /*if (!isDaftar) return reply(mess.only.daftarB)*/ teks1 = gh.split("|")[0]; teks2 = gh.split("|")[1]; data = await fetchJson(`https://tobz-api.herokuapp.com/api/textpro?theme=glitch&text1=${teks1}&text2=${teks2}&apikey=BotWeA`) hasil = await getBuffer(data.result) client.sendMessage(from, hasil, image, {quoted: mek, caption: 'neh...'}) break case 'leave': if (!isGroup) return reply(mess.only.group) if (!isGroupAdmins) return reply(mess.only.admin) setTimeout( () => { client.groupLeave (from) }, 2000) setTimeout( () => { client.updatePresence(from, Presence.composing) client.sendMessage(from, 'Sayonara👋', text) // ur cods }, 0) break case 'chord': if (args.length < 1) return reply('judul lagunya mana kak') /*if (!isDaftar) return reply(mess.only.daftarB)*/ tels = body.slice(7) anu = await fetchJson(`https://arugaz.herokuapp.com/api/chord?q=${tels}`, {method: 'get'}) reply(anu.result) break case 'lirik': if (args.length < 1) return reply('Lirik lagunya mana kak?') /*if (!isDaftar) return reply(mess.only.daftarB)*/ tels = body.slice(7) anu = await fetchJson(`https://arugaz.herokuapp.com/api/lirik?judul=${tels}`, {method: 'get'}) reply(anu.result) break case 'igstalk': hmm = await fetchJson(`https://freerestapi.herokuapp.com/api/v1/igs?u=${body.slice(9)}`) buffer = await getBuffer(hmm.data.profilehd) hasil = `Fullname : ${hmm.data.fullname}\npengikut : ${hmm.data.follower}\nMengikuti : ${hmm.data.following}\nPrivate : ${hmm.data.private}\nVerified : ${hmm.data.verified}\nbio : ${hmm.data.bio}` client.sendMessage(from, buffer, image, {quoted: mek, caption: hasil}) break case 'ownergrup': case 'ownergroup': client.updatePresence(from, Presence.composing) options = { text: `Dono do grupo e o : @${from.split("-")[0]}`, contextInfo: { mentionedJid: [from] } } client.sendMessage(from, options, text, { quoted: mek } ) break case 'quran': anu = await fetchJson(`https://api.banghasan.com/quran/format/json/acak`, {method: 'get'}) quran = `${anu.acak.ar.teks}\n\n${anu.acak.id.teks}\nQ.S ${anu.surat.nama} ayat ${anu.acak.id.ayat}` client.sendMessage(from, quran, text, {quoted: mek}) break case 'nekonime': data = await fetchJson('https://waifu.pics/api/sfw/neko') /*if (!isDaftar) return reply(mess.only.daftarB)*/ hasil = await getBuffer(data.url) client.sendMessage(from, hasil, image, {quoted: mek}) break case 'neko': gatauda = body.slice(6) reply(mess.wait) anu = await fetchJson(`https://arugaz.herokuapp.com/api/nekonime`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek}) break case 'lolihentai': gatauda = body.slice(6) reply(mess.wait) anu = await fetchJson(`https://api.lolis.life/random?nsfw=true`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek}) break case 'add': client.updatePresence(from, Presence.composing) if (!isGroup) return reply(mess.only.group) if (!isGroupAdmins) return reply(mess.only.admin) if (!isBotGroupAdmins) return reply(mess.only.Badmin) if (args.length < 1) return reply('Yang mau di add jin ya?') if (args[0].startsWith('08')) return reply('Gunakan kode negara mas') try { num = `${args[0].replace(/ /g, '')}@s.whatsapp.net` client.groupAdd(from, [num]) } catch (e) { console.log('Error :', e) reply('Gagal menambahkan target, mungkin karena di private') } break case 'kick': client.updatePresence(from, Presence.composing) if (!isGroup) return reply(mess.only.group) if (!isGroupAdmins) return reply(mess.only.admin) if (!isBotGroupAdmins) return reply(mess.only.Badmin) if (mek.message.extendedTextMessage === undefined || mek.message.extendedTextMessage === null) return reply('Tag target yang ingin di tendang!') mentioned = mek.message.extendedTextMessage.contextInfo.mentionedJid if (mentioned.length > 1) { teks = 'Perintah di terima, mengeluarkan :\n' for (let _ of mentioned) { teks += `@${_.split('@')[0]}\n` } mentions(teks, mentioned, true) client.groupRemove(from, mentioned) } else { mentions(`Perintah di terima, mengeluarkan : @${mentioned[0].split('@')[0]}`, mentioned, true) client.groupRemove(from, mentioned) client.sendMessage(mentioned, 'yahaha Lu kekick😂', text) } break case 'exe': client.updatePresence(from, Presence.composing) if (!isOwner) return reply(mess.only.ownerB) const cmd = body.slice(5) exec(cmd, (err, stdout) => { if(err) return client.sendMessage(from, "Command Salah", text, { quoted: mek }) if (stdout) { client.sendMessage(from, stdout, text, { quoted: mek }) } }) break case 'linkgroup': case 'linkgrup': case 'linkgc': client.updatePresence(from, Presence.composing) if (!isGroup) return reply(mess.only.group) /*if (!isDaftar) return reply(mess.only.daftarB)*/ if (!isBotGroupAdmins) return reply(mess.only.Badmin) linkgc = await client.groupInviteCode (from) yeh = `https://chat.whatsapp.com/${linkgc}\n\nLink Group *${groupName}*` client.sendMessage(from, yeh, text, {quoted: mek, detectLinks: false}) break case 'qrcode': buff = await getBuffer(`https://api.qrserver.com/v1/create-qr-code/?data=${body.slice(8)}&size=1080%C3%971080`) client.sendMessage(from, buff, image, {quoted: mek}) break case 'ocr': if ((isMedia && !mek.message.videoMessage || isQuotedImage) && args.length == 0) { const encmedia = isQuotedImage ? JSON.parse(JSON.stringify(mek).replace('quotedM','m')).message.extendedTextMessage.contextInfo : mek const media = await client.downloadAndSaveMediaMessage(encmedia) reply(mess.wait) await recognize(media, {lang: 'eng+ind', oem: 1, psm: 3}) .then(teks => { reply(teks.trim()) fs.unlinkSync(media) }) .catch(err => { reply(err.message) fs.unlinkSync(media) }) } else { reply('Foto aja mas') } break case 'bugreport': client.updatePresence(from, Presence.composing) if (args.length < 1) return reply('Bugnya apa kak?') tek = body.slice(10) bug = { text: `*[BUG REPORT]*\n\n*Pengirim :* @${sender.split("@")[0]}\n*Pada Jam :* ${time}\n*Pesan :* ${tek}`, contextInfo: { mentionedJid: [sender] } } client.sendMessage(nomorOwner, bug, text, {quoted: mek}) client.sendMessage(from, 'Laporan mu telah dikirim ke owner BOT, laporan palsu/main2 tidak akan ditanggapi.', text, {quoted: mek}) break case 'apakah': client.updatePresence(from, Presence.composing) random = apakah[Math.floor(Math.random() * (apakah.length))] hasil = `Pertanyaan : *${body.slice(1)}*\n\nJawaban : *${random}*` reply(hasil) break case 'bisakah': client.updatePresence(from, Presence.composing) /*if (!isDaftar) return reply(mess.only.daftarB)*/ random = bisakah[Math.floor(Math.random() * (bisakah.length))] hasil = `Pertanyaan : *${body.slice(1)}*\n\nJawaban : *${random}*` reply(hasil) break case 'rate': client.updatePresence(from, Presence.composing) /*if (!isDaftar) return reply(mess.only.daftarB)*/ random = `${Math.floor(Math.random() * 100)}` hasil = `Pertanyaan : *${body.slice(1)}*\n\nJawaban : *${random}%*` reply(hasil) break case 'kapankah': client.updatePresence(from, Presence.composing) /*if (!isDaftar) return reply(mess.only.daftarB)*/ random = kapankah[Math.floor(Math.random() * (kapankah.length))] random2 = `${Math.floor(Math.random() * 8)}` hasil = `Pertanyaan : *${body.slice(1)}*\n\nJawaban : *${random2} ${random}*` reply(hasil) break case 'closegc': client.updatePresence(from, Presence.composing) if (!isGroup) return reply(mess.only.group) if (!isGroupAdmins) return reply(mess.only.admin) if (!isBotGroupAdmins) return reply(mess.only.Badmin) var nomor = mek.participant const close = { text: `Grup ditutup oleh admin @${nomor.split("@s.whatsapp.net")[0]}\nsekarang *hanya admin* yang dapat mengirim pesan`, contextInfo: { mentionedJid: [nomor] } } client.groupSettingChange (from, GroupSettingChange.messageSend, true); reply(close) break case 'opengc': case 'bukagc': client.updatePresence(from, Presence.composing) if (!isGroup) return reply(mess.only.group) if (!isGroupAdmins) return reply(mess.only.admin) if (!isBotGroupAdmins) return reply(mess.only.Badmin) open = { text: `Grup dibuka oleh admin @${sender.split("@")[0]}\nsekarang *semua peserta* dapat mengirim pesan`, contextInfo: { mentionedJid: [sender] } } client.groupSettingChange (from, GroupSettingChange.messageSend, false) client.sendMessage(from, open, text, {quoted: mek}) break case 'stiker': case 'sticker': case 'stickergif': case 'stikergif': if ((isMedia && !mek.message.videoMessage || isQuotedImage) && args.length == 0) { const encmedia = isQuotedImage ? JSON.parse(JSON.stringify(mek).replace('quotedM','m')).message.extendedTextMessage.contextInfo : mek const media = await client.downloadAndSaveMediaMessage(encmedia) /*if (!isDaftar) return reply(mess.only.daftarB)*/ ran = getRandom('.webp') await ffmpeg(`./${media}`) .input(media) .on('start', function (cmd) { console.log(`Started : ${cmd}`) }) .on('error', function (err) { console.log(`Error : ${err}`) fs.unlinkSync(media) reply(mess.error.stick) }) .on('end', function () { console.log('Finish') client.sendMessage(from, fs.readFileSync(ran), sticker, {quoted: mek}) fs.unlinkSync(media) fs.unlinkSync(ran) }) .addOutputOptions([`-vcodec`,`libwebp`,`-vf`,`scale='min(320,iw)':min'(320,ih)':force_original_aspect_ratio=decrease,fps=15, pad=320:320:-1:-1:color=white@0.0, split [a][b]; [a] palettegen=reserve_transparent=on:transparency_color=ffffff [p]; [b][p] paletteuse`]) .toFormat('webp') .save(ran) } else if ((isMedia && mek.message.videoMessage.seconds < 11 || isQuotedVideo && mek.message.extendedTextMessage.contextInfo.quotedMessage.videoMessage.seconds < 11) && args.length == 0) { const encmedia = isQuotedVideo ? JSON.parse(JSON.stringify(mek).replace('quotedM','m')).message.extendedTextMessage.contextInfo : mek const media = await client.downloadAndSaveMediaMessage(encmedia) ran = getRandom('.webp') reply(mess.wait) await ffmpeg(`./${media}`) .inputFormat(media.split('.')[1]) .on('start', function (cmd) { console.log(`Started : ${cmd}`) }) .on('error', function (err) { console.log(`Error : ${err}`) fs.unlinkSync(media) tipe = media.endsWith('.mp4') ? 'video' : 'gif' reply(`❌ Gagal, pada saat mengkonversi ${tipe} ke stiker`) }) .on('end', function () { console.log('Finish') buff = fs.readFileSync(ran) client.sendMessage(from, buff, sticker) fs.unlinkSync(media) fs.unlinkSync(ran) }) .addOutputOptions([`-vcodec`,`libwebp`,`-vf`,`scale='min(320,iw)':min'(320,ih)':force_original_aspect_ratio=decrease,fps=15, pad=320:320:-1:-1:color=white@0.0, split [a][b]; [a] palettegen=reserve_transparent=on:transparency_color=ffffff [p]; [b][p] paletteuse`]) .toFormat('webp') .save(ran) } break case 'animehug': ranp = getRandom('.gif') rano = getRandom('.webp') anu = await fetchJson('https://tobz-api.herokuapp.com/api/hug&apikey=BotWeA', {method: 'get'}) /*if (!isDaftar) return reply(mess.only.daftarB)*/ if (anu.error) return reply(anu.error) exec(`wget ${anu.result} -O ${ranp} && ffmpeg -i ${ranp} -vcodec libwebp -filter:v fps=fps=15 -lossless 1 -loop 0 -preset default -an -vsync 0 -s 512:512 ${rano}`, (err) => { fs.unlinkSync(ranp) if (err) return reply(mess.error.stick) buffer = fs.readFileSync(rano) client.sendMessage(from, buffer, sticker, {quoted: mek}) fs.unlinkSync(rano) }) break case 'toimg': client.updatePresence(from, Presence.composing) /*if (!isDaftar) return reply(mess.only.daftarB)*/ if (!isQuotedSticker) return reply('❌ reply stickernya um ❌') reply(mess.wait) encmedia = JSON.parse(JSON.stringify(mek).replace('quotedM','m')).message.extendedTextMessage.contextInfo media = await client.downloadAndSaveMediaMessage(encmedia) ran = getRandom('.png') exec(`ffmpeg -i ${media} ${ran}`, (err) => { fs.unlinkSync(media) if (err) return reply('❌ Gagal, pada saat mengkonversi sticker ke gambar ❌') buffer = fs.readFileSync(ran) client.sendMessage(from, buffer, image, {quoted: mek, caption: '>//<'}) fs.unlinkSync(ran) }) break case 'tomp3': client.updatePresence(from, Presence.composing) /*if (!isDaftar) return reply(mess.only.daftarB)*/ if (!isQuotedVideo) return reply('❌ reply videonya um ❌') reply(mess.wait) encmedia = JSON.parse(JSON.stringify(mek).replace('quotedM','m')).message.extendedTextMessage.contextInfo media = await client.downloadAndSaveMediaMessage(encmedia) ran = getRandom('.mp4') exec(`ffmpeg -i ${media} ${ran}`, (err) => { fs.unlinkSync(media) if (err) return reply('❌ Gagal, pada saat mengkonversi video ke mp3 ❌') buffer = fs.readFileSync(ran) client.sendMessage(from, buffer, audio, {mimetype: 'audio/mp4', quoted: mek}) fs.unlinkSync(ran) }) break case 'ninjalogo': if (args.length < 1) return reply('Teks nya mana?') /*if (!isDaftar) return reply(mess.only.daftarB)*/ gh = body.slice(11) gl1 = gh.split("|")[0]; gl2 = gh.split("|")[1]; reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/textpro?theme=ninjalogo&text1=${gl1}&text2=${gl2}`, {method: 'get'}) buff = await getBuffer(anu.result) client.sendMessage(from, buff, image, {quoted: mek}) break case 'play': reply(mess.wait) anu = await fetchJson(`https://api.vhtear.com/ytmp3?query=${body.slice(6)}&apikey=yourapikey`) /*if (!isDaftar) return reply(mess.only.daftarB)*/ if (anu.error) return reply(anu.error) infomp3 = `*Lagu Ditemukan!!!*\nJudul : ${anu.result.title}\nDurasi : ${anu.result.duration}\nUkuran : ${anu.result.size}\n\n*TUNGGU SEBENTAR LAGI DIKIRIM MOHON JANGAN SPAM YA SAYANG*` buffer = await getBuffer(anu.result.thumb) lagu = await getBuffer(anu.result.mp3) client.sendMessage(from, buffer, image, {quoted: mek, caption: infomp3}) client.sendMessage(from, lagu, audio, {mimetype: 'audio/mp4', filename: `${anu.title}.mp3`, quoted: mek}) break case 'joox2': reply(mess.wait) data = await fetchJson(`https://tobz-api.herokuapp.com/api/joox?q=${body.slice(6)}&apikey=BotWeA`, {method: 'get'}) if (data.error) return reply(data.error) infomp3 = `*Lagu Ditemukan!!!*\nJudul : ${data.result.judul}\nAlbum : ${data.result.album}\nDipublikasi : ${data.result.dipublikasi}\n*Filesize* : ${data.filesize}\n*TUNGGU SEBENTAR LAGI DIKIRIM MOHON JANGAN SPAM*` buffer = await getBuffer(data.result.thumb) lagu = await getBuffer(data.result.mp3) client.sendMessage(from, buffer, image, {quoted: mek, caption: infomp3}) client.sendMessage(from, lagu, audio, {mimetype: 'audio/mp4', filename: `${data.result.title}.mp3`, quoted: mek}) break case 'infocuaca': anu = await fetchJson(`http://tobz-cuaca.herokuapp.com/?menu=cuaca&wilayah=${body.slice(6)}&apiKey=SLpvUgOcMYwIx0pFeELt`, {method: 'get'}) /*if (!isDaftar) return reply(mess.only.daftarB)*/ if (anu.error) return reply(anu.error) hasil = ` *Tempat : ${anu.tempat}\nCuaca : ${anu.cuaca}\nAngin : ${anu.angin}\nSuhu : ${anu.suhu}\nKelembapan : ${anu.kelembapan}` client.sendMessage(from, hasil, text, {quoted: mek}) break case 'game': anu = await fetchJson(`http://rt-files.000webhostapp.com/tts.php?apikey=rasitech`, {method: 'get'}) /*if (!isDaftar) return reply(mess.only.daftarB)*/ setTimeout( () => { client.sendMessage(from, '*➸ Jawaban :* '+anu.result.jawaban+'\n'+anu.result.desk, text, {quoted: mek}) // ur cods }, 30000) // 1000 = 1s, setTimeout( () => { client.sendMessage(from, '_10 Detik lagi…_', text) // ur cods }, 20000) // 1000 = 1s, setTimeout( () => { client.sendMessage(from, '_20 Detik lagi_…', text) // ur cods }, 10000) // 1000 = 1s, setTimeout( () => { client.sendMessage(from, '_30 Detik lagi_…', text) // ur cods }, 1000) // 1000 = 1s, setTimeout( () => { client.sendMessage(from, anu.result.soal, text, { quoted: mek }) // ur cods }, 0) // 1000 = 1s, break case 'level': if (!isLevelingOn) return reply(mess.levelnoton) if (!isGroup) return reply(mess.only.group) const userLevel = getLevelingLevel(sender) const userXp = getLevelingXp(sender) if (userLevel === undefined && userXp === undefined) return reply(mess.levelnol) sem = sender.replace('@s.whatsapp.net','') resul = `◪ *LEVEL*\n ├─ ❏ *Nome* : ${sem}\n ├─ ❏ *XP do usuario* : ${userXp}\n └─ ❏ *Level do usuario* : ${userLevel}` client.sendMessage(from, resul, text, { quoted: mek}) .catch(async (err) => { console.error(err) await reply(`Error!\n${err}`) }) break case 'fitnah': case 'fake': if (!isGroup) return reply(mess.only.group) arg = body.substring(body.indexOf(' ') + 1) isi = arg.split(' |')[0] pesan = arg.split('|')[1] pesan2 = arg.split('|')[2] reply(pesan, isi, pesan2) break case 'leveling': if (!isGroup) return reply(mess.only.group) if (!isGroupAdmins) return reply(mess.only.admin) if (args.length < 1) return reply('Digite 1 para ativar o recurso') if (args[0] === '1') { if (isLevelingOn) return reply('*O recurso de level ja esta ativado*') _leveling.push(groupId) fs.writeFileSync('./database/group/leveling.json', JSON.stringify(_leveling)) reply(mess.levelon) } else if (args[0] === '0') { _leveling.splice(groupId, 1) fs.writeFileSync('./database/group/leveling.json', JSON.stringify(_leveling)) reply(mess.leveloff) } else { reply(` *1 para ativar, 0 para desativar* \n *Exemplo: ${prefix}leveling 1* `) } break case 'ping': await client.sendMessage(from, `Pong!!!\nSpeed: ${processTime(time, moment())} _Second_`) break case 'neonlogo': var gh = body.slice(9) var teks1 = gh.split("|")[0]; if (args.length < 1) return reply('teksnya mana um\nContoh: ${prefix}neonlogo NazwaCanss') reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/textpro?theme=neon_light&text=${teks1}&apikey=BotWeA`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Nih kak logonya...'}) break case 'neonlogo2': var gh = body.slice(9) teks1 = gh.split("|")[0]; if (args.length < 1) return reply('teksnya mana um\nContoh: ${prefix}neonlogo2 NazwaCanss') reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/textpro?theme=neon_technology&text=${text1}&apikey=BotWeA`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Nih kak logonya...'}) break case 'lionlogo': var gh = body.slice(11) var teks1 = gh.split("|")[0]; var teks2 = gh.split("|")[1]; if (args.length < 1) return reply('teksnya mana um\nContoh: ${prefix}lionlogo Nazwa|Canss') reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/textpro?theme=lionlogo&text1=${text1}&text2=${teks2}&apikey=BotWeA`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Nih kak logonya...'}) break /*case 'jsholat': tels = body.slice(8) if (args.length < 1) return reply('Daerahnya dimana kak?') anu = await fetchJson(`https://tobz-api.herokuapp.com/api/jadwalshalat?q=${tels}&apikey=BotWeA`, {method: 'get'}) reply(anu.result) break*/ case 'jokerlogo': var gh = body.slice(11) var teks1 = gh.split("|")[0]; if (args.length < 1) return reply('teksnya mana um\nContoh: ${prefix}jokerlogo NazwaCanss') reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/textpro?theme=jokerlogo&text=${teks1}&apikey=BotWeA`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Nih kak logonya...'}) break case 'coffee': var gh = body.slice(7) var teks1 = gh.split("|")[0]; if (args.length < 1) return reply(`Digite Assim\nExemplo: ${prefix}coffee Toin`) reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/photooxy?theme=coffee&text=${teks1}&apikey=BotWeA`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Eh...'}) break case 'jadwaltvnow': reply(mess.wait) anu = await fetchJson(`http://api-melodicxt.herokuapp.com/api/jadwaltvnow?&apiKey=administrator`, {method: 'get'}) reply(anu.result.jadwalTV) break case 'afk': tels = body.slice(4) if (args.length < 1) return reply('por que?') var nom = mek.participant const tag = { text: `@${nom.split("@s.whatsapp.net")[0]} *TO AFK ${tels} NAUM PERTUBEM*`, contextInfo: { mentionedJid: [nom] } } client.sendMessage(from, tag, text, {quoted: mek}) break case 'shadow': var gh = body.slice(7) var teks1 = gh.split("|")[0]; if (args.length < 1) return reply(`Digite Assim\nExemplo: ${prefix}shadow Toin`) reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/photooxy?theme=shadow&text=${text1}&apikey=BotWeA`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Eh...'}) break case 'burnpaper': var gh = body.slice(10) var teks1 = gh.split("|")[0]; if (args.length < 1) return reply(`Digite Assim\nExemplo: ${prefix}burnpaper Toin`) reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/photooxy?theme=burn_paper&text=${teks1}&apikey=BotWeA`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Eh...'}) break case 'lovepaper': var gh = body.slice(10) var teks1 = gh.split("|")[0]; if (args.length < 1) return reply(`Digite Assim\nExemplo: ${prefix}lovepaper Toin`) reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/photooxy?theme=love_paper&text=${teks1}&apikey=BotWeA`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Eh...'}) break case 'woodblock': var gh = body.slice(10) var teks1 = gh.split("|")[0]; if (args.length < 1) return reply(`Digite Assim\nExemplo: ${prefix}woodblock Toin`) reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/photooxy?theme=wood_block&text=${teks1}&apikey=BotWeA`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Eh...'}) break case 'qowheart': var gh = body.slice(9) var teks1 = gh.split("|")[0]; if (args.length < 1) return reply(`Digite Assim\nExemplo: ${prefix}qowheart Toin`) reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/photooxy?theme=quote_on_wood_heart&text=${teks1}&apikey=BotWeA`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Eh...'}) break case 'mutgrass': var gh = body.slice(9) var teks1 = gh.split("|")[0]; if (args.length < 1) return reply(`Digite Assim\nExemplo: ${prefix}mutgrass Toin`) reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/photooxy?theme=message_under_the_grass&text=${teks1}&apikey=BotWeA`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Eh...'}) break case 'undergocean': var gh = body.slice(12) var teks1 = gh.split("|")[0]; if (args.length < 1) return reply(`Digite Assim\nExemplo: ${prefix}undergocean Toin`) reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/photooxy?theme=underwater_ocean&text=${teks1}&apikey=BotWeA`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Eh...'}) break case 'woodenboards': var gh = body.slice(13) var teks1 = gh.split("|")[0]; if (args.length < 1) return reply(`Digite Assim\nExemplo: ${prefix}woodenboards Toin`) reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/photooxy?theme=wooden_boards&text=${teks1}&apikey=BotWeA`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Eh...'}) break case 'wolfmetal': var gh = body.slice(10) var teks1 = gh.split("|")[0]; if (args.length < 1) return reply(`Digite Assim\nExemplo: ${prefix}wolfmetal Toin`) reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/photooxy?theme=wolf_metal&text=${teks1}&apikey=BotWeA`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Eh...'}) break case 'metalictglow': var gh = body.slice(14) var teks1 = gh.split("|")[0]; if (args.length < 1) return reply(`Digite Assim\nExemplo: ${prefix}metalictglow Toin`) reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/photooxy?theme=metalic_text_glow&text=${teks1}&apikey=BotWeA`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Eh...'}) break case '8bit': var gh = body.slice(5) var teks1 = gh.split("|")[0]; var teks2 = gh.split("|")[1]; if (args.length < 1) return reply(`Digite Assim\nExemplo: ${prefix}8bit Toin|Bot`) reply(mess.wait) anu = await fetchJson(`https://tobz-api.herokuapp.com/api/photooxy?theme=bit8&text1=${teks1}&text2=${teks2}&apikey=BotWeA`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek, caption: 'Eh...'}) break /*case 'daftar': client.updatePresence(from, Presence.composing) if (isDaftar) return reply('kamu sudah terdaftar') if (args.length < 1) return reply(`Parameter Salah\nCommand : ${prefix}daftar nama|umur\nContoh : ${prefix}daftar Caliph|12`) var reg = body.slice(8) var jeneng = reg.split("|")[0]; var umure = reg.split("|")[1]; user.push(sender) fs.writeFileSync('./src/daftar.json', JSON.stringify(user)) client.sendMessage(from, `\`\`\`Pendaftaran berhasil dengan SN: TM08GK8PPHBSJDH10J\`\`\`\n\n\`\`\`Pada ${date} ${time}\`\`\`\n\`\`\`[Nama]: ${jeneng}\`\`\`\n\`\`\`[Nomor]: wa.me/${sender.split("@")[0]}\`\`\`\n\`\`\`[Umur]: ${umure}\`\`\`\n\`\`\`Untuk menggunakan bot\`\`\`\n\`\`\`silahkan\`\`\`\n\`\`\`kirim ${prefix}help\`\`\`\n\`\`\`\nTotal Pengguna ${user.length}\`\`\``, text, {quoted: mek}) break*/ case 'welcome': if (!isGroup) return reply(mess.only.group) /*if (!isDaftar) return reply(mess.only.daftarB)*/ if (!isGroupAdmins) return reply(mess.only.Badmin) if (args.length < 1) return reply('ketik 1 untuk mengaktifkan') if (Number(args[0]) === 1) { if (isWelkom) return reply('fitur sudah aktif') welkom.push(from) fs.writeFileSync('./src/welkom.json', JSON.stringify(welkom)) reply('*❬ SUCESSO ❭* ativado o recurso de boas-vindas neste grupo') } else if (Number(args[0]) === 0) { welkom.splice(from, disable) fs.writeFileSync('./src/welkom.json', JSON.stringify(welkom)) reply('*❬ SUCESSO ❭* desativado o recurso de boas-vindas neste grupo') } else { reply('digite 1 para ativar, 0 para desativar o recurso') } break case 'fakta': fakta = body.slice(1) /*if (!isDaftar) return reply(mess.only.daftarB)*/ const fakta =['Massa bumi mencapai 5.972.190.000.000.000.000.000.000 kg. Mesekipun sedemikian berat, faktanya bumi memiliki kecepatan 107.281 km per jam untuk mengitari matahari. Cepat sekali, bukan?','Massa berat bumi didominasi debu-debu antariksa dan dapat berkurang akibat gas seperti hidrogen yang berkurang tiga kilogram setiap detiknya. Fakta unik ini menunjukkan bahwa bumi akan kehilangan 95 ribu ton massa setiap tahunnya','Pada 2018 populasi manusia diperkirakan mencapai 7,6 miliar orang. Meskipun bumi dipenuhi manusia, fakta unik mengungkapkan bahwa manusia tidak memengaruhi massa bumi. Hal ini dikarenakan manusia terbentuk dari atom dalam bentuk oksigen 65 persen, karbon 18,5 persen, dan hidrogen 9,5 persen.','bumi dipenuhi oleh 70 persen air sehingga kerap wajar jika bumi disebut dengan nama planet air. Lautan bumi yang paling dalam adalah Palung Mariana dengan kedalaman 10.994 meter di bawah air. Fakta unik dibalik Palung Mariana adalah jika kamu meletakkan Gunung Everest di sana, puncak tertingginya bahkan masih berada di bawah permukaan laut sejauh 1,6 kilometer!','Faktanya bumi yang manusia tinggali hanya satu persen bagian dari keseluruhan planet bumi. Fakta unik ini menunjukkan bahwa masih banyak bagian bumi yang memiliki misteri kehidupan. Tertarik melakukan penjelajahan untuk menguak misteri sekaligus fakta unik di bagian bumi lainnya','Terdapat sebuah kota di Rusia yang jalanannya tertata rapi dengan sebuah istana yang didesain seperti catur yang megah. Pembuatan pemukiman tersebut didalangi oleh presiden yang terobsesi dengan catur bernama Kirsan Ilyumzhinov.','Apakah kamu tahu fakta unik mengenai mozzarella yang dibuat dari susu kerbau dan bukan susu sapi? Sekitar 500 tahun yang lalu di Campania, Italia, mozzarella dibuat pertama kali menggunakan susu kerbau. Fakta unik dibalik penggunaan susu kerbau ini karena kandungan protein susu kerbau 10-11% lebih banyak daripada susu sapi.','Bali memiliki fakta unik karena memliki banyak hari libur yang disumbangkan oleh sejumlah hari raya besar keagamaan. Hampir setiap hari besar keagamaan ini setiap orang akan mendapatkan libur. Beberapa hai libur diantaranya adalah hari raya galungan, kuningan, nyepi, pagerwesi, saraswati, dan sejumlah upacara besar lainnya seperti piodalan (pujawali).','Ibukota Jakarta memiliki banyak pesona juga fakta unik yang mungkin belum kamu ketahui. Sebelum diberi nama Jakarta, Ibukota Indonesia ini telah memiliki beberapa kali perubahan nama. Nama Ibukota Indonesia sesuai urutan perubahannya diantaranya adalah Sunda Kelapa, Jayakarta, Batavia, Betawi, Jacatra, Jayakarta, dan Jakarta.','Pada tahun 1952 jendela pesawat didesain dalam bentuk persegi namun penggunaannya dinilai cacat sehingga tidak diterapkan kembali. Jendela yang bulat dirancang untuk menyiasati perbedaan tekanan udara dalam dan luar pesawat untuk menghindari kegagalan struktural yang dapat menyebabkan kecelakaan pesawat.','Makanan utama dari nyamuk jantan dan betina pada umumnya adalah nektar dan zat manis yang sebagian besar diperoleh dari tanaman. Namun nyamuk membutuhkan protein tambahan unuk bertelur yang bisa didapatkan dari manusia sedangkan nyamuk jantan tidak membutuhkan zat protein tambahan untuk bertelur.','Jembatan suramadu (surabaya-madura) adalah jembatan terpanjang di Asia Tenggara (5438 m).','Tertawa dan bahagia meningkatkan imun, terutama produksi sel-sel pembunuh alamiah yang membantu melindungi tubuh dari penyakit','Kecoa kentut setiap 15 menit dan terus mengeluarkan gas metana (kentut) selama 18 jam setelah kematian.','Mengoleskan jeruk nipis dapat mencerahkan bagian lutut / siku yang hitam.','Energi yang dihasilkan oleh angin ribut (topan) selama 10 menit lebih besar dibandingkan energi dari bom saat perang','Satu-satunya indera manusia yang tidak berfungsi saat tidur adalah indera penciuman.','Para astronot dilarang makan makanan berjenis kacang-kacangan sebelum pergi ke luar angkasa. Karena bisa menyebabkan mereka mudah kentut. Dan gas kentut sangat membahayakan bagi baju luar angkasa mereka.','Di AS saja, kucing membunuh miliaran hewan dalam kurun waktu setahun. Mereka bertanggung jawab atas kematian 1,4 - 73,7 miliar burung dan 6,9 - 20,7 miliar mamalia setiap tahun. Bukan hanya itu, sejauh ini mereka benar-benar memusnahkan total 33 spesies dari dunia.','Ikan hiu kehilangan gigi lebih dari 6000buah setiap tahun, dan gigi barunya tumbuh dalam waktu 24 jam.','Semut dapat mengangkat Beban 50 kali tubuhnya.','Mulut menghasilkan 1 liter ludah setiap hari.','Siput bisa tidur selama 3 tahun','Kecoak bisa hidup 9 hari tanpa kepala, dan akan mati karena kelaparan','Mata burung unta lebih besar dari otaknya'] const keh = fakta[Math.floor(Math.random() * fakta.length)] client.sendMessage(from, 'fakta : '+ keh, { quoted: mek }) break case 'water': if (args.length < 1) return reply(mess.blank) /*if (!isDaftar) return reply(mess.only.daftarB)*/ tels = body.slice(7) if (tels.length > 15) return reply('Teksnya kepanjangan, maksimal 20 karakter') reply(mess.wait) anu = await fetchJson(`https://zeksapi.herokuapp.com/api/tfire?text=${tels}&apikey=xptnbot352`, {method: 'get'}) buffer = await getBuffer(anu.result) client.sendMessage(from, buffer, image, {quoted: mek}) break case 'firetext': if (args.length < 1) return reply(mess.blank) /*if (!isDaftar) return reply(mess.only.daftarB)*/ tels = body.slice(7) if (tels.ength > 10) return reply('Teksnya kepanjangan, maksimal 9 karakter') reply(mess.wait) anu = await fetchJson(`https://zeksapi.herokuapp.com/api/tlight?text=${tels}&apikey=xptnbot352`, {method: 'get'}) buff = await getBuffer(anu.result) client.sendMessage(from, buff, image, {quoted: mek}) break case 'gantengcek': /*if (isDaftar) return reply(mess.only.daftarB)*/ ganteng = body.slice(1) const gan =['10','30','20','40','50','60','70','62','74','83','97','100','29','94','75','82','41','39'] const teng = gan[Math.floor(Math.random() * gan.length)] client.sendMessage(from, 'Pertanyaan : *'+ganteng+'*\n\nJawaban : '+ teng+'%', text, { quoted: mek }) break case 'cantikcek': /*if (isDaftar) return reply(mess.only.daftarB)*/ cantik = body.slice(1) const can =['10','30','20','40','50','60','70','62','74','83','97','100','29','94','75','82','41','39'] const tik = can[Math.floor(Math.random() * can.length)] client.sendMessage(from, 'Pertanyaan : *'+cantik+'*\n\nJawaban : '+ tik+'%', text, { quoted: mek }) break case 'watak': /*if (isDaftar) return reply(mess.only.daftarB)*/ watak = body.slice(1) const wa =['peny ayang','pem urah','Pem arah','Pem aaf','Pen urut','Ba ik','bap eran','Baik Hati','peny abar','Uw u','top deh, poko knya','Suka Memb antu'] const tak = wa[Math.floor(Math.random() * wa.length)] client.sendMessage(from, 'Pertanyaan : *'+watak+'*\n\nJawaban : '+ tak, text, { quoted: mek }) break case 'hobby': /*if (isDaftar) return reply(mess.only.daftarB)*/ hobby = body.slice(1) const hob =['Memasak','Membantu Atok','Mabar','Nobar','Sosmedtan','Membantu Orang lain','Nonton Anime','Nonton Drakor','Naik Motor','Nyanyi','Menari','Bertumbuk','Menggambar','Foto fotoan Ga jelas','Maen Game','Berbicara Sendiri'] const by = hob[Math.floor(Math.random() * hob.length)] client.sendMessage(from, 'Pertanyaan : *'+hobby+'*\n\nJawaban : '+ by, text, { quoted: mek }) break case 'wait': if ((isMedia && !mek.message.videoMessage || isQuotedImage) && args.length == 0) { /*if (!isDaftar) return reply(mess.only.daftarB)*/ reply(mess.wait) const encmedia = isQuotedImage ? JSON.parse(JSON.stringify(mek).replace('quotedM','m')).message.extendedTextMessage.contextInfo : mek media = await client.downloadMediaMessage(encmedia) await wait(media).then(res => { client.sendMessage(from, res.video, video, {quoted: mek, caption: res.teks.trim()}) }).catch(err => { reply(err) }) } else { reply('Oiin mi mama senor?') } break default: if (body.startsWith(`${prefix}${command}`)) { reply(`Maaf *${pushname}*, Command *${prefix}${command}* Tidak Terdaftar Di Dalam *${prefix}menu*!`) } if (isGroup && isSimi && budy != undefined) { console.log(budy) muehe = await simih(budy) console.log(muehe) reply(muehe) } else { console.log(color('[ERROR]','red'), 'Unregistered Command from', color(sender.split('@')[0])) } } } catch (e) { console.log('Error : %s', color(e, 'red')) } }) } starts()
export * from './en.js'; export * from './fr.js'; export * from './nl.js'; export * from './pt-br.js'; export * from './tr.js'; export * from './ru.js';
import { OutlineCardGiftcard as FilledRedeem } from './OutlineCardGiftcard'; export { FilledRedeem };
exports.up = function(knex) { return knex.schema.alterTable("mesures", function(table) { table .integer("ti_id") .references("id") .inTable("tis"); }); }; exports.down = function() { return Promise.resolve(); };
/** * @license * * Use of this source code is governed by an MIT-style license */ import { __awaiter } from 'tslib' import { SchemaBuilder } from '../schema-builder' export class PostgresSchemaBuilder extends SchemaBuilder { createDatabase(name) { return this.connection.statement( this.grammar.compileCreateDatabase(name, this.connection) ) } dropDatabaseIfExists(name) { return this.connection.statement( this.grammar.compileDropDatabaseIfExists(name) ) } hasTable(table) { return __awaiter(this, void 0, void 0, function* () { let database, schema ;[database, schema, table] = this.parseSchemaAndTable(table) table = this.connection.getTablePrefix() + table const result = yield this.connection.select( this.grammar.compileTableExists(), [database, schema, table] ) return result.length > 0 }) } dropAllTables() { var _a return __awaiter(this, void 0, void 0, function* () { const tables = [] const excludedTables = (_a = this.connection.getConfig('dont_drop')) !== null && _a !== void 0 ? _a : ['spatial_ref_sys'] const result = yield this.getAllTables() for (const row of result) { const table = row if (!excludedTables.includes(table)) { tables.push(table) } } if (!tables.length) { return } yield this.connection.statement(this.grammar.compileDropAllTables(tables)) }) } dropAllViews() { return __awaiter(this, void 0, void 0, function* () { const views = [] const result = yield this.getAllViews() for (const row of result) { views.push(row) } if (!views.length) { return } yield this.connection.statement(this.grammar.compileDropAllViews(views)) }) } dropAllTypes() { return __awaiter(this, void 0, void 0, function* () { const types = [] const result = yield this.getAllTypes() for (const row of result) { types.push(row) } if (!types.length) { return } yield this.connection.statement(this.grammar.compileDropAllTypes(types)) }) } getAllTables() { return this.connection.select( this.grammar.compileGetAllTables( this.parseSearchPath(this.connection.getConfig('search_path')) ) ) } getAllViews() { return this.connection.select( this.grammar.compileGetAllViews( this.parseSearchPath(this.connection.getConfig('search_path')) ) ) } getAllTypes() { return this.connection.select(this.grammar.compileGetAllTypes()) } getColumnListing(table) { return __awaiter(this, void 0, void 0, function* () { let database, schema ;[database, schema, table] = this.parseSchemaAndTable(table) table = this.connection.getTablePrefix() + table const results = yield this.connection.select( this.grammar.compileColumnListing(), [database, schema, table] ) return this.connection.getPostProcessor().processColumnListing(results) }) } parseSchemaAndTable(reference) { const searchPath = this.parseSearchPath( this.connection.getConfig('search_path') || 'public' ) const parts = reference.split('.') let database = this.connection.getConfig('database') if (parts.length === 3) { database = parts[0] parts.shift() } let schema = searchPath[0] === '$user' ? this.connection.getConfig('username') : searchPath[0] if (parts.length === 2) { schema = parts[0] parts.shift() } return [database, schema, parts[0]] } parseSearchPath(searchPath) { return searchPath } }
/** * Created by Video on 2016.11.06.. */ function bar() { var elsosor= ['']; var data = { labels: elsosor.concat($('#bar').data('nevek')) , series: [ { label: 'Fokszám', values: elsosor.concat($('#bar').data('degree')) }, /*{ label: '2013', values: [12, 43, 22, 11, 73, 25] }, { label: '2014', values: [31, 28, 14, 8, 15, 21] },*/] }; var chartWidth = 300, barHeight = 20, groupHeight = barHeight * data.series.length, gapBetweenGroups = 10, spaceForLabels = 150, spaceForLegend = 150; // Zip the series data together (first values, second values, etc.) var zippedData = []; for (var i = 0; i < data.labels.length; i++) { for (var j = 0; j < data.series.length; j++) { zippedData.push(data.series[j].values[i]); } } // Color scale var color = d3.scale.category20(); var chartHeight = barHeight * zippedData.length + gapBetweenGroups * data.labels.length; var x = d3.scale.linear() .domain([0, d3.max(zippedData)]) .range([0, chartWidth]); var y = d3.scale.linear() .range([chartHeight + gapBetweenGroups, 0]); var yAxis = d3.svg.axis() .scale(y) .tickFormat('') .tickSize(0) .orient("left"); // Specify the chart area and dimensions var chart = d3.select("#bar > .chart") .attr("width", spaceForLabels + chartWidth + spaceForLegend) .attr("height", chartHeight); // Create bars var bar = chart.selectAll("g") .data(zippedData) .enter().append("g") .attr("transform", function (d, i) { return "translate(" + spaceForLabels + "," + (i * barHeight + gapBetweenGroups * (0.5 + Math.floor(i / data.series.length))) + ")"; }); // Create rectangles of the correct width bar.append("rect") .attr("fill", function (d, i) { return color(i % data.series.length); }) .attr("class", "bar") .attr("width", x) .attr("height", barHeight - 1); // Add text label in bar bar.append("text") .attr("x", function (d) { return x(d) - 3; }) .attr("y", barHeight / 2) .attr("fill", "red") .attr("dy", ".35em") .text(function (d) { return d; }); // Draw labels bar.append("text") .attr("class", "label") .attr("x", function (d) { return -10; }) .attr("y", groupHeight / 2) .attr("dy", ".35em") .text(function (d, i) { if (i % data.series.length === 0) return data.labels[Math.floor(i / data.series.length)]; else return "" }); chart.append("g") .attr("class", "y axis") .attr("transform", "translate(" + spaceForLabels + ", " + -gapBetweenGroups / 2 + ")") .call(yAxis); // Draw legend var legendRectSize = 18, legendSpacing = 4; var legend = chart.selectAll('.legend') .data(data.series) .enter() .append('g') .attr('transform', function (d, i) { var height = legendRectSize + legendSpacing; var offset = -gapBetweenGroups / 2; var horz = spaceForLabels + chartWidth + 40 - legendRectSize; var vert = i * height - offset; return 'translate(' + horz + ',' + vert + ')'; }); legend.append('rect') .attr('width', legendRectSize) .attr('height', legendRectSize) .style('fill', function (d, i) { return color(i); }) .style('stroke', function (d, i) { return color(i); }); legend.append('text') .attr('class', 'legend') .attr('x', legendRectSize + legendSpacing) .attr('y', legendRectSize - legendSpacing) .text(function (d) { return d.label; }); }
import React, { useState } from "react" import { Link } from "gatsby" import { FiAlignJustify } from "react-icons/fi" import { MdMovie } from "react-icons/md" import { IconContext } from "react-icons" export const Navbar = () => { const [show, setShow] = useState(false) return ( <nav className="navbar"> <div className="nav-center"> <div className="nav-header"> <Link to="/"> <IconContext.Provider value={{ size: 70, color: "black" }}> <MdMovie /> </IconContext.Provider> </Link> <button className="nav-btn" onClick={() => setShow(!show)}> <FiAlignJustify /> </button> </div> <div className={show ? "nav-links show-links" : "nav-links"}> <Link to="/" className="nav-link" activeClassName="active-link" onClick={() => setShow(false)} > Home </Link> <Link to="/reviews" className="nav-link" activeClassName="active-link" onClick={() => setShow(false)} > Movies </Link> <Link to="/tags" className="nav-link" activeClassName="active-link" onClick={() => setShow(false)} > Tags </Link> <Link to="/about" className="nav-link" activeClassName="active-link" onClick={() => setShow(false)} > About </Link> <div className="nav-link contact-link"> <Link to="/contact" className="btn" onClick={() => setShow(false)}> Contact </Link> </div> </div> </div> </nav> ) } export default Navbar
const fs = require('fs'); const path = require('path'); const chalk = require('chalk'); const parse = require('react-docgen').parse; const chokidar = require('chokidar'); let paths = { examples: path.join(__dirname, '../src', 'docs', 'examples'), components: path.join(__dirname, '../src', 'components'), output: path.join(__dirname, '../config', 'componentData.js') }; const enableWatchMode = process.argv.slice(2) === '--watch'; if (enableWatchMode) { // Regenerate component metadata when components or examples change. chokidar .watch([paths.examples, paths.components]) .on('change', function(event, path) { generate(paths); }); } else { // Generate component metadata generate(paths); } function generate(paths) { let errors = []; let componentData = getDirectories(paths.components).map(function( componentName ) { try { return getComponentData(paths, componentName); } catch (error) { errors.push( 'An error occurred while attempting to generate metadata for ' + componentName + '. ' + error ); } }); writeFile( paths.output, 'module.exports = /* eslint-disable */ ' + JSON.stringify(errors.length ? errors : componentData) ); } function getComponentData(paths, componentName) { let content = readFile( path.join(paths.components, componentName, componentName + '.js') ); let info = parse(content); return { name: componentName, description: info.description, props: info.props, code: content, examples: getExampleData(paths.examples, componentName) }; } function getExampleData(examplesPath, componentName) { let examples = getExampleFiles(examplesPath, componentName); return examples.map(function(file) { let filePath = path.join(examplesPath, componentName, file); let content = readFile(filePath); let info = parse(content); return { // By convention, component name should match the filename. // So remove the .js extension to get the component name. name: file.slice(0, -3), description: info.description, code: content }; }); } function getExampleFiles(examplesPath, componentName) { let exampleFiles = []; try { exampleFiles = getFiles(path.join(examplesPath, componentName)); } catch (error) { console.log(chalk.red(`No examples found for ${componentName}.`)); } return exampleFiles; } function getDirectories(filepath) { return fs.readdirSync(filepath).filter(function(file) { return fs.statSync(path.join(filepath, file)).isDirectory(); }); } function getFiles(filepath) { return fs.readdirSync(filepath).filter(function(file) { return fs.statSync(path.join(filepath, file)).isFile(); }); } function writeFile(filepath, content) { fs.writeFile(filepath, content, function(err) { err ? console.log(chalk.red(err)) : console.log(chalk.green('Component data saved.')); }); } function readFile(filePath) { return fs.readFileSync(filePath, 'utf-8'); }
var jsffmpeg = require(__dirname + "/../index.js"); var args = require("node-getopt").create([ ["", "source=FILE", "source video"], ["", "target=FOLDER", "target folder"], ["", "renditions=OBJECT", "renditions object"], ["", "watermark=FILE", "watermark image"], ["", "docker=CONTAINER", "docker"], ["", "timeout=MS", "timeout"], ["", "ratiostrategy=STRATEGY", "ratio strategy", "fixed"], ["", "sizestrategy=STRATEGY", "size strategy", "keep"], ["", "shrinkstrategy=STRATEGY", "shrink strategy", "shrink-pad"], ["", "stretchstrategy=STRATEGY", "stretch strategy", "pad"], ["", "mixedstrategy=STRATEGY", "mixed strategy", "shrink-pad"] ]).bindHelp().parseSystem().options; const renditions = args.renditions || [ {resolution: "640x360", bitrate: 800, audio_rate: 96}, {resolution: "842x480", bitrate: 1400, audio_rate: 128}, {resolution: "1280x720", bitrate: 2800, audio_rate: 128} ]; jsffmpeg.ffmpeg_playlist(args.source, { watermark: args.watermark, renditions: renditions, //normalize_audio: true ratio_strategy: args.ratiostrategy, size_strategy: args.sizestrategy, shrink_strategy: args.shrinkstrategy, stretch_strategy: args.stretchstrategy, mixed_strategy: args.mixedstrategy }, args.target, null, null, { test_ffmpeg: true, timeout: args.timeout /*docker: { "container" : "jrottenberg/ffmpeg", "proxy": "localhost:1234", "replaceArguments": { "libfaac": "libfdk_aac", "^/var": "/private/var" }, "preprocessFiles": { "chown": "USERNAME", "chmod": 666, "mkdirs": true }, "postprocessFiles": { "chown": "daemon", "chmod": 666, "recoverChown": true, "recoverChmod": true } }, "test_info" : { "capabilities" : { "auto_rotate" : true }, "encoders" : ["libdfk_aac", "aac"] }*/ }).success(function(data) { console.log(data); }).error(function(error) { console.log(error); });
/** * @author Ammar Faizi <ammarfaizi2@gmail.com> */ class login{ constructor(t){ this.crayner = new crayner; this.dt = (new Date).getTime(); this.dv = 0; this.t = t; } l(urlx){ this.crayner.xhr( "GET",urlx+"?tq="+(this.t.substr(0,32))+"&ts="+this.dt, function(){ var x; try{ x = JSON.parse(this.responseText); } catch(e){ x = null; } if (x!=null) { window.location = x[0]; } } ); if ((this.dv++)%2==0) { this.dt += 12; } else { this.dt += (132912 + this.dv); } this.t = this.t.split("").sort( function(){ return 0.5-Math.random(); } ).join(""); } lg(urlx,u,p,t,hash,dynamic_token){ t = this.crayner.strrev(t); this.crayner.xhr( "POST",urlx+"?hk="+hash,function(){ var x; try{ x = JSON.parse(this.responseText); } catch(e){ x = null; } if(x!=null) { if(x['login']!=true) { var s="background-color:#F8BCBC;"; document.getElementById("u").style = s; document.getElementById("p").style = s; } (x['alert']!='') && (alert(x['alert'])); (x['r']!='') && (window.location=x['r']); } },"login=1&username="+encodeURI(u)+"&password="+encodeURI(p)+"&_token="+encodeURI(t)+"&dynamic_token="+encodeURI(dynamic_token), { "Content-type":"application/x-www-form-urlencoded" } ); } }
const router = require('express').Router(); const { Tag, Product, ProductTag, Category } = require('../../models'); // The `/api/tags` endpoint router.get('/', async (req, res) => { // find all tags // be sure to include its associated Product data try{ const tagData = await Tag.findAll({ include:[{model: Product}] }); res.status(200).json(tagData); } catch (err) { res.status(500).json(err); } }); router.get('/:id', async (req, res) => { // find a single tag by its `id` // be sure to include its associated Product data try{ const tagData = await Tag.findByPk(req.params.id, { include:[{model: Product}] }); if(tagData.id == req.params.id) { res.status(200).json(tagData); } else { res.status(400).json({message: "No tag with that id"}); }; } catch (err) { res.status(500).json(err); }; }); router.post('/', async (req, res) => { // create a new tag /* req.body should look like this: {"tag_name": "orange" */ try{ const tagData = await Tag.create(req.body); if(req.body.tag_name == null) { res.status(400).json({message: "Could not create a tag with that json input"}); } else { res.status(200).json(tagData); }; } catch (err) { res.statust(500).json(err); } }); router.put('/:id', async (req, res) => { // update a tag's name by its `id` value /* req.body should look like this: {"tag_name": "expensive" */ try{ const tagData = await Tag.findByPk(req.params.id, { include:[{model: Product}] }); if(tagData.id == req.params.id) { Tag.update(req.body, { where: { id: req.params.id, }, }); }; if(!tagData) { res.status(400).json({message: "No tag with that id"}); }; res.status(200).json(tagData); } catch (err) { res.status(500).json(err); }; }); router.delete('/:id', async (req, res) => { // delete on tag by its `id` value try{ const tagData = await Tag.findByPk(req.params.id, { include:[{model: Product}], }); if(tagData.id == req.params.id) { Tag.destroy({ where:{ id:req.params.id, }, }); } if(!tagData) { res.status(400).json({message: "No tag with that id"}); } else { res.status(200).json(tagData); }; } catch (err) { res.status(500).json(err); } }); module.exports = router;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.checkCachedDataLink = exports.getNextRevisionFromEntry = exports.getOrCreateRegistryEntry = exports.getNextRegistryEntry = exports.getOrCreateRawBytesRegistryEntry = exports.getRawBytes = exports.setDataLink = exports.deleteJSON = exports.setJSON = exports.getJSON = exports.DEFAULT_SET_JSON_OPTIONS = exports.DEFAULT_GET_JSON_OPTIONS = void 0; const tweetnacl_1 = require("tweetnacl"); const download_1 = require("./download"); const registry_1 = require("./registry"); const sia_1 = require("./skylink/sia"); const number_1 = require("./utils/number"); const url_1 = require("./utils/url"); const string_1 = require("./utils/string"); const format_1 = require("./skylink/format"); const upload_1 = require("./upload"); const array_1 = require("./utils/array"); const encoding_1 = require("./utils/encoding"); const options_1 = require("./utils/options"); const validation_1 = require("./utils/validation"); const JSON_RESPONSE_VERSION = 2; /** * The default options for get JSON. Includes the default get entry and download * options. */ exports.DEFAULT_GET_JSON_OPTIONS = { ...options_1.DEFAULT_BASE_OPTIONS, ...registry_1.DEFAULT_GET_ENTRY_OPTIONS, ...download_1.DEFAULT_DOWNLOAD_OPTIONS, cachedDataLink: undefined, }; /** * The default options for set JSON. Includes the default upload, get JSON, and * set entry options. */ exports.DEFAULT_SET_JSON_OPTIONS = { ...options_1.DEFAULT_BASE_OPTIONS, ...upload_1.DEFAULT_UPLOAD_OPTIONS, ...exports.DEFAULT_GET_JSON_OPTIONS, ...registry_1.DEFAULT_SET_ENTRY_OPTIONS, }; // ==== // JSON // ==== /** * Gets the JSON object corresponding to the publicKey and dataKey. * * @param this - SkynetClient * @param publicKey - The user public key. * @param dataKey - The key of the data to fetch for the given user. * @param [customOptions] - Additional settings that can optionally be set. * @returns - The returned JSON and corresponding data link. * @throws - Will throw if the returned signature does not match the returned entry, or if the skylink in the entry is invalid. */ async function getJSON(publicKey, dataKey, customOptions) { (0, validation_1.validateOptionalObject)("customOptions", customOptions, "parameter", exports.DEFAULT_GET_JSON_OPTIONS); // Rest of validation is done in `getEntry`. const opts = { ...exports.DEFAULT_GET_JSON_OPTIONS, ...this.customOptions, ...customOptions, }; // Lookup the registry entry. const entry = await getSkyDBRegistryEntry(this, publicKey, dataKey, opts); if (entry === null) { return { data: null, dataLink: null }; } // Determine the data link. // TODO: Can this still be an entry link which hasn't yet resolved to a data link? const { rawDataLink, dataLink } = parseDataLink(entry.data, true); // If a cached data link is provided and the data link hasn't changed, return. if (checkCachedDataLink(rawDataLink, opts.cachedDataLink)) { return { data: null, dataLink }; } // Download the data in the returned data link. const downloadOpts = (0, options_1.extractOptions)(opts, download_1.DEFAULT_DOWNLOAD_OPTIONS); const { data } = await this.getFileContent(dataLink, downloadOpts); if (typeof data !== "object" || data === null) { throw new Error(`File data for the entry at data key '${dataKey}' is not JSON.`); } if (!(data["_data"] && data["_v"])) { // Legacy data prior to skynet-js v4, return as-is. return { data, dataLink }; } const actualData = data["_data"]; if (typeof actualData !== "object" || data === null) { throw new Error(`File data '_data' for the entry at data key '${dataKey}' is not JSON.`); } return { data: actualData, dataLink }; } exports.getJSON = getJSON; /** * Sets a JSON object at the registry entry corresponding to the publicKey and dataKey. * * @param this - SkynetClient * @param privateKey - The user private key. * @param dataKey - The key of the data to fetch for the given user. * @param json - The JSON data to set. * @param [customOptions] - Additional settings that can optionally be set. * @returns - The returned JSON and corresponding data link. * @throws - Will throw if the input keys are not valid strings. */ async function setJSON(privateKey, dataKey, json, customOptions) { (0, validation_1.validateHexString)("privateKey", privateKey, "parameter"); (0, validation_1.validateString)("dataKey", dataKey, "parameter"); (0, validation_1.validateObject)("json", json, "parameter"); (0, validation_1.validateOptionalObject)("customOptions", customOptions, "parameter", exports.DEFAULT_SET_JSON_OPTIONS); const opts = { ...exports.DEFAULT_SET_JSON_OPTIONS, ...this.customOptions, ...customOptions, }; const { publicKey: publicKeyArray } = tweetnacl_1.sign.keyPair.fromSecretKey((0, string_1.hexToUint8Array)(privateKey)); const [entry, dataLink] = await getOrCreateRegistryEntry(this, (0, string_1.toHexString)(publicKeyArray), dataKey, json, opts); // Update the registry. const setEntryOpts = (0, options_1.extractOptions)(opts, registry_1.DEFAULT_SET_ENTRY_OPTIONS); await this.registry.setEntry(privateKey, entry, setEntryOpts); return { data: json, dataLink: (0, format_1.formatSkylink)(dataLink) }; } exports.setJSON = setJSON; /** * Deletes a JSON object at the registry entry corresponding to the publicKey and dataKey. * * @param this - SkynetClient * @param privateKey - The user private key. * @param dataKey - The key of the data to fetch for the given user. * @param [customOptions] - Additional settings that can optionally be set. * @throws - Will throw if the input keys are not valid strings. */ async function deleteJSON(privateKey, dataKey, customOptions) { (0, validation_1.validateHexString)("privateKey", privateKey, "parameter"); (0, validation_1.validateString)("dataKey", dataKey, "parameter"); (0, validation_1.validateOptionalObject)("customOptions", customOptions, "parameter", exports.DEFAULT_SET_JSON_OPTIONS); const opts = { ...exports.DEFAULT_SET_JSON_OPTIONS, ...this.customOptions, ...customOptions, }; const { publicKey: publicKeyArray } = tweetnacl_1.sign.keyPair.fromSecretKey((0, string_1.hexToUint8Array)(privateKey)); const getEntryOpts = (0, options_1.extractOptions)(opts, registry_1.DEFAULT_GET_ENTRY_OPTIONS); const entry = await getNextRegistryEntry(this, (0, string_1.toHexString)(publicKeyArray), dataKey, new Uint8Array(sia_1.RAW_SKYLINK_SIZE), getEntryOpts); // Update the registry. const setEntryOpts = (0, options_1.extractOptions)(opts, registry_1.DEFAULT_SET_ENTRY_OPTIONS); await this.registry.setEntry(privateKey, entry, setEntryOpts); } exports.deleteJSON = deleteJSON; /** * Sets the datalink for the entry at the given private key and data key. * * @param this - SkynetClient * @param privateKey - The user private key. * @param dataKey - The data key. * @param dataLink - The data link to set at the entry. * @param [customOptions] - Additional settings that can optionally be set. * @throws - Will throw if the input keys are not valid strings. */ async function setDataLink(privateKey, dataKey, dataLink, customOptions) { (0, validation_1.validateHexString)("privateKey", privateKey, "parameter"); (0, validation_1.validateString)("dataKey", dataKey, "parameter"); (0, validation_1.validateString)("dataLink", dataLink, "parameter"); (0, validation_1.validateOptionalObject)("customOptions", customOptions, "parameter", exports.DEFAULT_SET_JSON_OPTIONS); const opts = { ...exports.DEFAULT_SET_JSON_OPTIONS, ...this.customOptions, ...customOptions, }; const { publicKey: publicKeyArray } = tweetnacl_1.sign.keyPair.fromSecretKey((0, string_1.hexToUint8Array)(privateKey)); const getEntryOpts = (0, options_1.extractOptions)(opts, registry_1.DEFAULT_GET_ENTRY_OPTIONS); const entry = await getNextRegistryEntry(this, (0, string_1.toHexString)(publicKeyArray), dataKey, (0, sia_1.decodeSkylink)(dataLink), getEntryOpts); // Update the registry. const setEntryOpts = (0, options_1.extractOptions)(opts, registry_1.DEFAULT_SET_ENTRY_OPTIONS); await this.registry.setEntry(privateKey, entry, setEntryOpts); } exports.setDataLink = setDataLink; // ========= // Raw Bytes // ========= /** * Gets the raw bytes corresponding to the publicKey and dataKey. The caller is responsible for setting any metadata in the bytes. * * @param this - SkynetClient * @param publicKey - The user public key. * @param dataKey - The key of the data to fetch for the given user. * @param [customOptions] - Additional settings that can optionally be set. * @returns - The returned bytes. * @throws - Will throw if the returned signature does not match the returned entry, or if the skylink in the entry is invalid. */ async function getRawBytes(publicKey, dataKey, // TODO: Take a new options type? customOptions) { (0, validation_1.validateOptionalObject)("customOptions", customOptions, "parameter", exports.DEFAULT_GET_JSON_OPTIONS); // Rest of validation is done in `getEntry`. const opts = { ...exports.DEFAULT_GET_JSON_OPTIONS, ...this.customOptions, ...customOptions, }; // Lookup the registry entry. const entry = await getSkyDBRegistryEntry(this, publicKey, dataKey, opts); if (entry === null) { return { data: null, dataLink: null }; } // Determine the data link. // TODO: Can this still be an entry link which hasn't yet resolved to a data link? const { rawDataLink, dataLink } = parseDataLink(entry.data, false); // If a cached data link is provided and the data link hasn't changed, return. if (checkCachedDataLink(rawDataLink, opts.cachedDataLink)) { return { data: null, dataLink }; } // Download the data in the returned data link. const downloadOpts = { ...(0, options_1.extractOptions)(opts, download_1.DEFAULT_DOWNLOAD_OPTIONS), responseType: "arraybuffer", }; const { data: buffer } = await this.getFileContent(dataLink, downloadOpts); return { data: new Uint8Array(buffer), dataLink }; } exports.getRawBytes = getRawBytes; /* istanbul ignore next */ /** * Gets the registry entry for the given raw bytes or creates the entry if it doesn't exist. * * @param client - The Skynet client. * @param publicKey - The user public key. * @param dataKey - The dat akey. * @param data - The raw byte data to set. * @param [customOptions] - Additional settings that can optionally be set. * @returns - The registry entry and corresponding data link. * @throws - Will throw if the revision is already the maximum value. */ // TODO: Rename & refactor after the SkyDB caching refactor. async function getOrCreateRawBytesRegistryEntry(client, publicKey, dataKey, data, customOptions) { // Not publicly available, don't validate input. const opts = { ...exports.DEFAULT_SET_JSON_OPTIONS, ...client.customOptions, ...customOptions, }; // Create the data to upload to acquire its skylink. let dataKeyHex = dataKey; if (!opts.hashedDataKeyHex) { dataKeyHex = (0, string_1.toHexString)((0, string_1.stringToUint8ArrayUtf8)(dataKey)); } const file = new File([data], `dk:${dataKeyHex}`, { type: "application/octet-stream" }); // Start file upload, do not block. const uploadOpts = (0, options_1.extractOptions)(opts, upload_1.DEFAULT_UPLOAD_OPTIONS); const skyfilePromise = client.uploadFile(file, uploadOpts); // Fetch the current value to find out the revision. // // Start getEntry, do not block. const getEntryOpts = (0, options_1.extractOptions)(opts, registry_1.DEFAULT_GET_ENTRY_OPTIONS); const entryPromise = client.registry.getEntry(publicKey, dataKey, getEntryOpts); // Block until both getEntry and uploadFile are finished. const [signedEntry, skyfile] = await Promise.all([ entryPromise, skyfilePromise, ]); const revision = getNextRevisionFromEntry(signedEntry.entry); // Build the registry entry. const dataLink = (0, string_1.trimUriPrefix)(skyfile.skylink, url_1.URI_SKYNET_PREFIX); const rawDataLink = (0, encoding_1.decodeSkylinkBase64)(dataLink); (0, validation_1.validateUint8ArrayLen)("rawDataLink", rawDataLink, "skylink byte array", sia_1.RAW_SKYLINK_SIZE); const entry = { dataKey, data: rawDataLink, revision, }; return entry; } exports.getOrCreateRawBytesRegistryEntry = getOrCreateRawBytesRegistryEntry; // ======= // Helpers // ======= /** * Gets the next entry for the given public key and data key, setting the data to be the given data and the revision number accordingly. * * @param client - The Skynet client. * @param publicKey - The user public key. * @param dataKey - The dat akey. * @param data - The data to set. * @param [customOptions] - Additional settings that can optionally be set. * @returns - The registry entry and corresponding data link. * @throws - Will throw if the revision is already the maximum value. */ async function getNextRegistryEntry(client, publicKey, dataKey, data, customOptions) { // Not publicly available, don't validate input. const opts = { ...registry_1.DEFAULT_GET_ENTRY_OPTIONS, ...client.customOptions, ...customOptions, }; // Get the latest entry. // TODO: Can remove this once we start caching the latest revision. const signedEntry = await client.registry.getEntry(publicKey, dataKey, opts); const revision = getNextRevisionFromEntry(signedEntry.entry); // Build the registry entry. const entry = { dataKey, data, revision, }; return entry; } exports.getNextRegistryEntry = getNextRegistryEntry; /** * Gets the registry entry and data link or creates the entry if it doesn't exist. * * @param client - The Skynet client. * @param publicKey - The user public key. * @param dataKey - The dat akey. * @param json - The JSON to set. * @param [customOptions] - Additional settings that can optionally be set. * @returns - The registry entry and corresponding data link. * @throws - Will throw if the revision is already the maximum value. */ async function getOrCreateRegistryEntry(client, publicKey, dataKey, json, customOptions) { // Not publicly available, don't validate input. const opts = { ...exports.DEFAULT_SET_JSON_OPTIONS, ...client.customOptions, ...customOptions, }; // Set the hidden _data and _v fields. const fullData = { _data: json, _v: JSON_RESPONSE_VERSION }; // Create the data to upload to acquire its skylink. let dataKeyHex = dataKey; if (!opts.hashedDataKeyHex) { dataKeyHex = (0, string_1.toHexString)((0, string_1.stringToUint8ArrayUtf8)(dataKey)); } const file = new File([JSON.stringify(fullData)], `dk:${dataKeyHex}`, { type: "application/json" }); // Start file upload, do not block. const uploadOpts = (0, options_1.extractOptions)(opts, upload_1.DEFAULT_UPLOAD_OPTIONS); const skyfilePromise = client.uploadFile(file, uploadOpts); // Fetch the current value to find out the revision. // // Start getEntry, do not block. const getEntryOpts = (0, options_1.extractOptions)(opts, registry_1.DEFAULT_GET_ENTRY_OPTIONS); const entryPromise = client.registry.getEntry(publicKey, dataKey, getEntryOpts); // Block until both getEntry and uploadFile are finished. const [signedEntry, skyfile] = await Promise.all([ entryPromise, skyfilePromise, ]); const revision = getNextRevisionFromEntry(signedEntry.entry); // Build the registry entry. const dataLink = (0, string_1.trimUriPrefix)(skyfile.skylink, url_1.URI_SKYNET_PREFIX); const data = (0, encoding_1.decodeSkylinkBase64)(dataLink); (0, validation_1.validateUint8ArrayLen)("data", data, "skylink byte array", sia_1.RAW_SKYLINK_SIZE); const entry = { dataKey, data, revision, }; return [entry, (0, format_1.formatSkylink)(dataLink)]; } exports.getOrCreateRegistryEntry = getOrCreateRegistryEntry; /** * Gets the next revision from a returned entry (or 0 if the entry was not found). * * @param entry - The returned registry entry. * @returns - The revision. * @throws - Will throw if the next revision would be beyond the maximum allowed value. */ function getNextRevisionFromEntry(entry) { let revision; if (entry === null) { revision = BigInt(0); } else { revision = entry.revision + BigInt(1); } // Throw if the revision is already the maximum value. if (revision > number_1.MAX_REVISION) { throw new Error("Current entry already has maximum allowed revision, could not update the entry"); } return revision; } exports.getNextRevisionFromEntry = getNextRevisionFromEntry; /** * Checks whether the raw data link matches the cached data link, if provided. * * @param rawDataLink - The raw, unformatted data link. * @param cachedDataLink - The cached data link, if provided. * @returns - Whether the cached data link is a match. * @throws - Will throw if the given cached data link is not a valid skylink. */ function checkCachedDataLink(rawDataLink, cachedDataLink) { if (cachedDataLink) { cachedDataLink = (0, validation_1.validateSkylinkString)("cachedDataLink", cachedDataLink, "optional parameter"); return rawDataLink === cachedDataLink; } return false; } exports.checkCachedDataLink = checkCachedDataLink; /** * Gets the registry entry, returning null if the entry contains an empty skylink (the deletion sentinel). * * @param client - The Skynet Client * @param publicKey - The user public key. * @param dataKey - The key of the data to fetch for the given user. * @param opts - Additional settings. * @returns - The registry entry, or null if not found or deleted. */ async function getSkyDBRegistryEntry(client, publicKey, dataKey, opts) { const getEntryOpts = (0, options_1.extractOptions)(opts, registry_1.DEFAULT_GET_ENTRY_OPTIONS); const { entry } = await client.registry.getEntry(publicKey, dataKey, getEntryOpts); if (entry === null || (0, array_1.areEqualUint8Arrays)(entry.data, sia_1.EMPTY_SKYLINK)) { return null; } return entry; } /** * Parses a data link out of the given registry entry data. * * @param data - The raw registry entry data. * @param legacy - Whether to check for possible legacy skylink data, encoded as base64. * @returns - The raw, unformatted data link and the formatted data link. * @throws - Will throw if the data is not of the expected length for a skylink. */ function parseDataLink(data, legacy) { let rawDataLink = ""; if (legacy && data.length === sia_1.BASE64_ENCODED_SKYLINK_SIZE) { // Legacy data, convert to string for backwards compatibility. rawDataLink = (0, string_1.uint8ArrayToStringUtf8)(data); } else if (data.length === sia_1.RAW_SKYLINK_SIZE) { // Convert the bytes to a base64 skylink. rawDataLink = (0, encoding_1.encodeSkylinkBase64)(data); } else { (0, validation_1.throwValidationError)("entry.data", data, "returned entry data", `length ${sia_1.RAW_SKYLINK_SIZE} bytes`); } return { rawDataLink, dataLink: (0, format_1.formatSkylink)(rawDataLink) }; }
import React from "react"; import { Table, Row, Col, Divider } from "antd"; import PropTypes from "prop-types"; import Highlight from "react-highlighter"; import downloadFileFromDocumentManager from "@/utils/actionlessNetworkCalls"; import LinkButton from "@/components/common/LinkButton"; /** * @class DocumentResultsTable - displays a table of mine search results */ const propTypes = { header: PropTypes.string.isRequired, highlightRegex: PropTypes.objectOf(PropTypes.regexp).isRequired, searchResults: PropTypes.arrayOf(PropTypes.object).isRequired, }; const defaultProps = {}; export const DocumentResultsTable = (props) => { const columns = [ { title: "Document Guid", dataIndex: "document_guid", key: "document_guid", render: (text, record) => [ <Row> <Col span={24}> <LinkButton key={record.mine_document_guid || record.permit_amendment_document_guid} onClick={() => downloadFileFromDocumentManager(record.document_manager_guid, record.document_name) } > <Highlight search={props.highlightRegex}>{record.document_name}</Highlight> </LinkButton> </Col> </Row>, <Row className="padding-small--top"> <Col xs={24} md={6}> <p>Mine</p> </Col> <Col xs={24} md={18}> <p>{record.mine_name}</p> </Col> </Row>, ], }, ]; return ( <div> <h2>{props.header}</h2> <Divider /> <Table className="nested-table padding-large--bottom" align="left" showHeader={false} pagination={false} columns={columns} dataSource={props.searchResults} /> </div> ); }; DocumentResultsTable.propTypes = propTypes; DocumentResultsTable.defaultProps = defaultProps; export default DocumentResultsTable;
const graphQlLib = require('/lib/graphql'); for (var exportKey in graphQlLib) { exports[exportKey] = graphQlLib[exportKey]; } exports.createObjectType = function (context, params) { const creationCallback = context.options && context.options.creationCallbacks && context.options.creationCallbacks[params.name]; if (creationCallback) { creationCallback(context, params); } return context.schemaGenerator.createObjectType(params); };
/* Bean Counting: You can get the Nth character, or letter, from a string by writing "string". charAt(N), similar to how you get its length with "s".length. The returned value will be a string containing only one character (for example, "b" ). The first character has position zero, which causes the last one to be found at position string.length - 1. In other words, a two-character string has length 2, and its characters have positions 0 and 1. Write a function countBs that takes a string as its only argument and returns a number that indicates how many uppercase “B” characters are in the string. Next, write a function called countChar that behaves like countBs, except it takes a second argument that indicates the character that is to be counted (rather than counting only uppercase “B” characters). Rewrite countBs to make use of this new function. */ function countBs(string) { return countChar(string, "B"); } function countChar(string, char) { var count = 0; for (var i = 0; i <= string.length - 1; i++) { if (string.charAt(i) === char) count++; else continue; } return count; } console.log(countBs("Bowling Ball")); console.log(countChar("Bowling Ball", "l"));
import React from 'react'; const AttachmentIcon = props => ( <svg {...props.size || { width: '24px', height: '24px' }} {...props} viewBox="0 0 24 24"> {props.title && <title>{props.title}</title>} <path fill={props.fill || '#666666'} d="M16.5,6V17.5A4,4 0 0,1 12.5,21.5A4,4 0 0,1 8.5,17.5V5A2.5,2.5 0 0,1 11,2.5A2.5,2.5 0 0,1 13.5,5V15.5A1,1 0 0,1 12.5,16.5A1,1 0 0,1 11.5,15.5V6H10V15.5A2.5,2.5 0 0,0 12.5,18A2.5,2.5 0 0,0 15,15.5V5A4,4 0 0,0 11,1A4,4 0 0,0 7,5V17.5A5.5,5.5 0 0,0 12.5,23A5.5,5.5 0 0,0 18,17.5V6H16.5Z" /> </svg> ); export default AttachmentIcon;
/*** * @copyright 2017 Digital Devils BV * @author Digital Devils BV <info@digitaldevils.nl> * @package Remote Gallery * @link https://www.digitaldevils.nl/ * @version 1.0 ***/ var remoteGallery = (function(){ // Define variables var input = new URL(window.location).searchParams; var folder = ''; var prefix = ''; var postfix = ''; var start = ''; var end = ''; var leading_zeros = ''; // Set input $('#photo').val(input.get('photo') != null ? input.get('photo') : ''); $('#amount').val(input.get('amount') != null ? input.get('amount') : '10'); /*** Private functions ***/ var _getInput = function(){ // Check photo URL if($('#photo').val() != ''){ // Parse photo url var parser = new URL($('#photo').val()); var path_parts = parser.pathname.split('/') var filename = path_parts.pop(); var file_parts = filename.split('.') // Get input folder = parser.origin + path_parts.join('/')+'/'; start = filename.match(/.*(?:\D|^)(\d+)/)[1]; end = parseInt(start) + parseInt($('#amount').val()) - 1; prefix = filename.substr(0, filename.indexOf(start)); postfix = filename.substr(filename.indexOf(start) + start.length); leading_zeros = ''; } }; var _getLeadingZeroes = function(){ // Get leading zeroes for(var i = 0; i < start.length; i++){ if(start.charAt(i) == '0'){ leading_zeros += '0'; }else{ break; } } // Remove leading zeroes from start start = start.substr(leading_zeros.length); }; // Reset gallery var _resetGallery = function(gallery){ // Empty gallery $(gallery).empty(); }; /*** Public functions ***/ // Build gallery var buildGallery = function(options){ // Get input _getInput(); _getLeadingZeroes(); if(start != ''){ // Reset gallery _resetGallery(options.gallery); // Loop through images for(var i = start; i <= end; i++){ if(i == 10 || i == 100 || i == 1000){ leading_zeros = leading_zeros.substr(1); } // Add leading zeroes number = leading_zeros.substr(0, i) + i; // Check if image exists image = new Image(); image.onload = function(){ // Add to gallery $(options.gallery).append('\ <div class="columns">\ <a href="'+this.src+'" class="thumbnail">\ <img src="'+this.src+'">\ </a>\ </div>\ '); // Completed loading options.complete(); }; image.onerror = function(){ // Add to errors $(options.errors + ' ul').append('\ <li>'+this.src+' not found</li>\ '); // Show errors $(options.errors).removeClass('hide'); // Completed loading options.complete(); }; // Load image image.src = folder + prefix + number + postfix; } } }; // Output return { 'buildGallery': buildGallery }; })();
let mesh, group, axesHelper, ground, lightDirectional, cameraHelper; let sceneRotation = 1; let renderer, camera, controls, scene; function initThreejs () { camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 1000 ); camera.position.set( - 100, - 100, 100 ); camera.up.set( 0, 0, 1 ); scene = new THREE.Scene(); scene.background = new THREE.Color( 0xcce0ff ); //scene.fog = new THREE.Fog( 0xcce0ff, 550, 800 ); scene.add( camera ); renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement ); renderer.outputEncoding = THREE.sRGBEncoding; renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; controls = new THREE.OrbitControls( camera, renderer.domElement ); //controls.minDistance = 40; //controls.maxDistance = 500; //controls.autoRotate = true; controls.enableDamping = true; controls.dampingFactor = 0.09; //controls.enablePan = false; controls.autoRotateSpeed = 2; //controls.maxPolarAngle = Math.PI * 0.5; window.addEventListener( "resize", onWindowResize, false ); window.addEventListener( "orientationchange", onWindowResize, false ); window.parent.addEventListener( "keyup", () => controls.autoRotate = false, false ); renderer.domElement.addEventListener( "click", () => controls.autoRotate = false, false ); addLights(); axesHelper = new THREE.AxesHelper( 100 ); scene.add( axesHelper ); addGround(); } function addLights () { //scene.add( new THREE.AmbientLight( 0x404040 ) ); scene.add( new THREE.AmbientLight( 0x666666 ) ); const pointLight = new THREE.PointLight( 0xffffff, 0.2 ); pointLight.position.copy( camera.position ); camera.add( pointLight ); lightDirectional = new THREE.DirectionalLight( 0xdffffff, 0.9 ); lightDirectional.position.set( 50, - 200, 20 ); lightDirectional.castShadow = true; lightDirectional.shadow.mapSize.width = 1024; lightDirectional.shadow.mapSize.height = 1024; var d = 100; lightDirectional.shadow.camera.left = - d; lightDirectional.shadow.camera.right = d; lightDirectional.shadow.camera.top = d; lightDirectional.shadow.camera.bottom = - d; lightDirectional.shadow.camera.far = 500; scene.add( lightDirectional ); //scene.add( new THREE.CameraHelper( lightDirectional.shadow.camera ) ); } function addGround () { const geometry = new THREE.PlaneBufferGeometry( 2000, 2000 ); const material = new THREE.MeshPhongMaterial( { color: 0xaaaaaa, depthWrite: false, side: 2 } ); ground = new THREE.Mesh( geometry, material ); ground.name = "ground"; ground.receiveShadow = true; scene.add( ground ); } function zoomObjectBoundingSphere ( obj = group ) { //console.log( "obj", obj ); let center = new THREE.Vector3( 0, 0, 0 ); let radius = 50; const bbox = new THREE.Box3().setFromObject( obj ); //console.log( 'bbox', bbox ); if ( bbox.max.x !== Infinity ) { const sphere = bbox.getBoundingSphere( new THREE.Sphere() ); center = sphere.center; radius = sphere.radius; //console.log( "sphere", sphere ) } ground.position.z = bbox.min.z; controls.target.copy( center ); // needed because model may be far from origin controls.maxDistance = 50 * radius; delta = camera.position.clone().sub( controls.target ).normalize(); //console.log( 'delta', delta ); position = controls.target.clone().add( delta.multiplyScalar( 2 * radius ) ); //console.log( 'position', position ); distance = controls.target.distanceTo( camera.position ); //camera.zoom = distance / ( * radius ) ; camera.position.copy( center.clone().add( new THREE.Vector3( - 1.5 * radius, 1.5 * radius, 0.5 * radius ) ) ); camera.near = 0.001 * radius; //2 * camera.position.length(); camera.far = 50 * radius; //2 * camera.position.length(); camera.updateProjectionMatrix(); axesHelper.position.copy( center ); if ( lightDirectional ) { lightDirectional.position.copy( center.clone().add( new THREE.Vector3( - 1.5 * radius, 1.5 * radius, 0.25 * radius ) ) ); lightDirectional.shadow.camera.scale.set( 0.02 * radius, 0.02 * radius, 0.2 * radius ); var d = 50; lightDirectional.shadow.camera.left = - d; lightDirectional.shadow.camera.right = d; lightDirectional.shadow.camera.top = d; lightDirectional.shadow.camera.bottom = - d; lightDirectional.shadow.camera.far = 500; //targetObject.position.copy( center ); scene.remove( cameraHelper ); cameraHelper = new THREE.CameraHelper( lightDirectional.shadow.camera ); scene.add( cameraHelper ); } let event = new Event( "onresetthree", { "bubbles": true, "cancelable": false, detail: true } ); //window.addEventListener( "onrresetthree", doThings, false ); // listening: or-object-rotation-xx.js // listening: dss-display-scene-settings-xx.js window.dispatchEvent( event ); console.log( "mszoom ",performance.now() - timeStart ); } ////////// function requestFile ( url, callback ) { const xhr = new XMLHttpRequest(); xhr.open( "GET", url, true ); xhr.onerror = ( xhr ) => console.log( "error:", xhr ); //xhr.onprogress = ( xhr ) => console.log( 'bytes loaded:', xhr.loaded ); xhr.onload = ( xhr ) => callback( xhr.target.response ); xhr.send( null ); } function setStats () { const script = document.head.appendChild( document.createElement( "script" ) ); script.onload = () => { const stats = new Stats(); const sts = document.body.appendChild( stats.dom ); sts.style.left = ""; sts.style.right = "0px"; requestAnimationFrame( function loop () { stats.update(); requestAnimationFrame( loop ); } ); }; script.src = "https://raw.githack.com/mrdoob/stats.js/master/build/stats.min.js"; const render = renderer.info.render; //divInfo.classList.add( "navText" ); divInfo.innerHTML = ` Renderer<br> Calls: ${render.calls }<br> Triangles: ${render.triangles.toLocaleString() }<br> `; } function onWindowResize () { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight ); //controls.handleResize(); //console.log( 'onWindowResize window.innerWidth', window.innerWidth ); } function animate () { requestAnimationFrame( animate ); renderer.render( scene, camera ); controls.update(); }
const express = require('express'); const router = express.Router(); router.get('/', function(req, res) { res.render('index'); }); module.exports = router;
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; import routes, { formatDate, hasPermission, err } from '../../constants'; import { sendFlashMessage, clearFlashMessages, fetchPermission, deletePermission, addUserToPermission, removeUserFromPermission } from '../../actions'; import { CustomRedirect } from '../Common'; class PermissionPage extends Component { static propTypes = { history: PropTypes.shape({ push: PropTypes.func }).isRequired, user: PropTypes.object.isRequired, match: PropTypes.shape({ params: PropTypes.shape({ id: PropTypes.string }) }).isRequired, flash: PropTypes.func.isRequired, clear: PropTypes.func.isRequired }; constructor(props) { super(props); this.state = { permission: null, loading: true, memberEmail: '', members: [] }; } componentDidMount = async () => { const { flash, clear } = this.props; try { clear(); const permission = await fetchPermission(this.props.match.params.id); console.log('Fetched permission:', permission); this.setState({ permission, loading: false, members: permission ? permission.members : [] }); } catch (error) { console.error('Permission Page error:', error); this.setState({ loading: false }); flash(err(error)); } }; onChange = e => this.setState({ [e.target.id]: e.target.value }); onClick = id => () => this.props.history.push(`/member/${id}`); onAddUser = async e => { e.preventDefault(); const { flash, clear } = this.props; const { memberEmail } = this.state; try { clear(); const response = await addUserToPermission(this.props.match.params.id, memberEmail); console.log('Added user to permission:', response); const { permission } = response; this.setState({ members: permission.members, memberEmail: '' }); return flash('Successfully added user to this permission', 'green'); } catch (error) { console.error('Permissions Page error:', error); return flash(err(error)); } }; onDeleteUser = async e => { e.preventDefault(); e.stopPropagation(); const { flash, clear } = this.props; const { id: memberID } = e.target; try { clear(); const { permission } = await removeUserFromPermission( this.props.match.params.id, memberID ); this.setState({ members: permission.members }); return flash('Successfully removed user from this permission', 'green'); } catch (error) { console.error('Permissions Page error:', error); return flash(err(error)); } }; onDeletePermission = async e => { e.preventDefault(); const { flash, clear, history } = this.props; try { clear(); await deletePermission(this.props.match.params.id); history.push('/permissions'); return flash('Permission successfully deleted', 'green'); } catch (error) { console.error('Permissions Page error:', error); return flash(err(error)); } }; render() { const { permission, loading, memberEmail, members } = this.state; const { user } = this.props; if (loading) return <div>Loading...</div>; if (!permission) return <CustomRedirect msgRed="Permission not found" />; return ( <div className="section"> <div className="section-container"> {/* <Header message={`Permission: ${permission.name}`} /> */} <h3> Permission: {permission.name} <Link to={routes.PERMISSIONS} className="pull-left"> <button type="button" className="btn btn-primary btn-sm"> <span className="glyphicon glyphicon-chevron-left" aria-hidden="true" /> Permissions </button> </Link> </h3> <div className="panel panel-default text-left"> <div className="panel-body"> <div id="profile_intro_text"> <div id="profile_name">{permission.name}</div> <div id="profile_major">{permission.description}</div> <div id="profile_badges"> <div className="profile_badge"> <div className="profile_badge_title">Users</div> {members ? members.length : 0} </div> </div> </div> </div> </div> <hr /> <h3>Users</h3> <div className="panel panel-default"> <table className="table table-bordered table-hover table-clickable panel-body sortableTable"> <thead> <tr> <th>Member</th> <th>Date Added</th> <th>Added By</th> </tr> </thead> <tbody> {members && members.length ? ( members.map((m, i) => ( <tr onClick={this.onClick(m.member._id)} key={i}> <td>{m.member.name}</td> <td>{formatDate(m.dateAdded)}</td> <td> {m.recordedBy ? m.recordedBy.name : 'Unknown'} <button className="btn btn-xs btn-danger pull-right" id={m.member._id} onClick={this.onDeleteUser} > Delete </button> </td> </tr> )) ) : ( <tr> <td>No Users</td> <td /> <td /> </tr> )} <tr> <td /> <td> <input type="text" id="memberEmail" name="member_name" placeholder="Add User" className="form-control membersautocomplete" data-bvalidator="required" value={memberEmail} onChange={this.onChange} /> </td> <td> <input type="submit" value="Add User" className="btn btn-sm btn-primary" onClick={this.onAddUser} /> </td> </tr> </tbody> </table> </div> {hasPermission(user, 'adminpermissions') && ( <button className="btn btn-sm btn-danger pull-right" onClick={this.onDeletePermission} > Delete Permission </button> )} </div> </div> ); } } const mapStateToProps = state => ({ ...state.sessionState }); export default connect( mapStateToProps, { flash: sendFlashMessage, clear: clearFlashMessages } )(PermissionPage);
//>>built define( //begin v1.x content ({ displayOptions: "[zobraziť voľby]", title: "Nadpis", authors: "Autori", contributors: "Prispievatelia", id: "ID", close: "[zatvoriť]", updated: "Aktualizovaný", summary: "Súhrn", content: "Obsah" }) //end v1.x content );
/** * Creates a new permission group * @param name {String} Name of the permission group */ PermissionGroup.prototype.constructor = function(name) { if (name) { this.name = name; } else { throw "Invalid PermissionGroup! Some parts are missing!"; } };
//CoverViewer Open labels dialog CoverViewer.prototype.LabelsOpen = function() { //Check for create the labes window if(this.labels.created === false) { //Create the labels window this.LabelsCreate(); //Set created as true this.labels.created = true; } //Show the labels dialog this.labels.Show(); }; //CoverViewer labels create CoverViewer.prototype.LabelsCreate = function() { //Initialize the div var div = ''; //Read all the names for(var i = 0; i < this.bams.label.length; i++) { //Create the name row div = div + '<div class="' + this.labels.row.class + '">'; //Add the switch div div = div + '<div id="' + this.labels.switch.id + '_' + i + '" class="' + this.labels.switch.class + '">'; //Add the switch input div = div + '<input type="checkbox" value="1" id="' + this.labels.switch.id + '_' + i + 'ch" name>'; //Add the switch label div = div + '<label for="' + this.labels.switch.id + '_' + i + 'ch2"></label>'; //Add the div for the background div = div + '<div></div>'; //Close the switch div = div + '</div>'; //Name span div = div + '<span class="' + this.labels.names.class + '" style="color:' + this.bams.color[i] + ';">'; //Add the name div = div + this.bams.label[i]; //Close the span name div = div + '</span>'; //Close the name element div = div + '</div>'; } //Add a line break div = div + '<br>'; //Add the done button div = div + '<div id="' + this.labels.done.id + '" class="' + this.labels.done.class + '">' + this.labels.done.title + '</div>'; //Show the names this.labels.Content(div); //Add the events for(var i = 0; i < this.bams.label.length; i++) { //Add the event CoverViewerLabelsSwitchEvent(this, i); //Change the status document.getElementById(this.labels.switch.id + '_' + i + 'ch').checked = true; } //dd the done button event CoverViewerLabelsDoneEvent(this); }; //CoverViewer Labels Click event CoverViewer.prototype.LabelsClick = function(i) { //Get the element var el = document.getElementById(this.labels.switch.id + '_' + i + 'ch'); //Change the active this.bams.active[i] = (this.bams.active[i] === true)? false : true; //Change the status el.checked = this.bams.active[i]; //Draw the actual region this.Move(); }; //CoverViewer labels done CoverViewer.prototype.LabelsDone = function() { //Hide the labels dialog this.labels.Hide(); }; //CoverViewer labels switch event function CoverViewerLabelsSwitchEvent(_this, _i) { //Add the on click event $('#' + _this.labels.switch.id + '_' + _i).on('click', function(){ _this.LabelsClick(_i); }); } //CoverViewer labels done event function CoverViewerLabelsDoneEvent(_this) { //Add the click event $('#' + _this.labels.done.id).on('click', function(){ _this.LabelsDone(); }); }
import React from "react"; import { useQuery } from "@apollo/react-hooks"; import { useEditionSelector } from "hooks"; import { STATS } from "queries/admin"; import { Heading, Section, } from "components/2020/uikit"; export const DasboardCard = ({ title, icon, items, // [ [left, right], [left, right], ... ] }) => ( <div className="admin--dashboard--card"> <h2 className="header"> {title} <div className={`icon icon--${icon}`} /> </h2> <ul> {items.map(([left, right], i) => ( <li key={i}> <span>{left}</span> <span>{right}</span> </li> ))} </ul> </div> ); export const AdminDashboard = () => { const { selectedEdition, EditionSelector } = useEditionSelector(); const { data } = useQuery(STATS, { variables: { editionId: selectedEdition?.id }}); if (!data) return null; const { adminStats: { events }, edition: { attendances, teams, suffrages }, } = data; return ( <Section> <Heading size="xl">Stats</Heading> <EditionSelector /> <div className="admin--dashboard"> <DasboardCard title={`${attendances.length} Users`} icon="person" items={[ ["Checked in", attendances.filter(a => a.checkedIn).length], ["With team", attendances.filter(a => a.user.currentTeam).length], ["Participants", attendances.filter(a => a.user.role === "participant").length], ]} /> <DasboardCard title={`${teams.length} Teams`} icon="group" items={[ ["Applied" , teams.filter(t => t.applied).length], ["Accepted" , teams.filter(t => t.accepted).length], ["Eligible" , teams.filter(t => t.eligible).length], ]} /> <DasboardCard title={`${suffrages.length} Categories`} icon="how-to-vote" items={suffrages.map(s => [`Teams up for ${s.name}`, s.teams.length])} /> <DasboardCard title={`${events.length} Events`} icon="work" items={events.map(w => [w.name, `${w.participants} / ${w.participant_limit}`])} /> </div> </Section> ); }; export default AdminDashboard;
module.exports = { skipFiles: ['Migrations.sol','test','zeppelin'], providerOptions: { network_id: 5888, //vmErrorsOnRPCResponse: false } };
var Analyzer = (function() { function Analyzer(options) { var defaults = { simplifyTolerance: 10 }; this.opt = _.extend({}, defaults, options); this.init(); } Analyzer.prototype.init = function(){ this.memory = []; this.memoryLimit = this.opt.player.instruments.length; this.mode = 'learn'; // or: listen this.loadMemory(this.opt.points); this.loadListeners(); }; Analyzer.prototype.addToMemory = function(points){ if (this.memory.length >= this.memoryLimit) return false; var index = this.memory.length; this.memory.push({ index: index, distance: 0, weight: 0, count: 1, points: points }); }; Analyzer.prototype.distanceBetween = function(p1, p2) { var distances = []; for (var i = 0; i < p1.length; i++) { var min = -1; for (var j = 0; j < p2.length; j++) { var dis = this._dist(p1[i].x, p1[i].y, p2[j].x, p2[j].y); if (min < 0 || dis < min) { min = dis; } else if (dis == 0) { break; } } if (min >= 0) distances.push(min) } var sum = _.reduce(distances, function(memo, num){ return memo + num; }, 0); return distances.length ? sum / distances.length : 0; }; Analyzer.prototype.loadListeners = function(){ var _this = this; $.subscribe('path.create', function(e, data){ _this.observe(data.points); }); }; Analyzer.prototype.loadMemory = function(points){ var _this = this; _.each(points, function(p){ _this.addToMemory(p); }); }; Analyzer.prototype.normalizePoints = function(points){ var _this = this; var scaleTo = 100.0; var nPoints = []; // console.log('Raw points', points); // translate to (0,0) and scale var xs = _.pluck(points, 'x'); var ys = _.pluck(points, 'y'); var min_x = _.min(xs); var min_y = _.min(ys); var max_x = _.max(xs); var max_y = _.max(ys); var multiplier = scaleTo / _.max([max_x-min_x, max_y-min_y]); _.each(points, function(p){ var n = {}; n.x = _this._round((p.x - min_x) * multiplier, 3); n.y = _this._round((p.y - min_y) * multiplier, 3); nPoints.push(n); }); // simplify the points nPoints = simplify(nPoints, this.opt.simplifyTolerance); return nPoints; }; Analyzer.prototype.observe = function(points){ $.publish('debug.message', ['Processing stroke data', false]); points = this.normalizePoints(points); // console.log('Normalized points', points); if (this.memory.length < this.memoryLimit) { this.addToMemory(points); } // if (this.memory.length >= this.memoryLimit) { // var obj = _.pluck(this.memory, 'points'); // var data = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj)); // window.open(data, "", "_blank"); // } this.processFromMemory(points); }; Analyzer.prototype.processFromMemory = function(points){ var _this = this; points = _.map(points, _.clone); // calculate distance between each path this.memory = _.each(this.memory, function(node, i){ var distance = _this.distanceBetween(node.points, points); node.distance = distance; return node; }); // normalize distances to create weights var ds = _.pluck(this.memory, 'distance'); // console.log('Distances', ds); var min_dist = _.min(ds); var max_dist = _.max(ds); this.memory = _.map(this.memory, function(node){ if (max_dist - min_dist <= 0) node.weight = 0; else node.weight = (node.distance - min_dist)/(max_dist - min_dist); node.weight = 1 - node.weight; return node; }); // find the closest match and tween var closest = _.min(this.memory, function(m){ return m.distance; }); var tweened = this.tween(closest, points, _.max([Math.pow(0.5, closest.count), 0.1])); this.memory[closest.index].count += 1; // this.memory[closest.index].points = tweened; // this.memory[closest.index].points = points; $.publish('debug.message', ['Matched node '+(closest.index+1)+ ' with distance '+closest.distance, true]); $.publish('path.processed', {memory: this.memory}); }; Analyzer.prototype.tween = function(fromPoints, toPoints, amount){ amount = amount || 0.5; var _this = this; var p1 = fromPoints; var p2 = toPoints; var tweened = []; for (var i = 0; i < p1.length; i++) { var min = -1; var min_j = -1; for (var j = 0; j < p2.length; j++) { var dis = this._dist(p1[i].x, p1[i].y, p2[j].x, p2[j].y); if (min < 0 || dis < min) { min = dis; min_j = j; } else if (dis == 0) { break; } } if (min_j >= 0) { var pt = _this.lerp(p1[i].x, p1[i].y, p2[min_j].x, p2[min_j].y, amount); tweened.push(pt); } } return tweened; }; Analyzer.prototype._dist = function(x1, y1, x2, y2) { return Math.sqrt(Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2)); }; Analyzer.prototype._lerp = function(x1, y1, x2, y2, amt) { var nx = x1+(x2-x1)*amt; var ny = y1+(y2-y1)*amt; return {x: nx, y: ny}; }; Analyzer.prototype._round = function(num, dec) { num = parseFloat(num); dec = dec || 0; return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec); }; return Analyzer; })(); $(function(){ var analyzer = new Analyzer(CONFIG); });